Facebook Messenger Bot: Understanding Syntax - 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();
}
};
Now, before trying to figure out what this code does (which she have explained), I am unable to understand why haven't she included any dependencies (precisely express) in this Node.Js file?
[Update] Can someone also please explain me in length what does the above code do?
Since this code looks like NodeJS code, Shouldn't she add something like
var express = require("express");
var app = express();
and do module.exports after?

To summarise the comments under the question:
You must import modules only if you need it. That chunk of code simply exports a function that can be used in any other module by importing it.
The author's just exporting an anonymous es6 arrow function, which is totally legit. It can be imported as
import * as whateverYouNameIt from 'controllers/verification';
or
let func = require('controllers/verification');
Have a look at arrow functions and node.js module exports

Related

When using React Native + Expo, where is the iOS API accessed?

I'm following the Expo tutorial where you build a simple image-sharing application (https://docs.expo.dev/tutorial/image-picker/).
I'm curious where in node_modules is the actual code that accesses the iOS permissions interface.
For example, in app.js I have the following code:
let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
The requestMediaLibraryPermissionsAsync method is located in node_modules/expo-image-picker/build/ImagePicker.js where I find:
export async function requestMediaLibraryPermissionsAsync(writeOnly = false) {
const imagePickerMethod = ExponentImagePicker.requestMediaLibraryPermissionsAsync;
return imagePickerMethod(writeOnly);
}
Going to node_modules/expo-image-picker/build/ExponentImagePicker.js I find:
import { NativeModulesProxy } from 'expo-modules-core';
export default NativeModulesProxy.ExponentImagePicker;
//# sourceMappingURL=ExponentImagePicker.js.map
This is where I'm becoming confused, and I'm not sure how to continue tracing through the modules. I see in node_modules/expo-modules-core/ios/interfaces/Permissions there are objective-c files related to iOS permissions - are these being used in this code example? Where in the code are we actually accessing the iOS API? I have a strong feeling that I'm approaching this question from the wrong angle, so please excuse my ignorance.
I think you have to look at the repository https://github.com/expo/expo/search?q=ExponentImagePicker
Try to find the API names you need.

Using module.exports= router but still getting Router.use() requires a middleware function but got a Object

I looked all over the internet and all I could find was:
"Make sure you add module.exports = router" at the end of your router file.
My router file is as follows:
let router = express.Router();
const staticOptions = {
root: path.join(__dirname, "./../../assets")
};
// a bunch of router.get() functions
module.exports = router;
// auth/google
I then go ahead and import it into my server.ts file as follows:
import * as googleAuthRouter from "./api/AccountLinking/googleAuth";
...
app.use("/auth/google", googleAuthRouter);
but I'm still getting the following error:
TypeError: Router.use() requires a middleware function but got a Object
I only have one route im importing into the server.js file. I barely just started this project. Everywhere I look online says: "you just need to do module.exports = router and it'll fix it." In this case it doesn't. What am i doing wrong?
Typescript is driving me crazy and seriously hindering my development efforts. I'm fairly close to giving up and going back to plain JS
Change import to require:
const googleAuthRouter = require('./api/AccountLinking/googleAuth');
app.use("/auth/google", googleAuthRouter);

Java Script modules initializing function handler

Going through the socket.io's get-started, and I come across a module requirement I can't find clear an explanation of:
var app = require('express')();
var http = require('http').Server(app);
the author describes these lines:
Express initializes app to be a function handler that you can supply to an HTTP server (as seen in line 2)
I haven't found explanations for this usage in any of the documentations for require that I have read. So, what is happening here? Socket.io is irrelevant to my question. It's only referenced to provide a bit of context. Not sure if this is a simple or complex question...
When you require('express'), you are importing something. That something is whatever the Express framework chooses to export. If you look at index.js here, we have the following:
module.exports = require('./lib/express');
Which you can see it just imports from a sub directory of the project. But you can see it specifically imports express.js. By default (shown here), it exports a function called createApplication:
exports = module.exports = createApplication;
/**
* Create an express application.
*
* #return {Function}
* #api public
*/
function createApplication() {
// ...
}
So when you require('express') it will resolve to function createApplication() which is just a function. Which is why you have the extra (), it's just executing/calling the returned function.
See Higher-order function.

How to define export for a module in javascript?

Hey I am doing a small project using react-app and I
have been trying all day to create export for this module.
I have installed it with npm, and i want to edit it so i can import and use it in my app.js
I have tried to define "reddit" using class\function\let and use either:
export default
module.exports
And either
import reddit from 'reddit.js';
var reddit = require('reddit.js');
And trying to check with a simple function from the module:
console.log(reddit.hot('cats'));
But I am still getting:
Uncaught TypeError: reddit.hot is not a function
I am a bit lost, what am I doing wrong?
The module uses window.reddit global variable. Don't override it!
So if you are on client side, just use:
require('reddit.js')
//...
reddit.hot('cats')
For server side - you have to do some trick to make it work, because on server side you don't have 'window' global variable.
Upd:
Example of back end usage:
const window = {};
const r = require('./reddit.js') // You don't really use r
const reddit = window.reddit;
reddit.hot('cats')
Reddit does not export anything because it was mainly designed to be added as a script tag!
// So for CommonJS module:
require('reddit.js');
//And for ES6 modules
import 'reddit.js';
And you you will be able to access reddit and reddit.hot() method through the window object.

node.js variable scope with routes separation

my routes are defined in an external folder
./routes
here's the way i define the routes in my server.js file
app.get('/', routes.index);
app.post('/validation', register.valid);
the register.valid module, which is originally written in
./routes/validation.js
is responsible for creating a new user account and register it into a database (MongoDB).
How can i access an object from server.js in validation.js ? First, i thought declaring the object before defining my routes would resolve the case, but actually it doesn't seem to be the solution.
I'm assuming your current code already does work (that is, you receive the posted data), but you need access to another object from validation.js.
If your code works, then you probably have this line in server.js:
var register = require('./routes/validation');
And you need acess to the variable obj in the validation module. You could have a function inside the validation module:
var foo;
exports.configure = function(obj) {
foo = obj;
}
The exports mean the variable configure will be accessible to modules which "require" the validation module. This way you can do, inside the server.js module:
register.configure(obj);
app.post('/validation', register.valid);
The exact configuration of this will depend on what you are actually trying to accomplish. Sometimes, for example, it's good to have a database object stored in a global variable.
Generally in this kind of structure server.js will create the app object and then pass that to individual routes modules via a function. I do it by having each router module export a single function like this:
//routes/validation.js
function setup(app) {
app.get(....blah
app.post(....blah
}
module.exports = setup;
Then I tie that together in server.js like this:
//server.js
var express = require('express');
var app = express();
require('./routes/validation')(app);
See also my express_code_structure sample project for other code organization tips.

Categories