Function call in external file in Nodejs

Asked

Viewed 468 times

0

I previously had a single file called aaa.js where there was the following code part below, and separated into parts:

const callback = (err, data, res) => {
    if (err) return console.log('ERRO: ', err);
    res.writeHead(200, {'Content-Type': 'application/json'});
    return res.end(JSON.stringify(data));
};
const getQuery = (reqUrl) => {
    const url_parts = url.parse(reqUrl);
    return querystring.parse(url_parts.query);
};
const find = (req, res) => {
    const query = getQuery(req.url);
    MeuObjeto.find(query, (err, data) => callback(err, data, res));
};
const CRUD = {
    find
};
module.exports = CRUD;

After doing code separation to organize better, I created four different files as follows:

aaa.js

const find = require('./../actions/action-find')(MeuModel);
const CRUD = {
    find
};
module.exports = CRUD;

find js

module.exports = (MeuModel) => {
    return (req, res) => {
        const query = getQuery(req.url); // <========= Como fica essa chamada?
        MeuModel.find(query, (err, data) => callback(err, data, res)); // <========= Como fica essa chamada?
    };
};

callback.js

module.exports = (err, data, res) => {
    if (err) return console.log('ERRO: ', err);
    res.writeHead(200, {'Content-Type': 'application/json'});
    return res.end(JSON.stringify(data));
};

get-query.js

module.exports = (reqUrl) => {
    const url_parts = url.parse(reqUrl);
    return querystring.parse(url_parts.query);
};

DOUBT: How do I call the functions "callback" and "get-query" from within the "find.js" file as pointed out in the code comment?

1 answer

0


const query = require('get-query')(url);
let callback = require('callback')(err, data, res);
MeuModel.find(query, (err, data) => callback;

When Voce wants to call another file Voce uses the require with its name (without the .js because it is calling the module), and passes the parameter that is used in the function of the other file in the next parentheses.

As functions can be stored in variables, give a require in function and then pass it pro callback, this second case I am not 100% sure (if anyone can confirm with comment Agradeco)

  • I couldn’t test this example of yours to see if it worked. I built some codes to simulate, but none worked, although I think your answer seems to be the right one. I don’t know how to solve...

  • @wBB what prevents you from testing? just change the code, I used your variables

  • What kept me from testing was knowing how to test correctly. Hence the opening of the topic... Now I got it: const find = require('./action-get-query-http')(MeuValor, MeuSegundoParam); and in the archive get-query stays module.exports = (Param1, Param2) => { return Param1 + ' ' + Param2; };. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.