Answer the question
In order to leave comments, you need to log in
How to break nodejs into modules and pass values to them when require?
I am writing a simple REST API on Nodejs - everything is in one file so far. I decided to move the bans to files under the headings:
tasks.js file
module.exports = function(app, db) {
app.get('/tasks', (req, res) => {
let findParams = {};
if (req.query.category) {
findParams.category = {};
findParams.category.$in = req.query.category.split(' ');
}
if (req.query.importance) {
findParams.importance = {};
findParams.importance.$in = req.query.importance.split(' ');
}
if (req.query.cost) {
findParams.cost = {};
let cost = req.query.cost.split(' ');
if (cost.indexOf('free') != -1 && cost.indexOf('paid') == -1) {
findParams.cost.$eq = 0;
}
if (cost.indexOf('free') == -1 && cost.indexOf('paid') != -1) {
findParams.cost.$gt = 0;
}
if (cost.indexOf('free') != -1 && cost.indexOf('paid') != -1) {
findParams.cost.$gte = 0;
}
}
// if (err) throw err;
db.collection('tasks').find(findParams).toArray((err, results) => {
res.send(results);
});
});
};
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cors());
var db;
MongoClient.connect('mongodb://xxxxxxxxxxxxxxxxxxxxx/swq', (err, database) => {
if (err) {
return console.log(err);
};
db = database;
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function () {
console.log('Node app is running on port', app.get('port'));
});
});
require('./tasks')(app, db);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question