Facebook Messenger Bot: Understanding Export Arguments - javascript

I am trying to learn how to create a facebook Bot.
I found this amazing article on Medium which illustrates how we can create a messenger bot
In this article, The author tells us to create a verification.js. file inside controllers/verification.js. and paste the following code in it.
module.exports = (req, res) => {
const hubChallenge = req.query[‘hub.challenge’];
const hubMode = req.query[‘hub.mode’];
const verifyTokenMatches = (req.query[‘hub.verify_token’] === ‘crowdbotics’);
if (hubMode && verifyTokenMatches) {
res.status(200).send(hubChallenge);
} else {
res.status(403).end();
}
};
This, I understand to be ES6 Anonymous function which executes immediately? And since we aren't doing anything like
var express = require("express");
var app = express();
I am assuming it to be simple Vanilla JavaScript file. Now in our app.js we just import like this const verificationController = require("./controllers/verficiation.js")
Now, The question which is bothering me is that how did we passed the arguments to this module.exports = (req, res) => {

Without reading the article or knowing anything about that bot, I assume you are going to use verificationController as middleware to an express route, like this:
app.get("/", verificationController, (req, res) => {...});
This will pass req and res as parameters to the function

Related

Possible to use router.param() inside a nested router in express.js?

I'm working on a code challenge and trying to challenge myself to make something that works as well as something that is well organized.
I have a router set up and functioning. This router in turn uses an additional router. All is working so far. Now I am trying to run router.param() to preform some logic in the child router using the parameter that comes from the parent router. I have included {mergeParams: true} when creating the child router.
I would like to run additional logic using the parameter for all http methods in the child router, but don't seem to be able to. Can I not use router.param() for this purpose? I also seem to not have access to req.minion in the child router (which was attached using router.param() in the parent).
Alternatively is there a way to carry over logic from the router.param() in the parent router to the child router?
Parent router
const {getFromDatabaseById, getAllFromDatabase} = require('./db');
const express = require('express');
const workRouter = require('./workRouter.js');
const minionsRouter = express.Router();
minionsRouter.use('/:minionID/work', workRouter);
minionsRouter.param('minionId', (req, res, next, minionId) => {
const minion = getFromDatabaseById('minions', minionId);
if(minion){
req.minion = minion;
next();
}else{
res.status(404).send();
}
});
minionsRouter.get('/', (req, res, next) => {
res.send(getAllFromDatabase('minions'));
});
minionsRouter.get('/:minionId', (req, res, next) => {
res.send(req.minion);
});
//Some additional http methods here
module.exports = minionsRouter;
Child router
const {getAllFromDatabase} = require('./db');
const express = require('express');
const workRouter = express.Router({mergeParams: true});
workRouter.param('minionId', (req, res, next, minionId) => {
const allWork = getAllFromDatabase('work');
const minionWork = allWork.filter(work => work.minionId === minionId);
console.log(minionWork);
if(minionWork){
req.minionWork = minionWork;
next();
}else{
res.status(404).send();
}
});
workRouter.get('/', (req, res, next) => {
res.send(req.minionWork);
});
//Some additional http methods here
module.exports = workRouter;
The get methods in the parent router work perfectly, and the get method in the child router works if I move the logic in the router.param() call to it, but as is it does not seem to attach minionWork to req. If router.param() won't work for this, how can I avoid repeating that code for all http methods in the child router? Thanks!

node.js express and regular expressions

Hi friends I am working with node.js and express. I have some endpoints and inside there are dynamic files every file have a name of an IP for example services/192.168.0.1.html, service/192.168.0.11.html, service/192.168.0.15 etc. So I want to make a dynamic route like this code:
app.get('/endpointej/**REGEXP**forIP.html', (req, res) => {
var ruta = {
root: path.join(__dirname + 'endpoint/)
}
res.sendFile("IPfiledinamic.html",ruta)
});
Can some one help me out please ?
Regards
You can use something like
// route is for GET /test/1.1.1.1.html, but not for GET /test/1.2.3.html
app.get(/test\/([0-9]{1,3}\.){3}[0-9]{1,3}\.html/, (req, res) => {
const ipRegex = /^\/test\/((?:[0-9]{1,3}\.){3}[0-9]{1,3})\.html$/
// do more here...
res.status(200).send(`matches, ${req.url.match(ipRegex)}`)
})

How to import object to another file?

I'm using Node.js to build a web application.
I have two files. Server.js - where I call the server to go online etc. And the other one is a file which includes a big object with data. I imported the file with data into server.js, I get the object in postman when I set the website to be live. But I can't dive inside the object to get the data inside the object. The error I'm getting says that the variable where my data is stored is not defined.
I think the fix is to import albumsData variable into server.js, but im completely stuck and can't find how to do it. If anyone has any idea, please share.
albumsData.js
const express = require('express');
const router = express.Router();
let albumsData = {
filled with data
}
router.get('/albumData', (req, res) => {
res.send(albumsData);
});
module.exports = router;
Server.js
app.use(require('./api/albumData/unikkatilData'))
app.use((req, res) => {
res.status(404)
.send(albumsData)
});
app.listen(4000, () => {
console.log('hello worldd')
})
If you want the albumsData object then you can do it like this:
In you albumsData.js file:
const albumsData = {
// Bunch of data
}
module.exports = albumsData
Then in your server.js file:
const albumData = require('./api/albumsData') // Make sure this path points directly to the albumsData.js file
move enter code here to new file (ex utils.js)
and export it exports.albumsData = albumsData; then you can call it
with const utils = require('./utils') ; utils.albumsData

Get middleware mount point from request in Express

I have an Express application with a router, here is the example of the router:
const router = require('express-promise-router')();
const users = require('./users');
const validate = require('./validate');
router.get('/users', users.list);
router.get('/users/:id', users.get);
// other routes here
module.exports = router;
Now I want to add a middleware that validates each query, like that (this is not the working example, it's just to show the idea of what I want to accomplish):
const schemas = {
'/users': 'some validation schema',
'/users/:id': 'another validation'
}
module.exports = (req, res, next) => {
const url = req.originalUrl; // This is where I'm stuck.
if (!schemas[url]) {
// throw new error that validation failed
}
// validating somehow
if (!req.validate(schemas[url])) {
// throw new error that validation failed
}
return next();
}
And for this, I need to get the middlelware mount folder (like '/users/:id' for '/users/557'). I've tried to use req.originalUrl, but it returns the full URL path instead of the mount folder.
How can I achieve this? And if there's no way, how can I write my validation middleware another way to make it work?
Inside req.route you will get the path of API.
Check this screenshot

Koa pass data from server to client

I want to pass through some environment variables from a Koa server to the client. In express I could do something like res.render('index', { data: 'someData' }); and then I could access data. In Koa I can't see how to do this. It mentions using context.state but I can't find any example of how to retrieve this in the client.
You can do something similar in Koa, you just need to use the right middleware. Try out koa-views if you're using one of the supported engines.
Here is a full example (this example assumes you're using Koa v1 and EJS as your templating engine):
app.js
const Koa = require('koa')
const views = require('koa-views')
const router = require('./routes')
const app = new Koa()
app.use(views(__dirname + '/views', { extension: 'ejs' }))
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)
routes.js
const router = require('koa-router')()
router.get('/', function * () {
yield this.render('index', { title: 'Home' })
})
router.get('/about', function * () {
yield this.render('about', { title: 'About' })
})
module.exports = router
Just change the extension argument you pass to the middleware based on which templating engine you are using.

Categories