Passing references to express-resources in node.js? - javascript

How can I pass for example the database reference
nano = require('nano')('http://127.0.0.1:5984')
db = nano.use('database')
to a resource 'User' (loaded with express-resource)?
I tried:
app.resource('user', require('./routes/user'), {db: db});
But that doesn't work.

You want to pass db to the user.js routing file. What you are doing is passing it to the app.resource function.
app.resource('user', require('./routes/user')(db));
You will have to wrap your user.js file in a function that can receive db as a parameter.
module.exports = function(db) {
return {
index: function(req, res) {}
, new: function(req, res) {}
, create: function(req, res) {}
// etc
};
};
If you don't like the way this is structured, you can also use a middleware.
app.use(function(req, res, next) {
req.db = db;
next();
});

Related

creating dynamic routes using nodejs

app.js
// Calling Routes
require("./routes")(app);
router folder
index.js
module.exports = function (app) {
app.use("/", require("./all_routes"));
}
all_routes.js
var express = require("express");
var router = express.Router();
router.get("/", function (req, res, next) {
res.render("home/index.html");
});
//About Page
router.get("/about", function (req, res, next) {
res.render("about/index.html");
});
//Contact
router.get("/contact", function (req, res, next) {
res.render("contact/index.html");
});
//product
router.get("/product", function (req, res, next) {
res.render("product/index.html");
});
//product list
router.get("/product/demo-product", function (req, res, next) {
res.render("demo-product/index.html");
});
router.get("/product/request-product", function (req, res, next) {
res.render("request-product/index.html");
});
//service
router.get("/service", function (req, res, next) {
res.render("product/index.html");
});
//service list
router.get("/service/what-we-do", function (req, res, next) {
res.render("what-we-do/index.html");
});
router.get("/service/how-we-do", function (req, res, next) {
res.render("how-we-do/index.html");
});
I am trying to reduce the code in all_routes.js file has same code is repeating again and again
I searched online and trying to create it dynamically but getting no success is there any way I can reduce the line of code as I have given the follow of my code above
If you'd like to cut down on boilerplate of all your get routes, one option is to create an object to map your routes to the files they're loading. Then you can iterate over that object and add the routes to your router.
const routes = {
"/": "home/index.html",
"/about": "about/index.html",
"/contact": "contact/index.html"
// Add others here
}
for (let key in routes) {
router.get(key, function (req, res, next) {
res.render(routes[key]);
});
}
Edit: If your routes are consistent in that the index.html file will always be in the directory named after the part after the last / in your route, you can potentially use an array and some fancy logic. Just don't break the rule!
const routes = [
"/contact",
"/product",
"/product/demo-product",
"/product/request-product"
]
routes.forEach(route => {
const path = /[^/]*$/.exec(route)[0];
router.get(route, function (req, res, next) {
res.render(`${path}/index.html`);
});
})

Passing JSON to Jade and using the same data for API access

I have the following code as a schema module:
router.get('/', function(req, res) {
Module.find(function (err, modules) {
if (!err) {
return res.json(modules);
} else {
res.statusCode = 500;
log.error('Internal error(%d): %s', res.statusCode, err.message);
return res.json({
error: 'Server error'
});
}
});
});
And this works fine for my API, but I'm also trying to use this data to load it into my Jade template.
var modules = require('./routes/modules');
// home page
app.get('/', function(req, res) {
res.render('index', { modules: modules })
});
app.use('/api/modules', modules);
But this just doesn't work, it gives me undefined as if it doesn't exist (when logged).
If I modify my router to the following:
res.render('index', {
modules: modules
})
It works fine for getting the data but not when accessing it through my API.
So my question, how can I use this particular piece of code for my API and for rendering it to the Jade template.
Your use of modules as the middleware is not correct. i.e.
app.use('/api/modules', modules);
As specified in the http://expressjs.com/en/guide/using-middleware.html, your middleware should call the next() function.
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
To solve this, you should define your route similar to the index route, but you will use res.send.
var modules = require('./routes/modules');
// home page
app.get('/', function(req, res) {
res.render('index', { modules: modules })
});
app.get('/api/modules', function(req, res) {
res.send({ modules: modules })
});

How to pass arguments into an outside module?

I have the following function that I placed inside a separate js file.
I am trying to use it inside another javascript file that requires passport.js, and I would like to call it using app.use to further modularize my application
var express = require('express');
var router = express.Router();
/* GET welcome page. */
router.get('/home', isLoggedIn, function(req, res, next) {
res.render('home', {
title: 'title',
user : req.user
});
});
// route middleware to make sure
function isLoggedIn(req, res, next) {
// if user is authenticated in the session
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
The reason I created it is so I reduce redundancy and not use the following code each time:
app.get('/home', isLoggedIn, function(req, res) {
res.render('home.ejs', {
user : req.user // get the user out of session and pass to template
});
});
However I can't seem to get it to work. is authenticated is undefined although it is in the same folder, and it gives me an error 404 not found when I issue a get. How I can keep it in an external file and still use it? should I also pass it the user argument from where I am calling it?
var express = require('express');
var router = express.Router();
module.exports = function (app, passport){
router.get('/home', isLoggedIn, function(req, res, next) {
res.render('home', {
title: 'title',
user : req.user
});
});
return router;
};
function isLoggedIn(req, res, next) {
// if user is logged in -
if (req.isAuthenticated())
return next();
// if they aren't redirect them to home
res.redirect('/');
}

node.js express routing db dependent

What i'm trying to do:
If the url exists in the db use static page template, if not, display specific page template. Can't seem to figure out, how too...
My app.js file
app.get('*', function(req, res){
var currenturl = req.url;
console.log('URL IS: ' + my_path)
if (!!db.get(my_path) )
{
//If it does exist in db
console.log('Does exist');
res.render('index', { thetitle: 'Express', title: db.get(currenturl).title, content: db.get(currenturl).content });
}else{
//If it doesn't exist in db
redirect to other sites
Like:
if you go to "/page" it will run this => app.get('/page', routes.index)
or "/users" will run => app.get('/users', routes.users)
}
});
You have to create your own simple middleware. Just make sure you put it above the express.router
app.use(function(req, res, next){
if (!!db.get(my_path)) {
// render your site from db
} else {
// call next() to continue with your normal routes
next();
}
});
app.get('/existsInDB', function(req, res) {
// should be intercepted by the middleware
})
app.get('/page', function(req, res) {
// should not be intercepted
res.render('page')
})
using express is easy. you can use the redirect function:
if (url_exists) res.render('index');
else res.redirect('/foo/bar');

javascript adding a value to function arguments

I'm trying to add an argument to a function passed along as an argument in an express js route.
This is an expressjs route:
app.get('path', someFunc,
function(req, res, next) {
res.render('layout');
});
The function someFunc right there takes the arguments req, res, next.
I want to add an additional argument to it. If I use apply or call it seems to replace all the existing arguments.
I want to be able to do:
someFunction (req, res, next, custom) {}
How can I do this? Thanks.
I am not sure that this is the best way but you could do something like this :
var someFunc = function (req, res, next, custom) { console.log(custom); next(); }
app.get('path',
function (req, res, next) { someFunc(req, res, next, 'custom') },
function(req, res, next) {
res.render('layout');
});
I would create a route like this:
// Inside your routes.js:
module.exports.someRoute = function(myArgument) {
return function(req, res, next) {
// Do whatever you want with myArgument.
};
};
// Inside your app.js:
app.get('path', routes.someRoute({ foo: 1 }));
This way your route setup is clear of any logic.

Categories