Fastify point-of-view local variables - node.js

I am switching from Express.js to Fastify. I need to do it quickly, so using only API is impossible yet. Haven't written React app.
My problem is: I am using point-of-view and I don't know how to pass local variable to all requests. In express there something like
app.use(function (req, res, next)
{
res.local.new_notifications = 50;
})
and I can get it in template engine on every page like
<%= new_notifications %>
Is there something like this in Fastify + point-of-view?

You can, I am not sure if it is a new implementation or not since you asked a solution more than 1 year ago, this is for future viewers.
You simple have to add a .locals object and attach to it anything you want available with your engine.
This is from the documentation:
If you want to provide data, which will be depended on by a request and available in all views, you have to add property locals to reply object, like in the example below:
fastify.addHook('preHandler', function (request, reply, done) {
reply.locals = {
text: getTextFromRequest(request) // it will be available in all views
}
done()
})
Be sure to create the object with the assignment {} since locals its not defined!

Related

Expressjs higher order router vs appending to request

Let's say I want to pass to an ExpressJS route callback an object.
I know I can append to app:
// router.js
const getFoo = (req, res) => res.json(req.app.foo);
// index.js
const app = express();
app.foo = {};
app.get('/foo', getFoo);
or I can use a higher order function:
// router.js
const getFoo = foo => (req, res) => res.json(foo);
// index.js
const app = express();
const foo = {};
app.get('/foo', getFoo(foo));
Both are easy to write, extend and test.
But, I don't know the implications of the solutions and whether one is better.
Is there anyone knowing real differences between the two approaches?
I think the second solution is more correct, here's why.
imagine you get used to the first solution and one day you need to send something called post or get or anything with the name of app property and you forget that there is already a property named like that, so you override original property without even realizing and when you call app.post() program will crash.
Believe me, you don't want hours of research wasted on something like that and realizing that you simply overrode original method
Also, in my opinion, it's always a bad idea mutating original object which wasn't generated by you
As #vahe-yavrumian mentioned it is not a good idea to mutate the state of the object created by a third party library.
between you can also use app.get() and app.set() methods to pass any data to the other routers in the queue (seems those methods are there just for this purpose.)
more information at https://expressjs.com/en/api.html.
The second solution easily allows you to pass different value for foo on different routes, if you ever found a need to do that.
The first solution essentially puts the value on the app singleton, which has all the implications of using singletons. (And as mentioned by #Anees, for express specifically the app settings with get and set are the proper place to store this, not a custom property)

Koa-router getting parsed params before hitting route

I'm using koa2 and koa-router together with sequelize on top. I want to be able to control user access based on their roles in the database, and it's been working somewhat so far. I made my own RBAC implementation, but I'm having some trouble.
I need to quit execution BEFORE any endpoint is hit if the user doesn't have access, considering endpoints can do any action (like inserting a new item etc.). This makes perfect sense, I realize I could potentially use transactions with Sequelize, but I find that would add more overhead and deadline is closing in.
My implementation so far looks somewhat like the following:
// initialize.js
initalizeRoutes()
initializeServerMiddleware()
Server middleware is registered after routes.
// function initializeRoutes
app.router = require('koa-router')
app.router.use('*', access_control(app))
require('./routes_init')
routes_init just runs a function which recursively parses a folder and imports all middleware definitions.
// function initializeServerMiddleware
// blah blah bunch of middleware
app.server.use(app.router.routes()).use(app.router.allowedMethods())
This is just regular koa-router.
However, the issue arises in access_control.
I have one file (access_control_definitions.js) where I specify named routes, their respective sequelize model name, and what rules exists for the route. (e.g. what role, if the owner is able to access their own resource...) I calculate whether the requester owns a resource by a route param (e.g. resource ID is ctx.params.id). However, in this implementation, params don't seem to be parsed. I don't think it's right that I have to manually parse the params before koa-router does it. Is anyone able to identify a better way based on this that would solve ctx.params not being filled with the actual named parameter?
edit: I also created a GitHub issue for this, considering it seems to me like there's some funny business going on.
So if you look at router.js
layerChain = matchedLayers.reduce(function(memo, layer) {
memo.push(function(ctx, next) {
ctx.captures = layer.captures(path, ctx.captures);
ctx.params = layer.params(path, ctx.captures, ctx.params);
ctx.routerName = layer.name;
return next();
});
return memo.concat(layer.stack);
}, []);
return compose(layerChain)(ctx, next);
What it does is that for every route function that you have, it add its own capturing layer to generate the params
Now this actually does make sense because you can have two middleware for same url with different parameters
router.use('/abc/:did', (ctx, next) => {
// ctx.router available
console.log('my request came here too', ctx.params.did)
if (next)
next();
});
router.get('/abc/:id', (ctx, next) => {
console.log('my request came here', ctx.params.id)
});
Now for the first handler a parameter id makes no sense and for the second one parameter did doesn't make any sense. Which means these parameters are specific to a handler and only make sense inside the handler. That is why it makes sense to not have the params that you expect to be there. I don't think it is a bug
And since you already found the workaround
const fromRouteId = pathToRegexp(ctx._matchedRoute).exec(ctx.captures[0])
You should use the same. Or a better one might be
var lastMatch = ctx.matched[ctx.matched.length-1];
params = lastMatch.params(ctx.originalUrl, lastMatch.captures(ctx.originalUrl), {})

Node.js / Express - modifying response template context through request/response objects

I am using Express to serve web pages in node.js application.
Let's say I want to have a variable foo available in all views rendered by render method of response object. I know that I can define dynamic helpers for this task. However, I found them unsuitable when you need to set helper variable asynchronously like this (Mongoose example):
Thing.count(filter, function(error, thingCount) {
foo = thingCount;
}
I've tried using connect middleware approach, which suits me perfectly, however the question here is how to affect the response context. By looking into render method definition in express/lib/view.js I've found that it can be manipulated by writing into app._locals object:
function putFooIntoContext (req, res, next) {
Thing.count(filter, function(error, thingCount) {
res.app._locals.foo = thingCount;
next();
}
}
It works as intended, however, I am a bit afraid that such straightforward approach is not the best solution. Can someone give me any ideas how to affect response context by interacting only with request/response objects in proper way designed by Express developers?
Express 3.x allows for asynchronous helpers to be utilized in the form of 'app.use'. So for a simple global 'foo' variable, your code would be as follows:
app.use(req, res, next) {
Thing.count(filter, function(error, thingCount) {
res.locals.foo = thingCount;
next();
});
}
Of course the middleware option is also valid, this is just another viewpoint and saves inserting the middleware per each app.get(....)

How do I pass variables from Connect's middleware into app.get-action?

I would like to create kind of a before filter which allows me to make the current user available in all actions. The followint approach works well and I didn't even need to declare a global variable:
app.use(function(req, res, next){
if(req.session.user_id){
/* Get user from database
and share it in a variable
that can be accessed frooom ...
*/
User.find({ /* ... */ }, function(err, users){
if(users.length == 1){
req.current_user = users[0];
}
next();
});
}
else{
next();
}
});
app.get('/', function(req, res){
// ... here!!
console.log(req.current_user);
res.render('index', {
current_user: req.current_user,
});
});
But I'm still unsure if it is okay to manipulate req because I don't know if it's right to change something that's not owned by me? Is there a better way to do this?
Go right ahead and tack on properties to req! When I was first starting out with Node.js and JavaScript, this felt very odd to me too (coming from a predominately C++ background). It is, however, quite natural given JavaScript's prototypical object model. After you get comfortable with it, you'll realize that you can do powerful things in succinct code.
I'm the developer of Passport (mentioned by the previous commenter). If you are planning on developing middleware that can be reused across apps, my advice is to pay a bit of attention to how you name the properties that you add to req or res, to avoid any potential conflict with other middleware in the same application.
For example, Passport sets the user at req.user, but gives an option to change that (so an app can say set it at req.currentUser, for example.). Internal, private variables are attached to a req._passport property.
It's a common approach to extend req with session or user object
For example see these examples:
Passport, a popular authentication library https://github.com/jaredhanson/passport/blob/master/lib/passport/strategies/session.js
Connect middleware for cookie session https://github.com/senchalabs/connect/blob/master/lib/middleware/cookieSession.js

Render template to variable in expressjs

Is there a way to render template to a variable instead to output?
res.render('list.ejs', {
posts: posts
});
something like this
var list = render('list.ejs', {
posts: posts
});
The easiest way to do that is to pass a callback to res.render, in your example:
res.render('list.ejs', {posts: posts}, function(err, list){
//
});
But if you want to render partial templates in order to include them in another template you definitely should have a look at view partials.
I am quite a newbie on express.js, anyway I am not sure you can access the rendered string that way, although if you look at express' "view.js" source on github (here) you see that it's accepting a callback as second argument, if that may help: you may access the rendered string there.
Otherwise, I think it's quite easy to patch the code to add a method returning the rendered string without sending it: on line #399 you have the very call that gives the string you are looking for.
This wasn't the question originally asked, but based on comments from the OP and others, it seems like the goal is to render a partial via json (jsonp), which is something I just had to do.
It's pretty easy:
app.get('/header', function (req, res)
{
res.render('partials/header', { session: req.session, layout: null }, function (err, output)
{
res.jsonp({ html: output });
});
});
Note: In my case, the header partial required the session, and my template library (express-hbs) needed layout: null to render the partial without using the default layout.
You can then call this from Javascript code in the client like any other JSONP endpoint.

Resources