In a sails.js application is there a simple way of including express-middleware?
For instance extending the request object with express-validator.
Adding express-middleware in a sails application is simple.
create a new policy.
policies
|_
middleware.js / .coffee
Add Express MiddlewareYOUR_MIDDLE_WARE_FILE_NAME.js
Inside your middleware file we create the standard export for node.js
module.exports = require('middle-ware')(OPTIONS_GO_HERE) // See middleware docs for configuration settings.
Then once you have created the middleware you can apply it to all requests or a single controller by following the Sails.js convension.
Entire Applicationpolicies.js
module.exports.policies = {
'*':['middleware'] // node same name as file without extention
}
Single Controller Action policies.js
module.exports.policies = {
RabbitController:{
feed:['middleware']
}
}
First of all, #SkyTecLabs' answer is the proper way to do this. But I wanted to add that, in some cases, you may need to control your static files (images, client-side javascript, css, etc) as well (I just had to deal with this recently). In this case, you can apply middleware generically to every route.
As of Sails.js v0.9.3, you can do:
// Put this in `config/express.js`
module.exports.express = {
customMiddleware: function (app) {
app.use(require('../node_modules/sails/node_modules/express').basicAuth('balderdash', 'wickywocky'));
}
};
More here: https://gist.github.com/mikermcneil/6255295
In the case where you want middleware to run before one or more of your controllers or actions, you're definitely better served using the policy approach though!
Related
In Fastify I can specify instance options while creating it, e.g.
const fastify = require('fastify')({logger:true, disableRequestLogging: false});
Is it possible to do this in a middleware registered with the instance?
e.g. if I do something like
fastify.register(myPlugin);
and instance of fastify is passed to myPlugin - can I, for example change its disableRequestLogging value while in the middleware?
The router is the what relies on disableRequestLogging to switch on/off logging for the request and the later response.
if (disableRequestLogging === false) {
childLogger.info({ req: request }, 'incoming request')
}
The router does provide a setup function that allows disableRequestLogging to be changed. You can see fastify.js uses router.setup() late in initialisation here to apply some new values.
The problem is fastify doesn't provide access to router as part of it's public API. Only functions like fastify.get/.post/.route etc which allow access to specific components of the router.
Short of modifying the source, I can't see a way. Not even something dodgey like onkeypatching a function in due to the way fastify variables are scoped. Even if you could do that, it would be delving into undefined/untested behaviours.
I want to extend this open topic: Add Routes at Runtime (ExpressJs) which sadly didn't help me enough.
I'm working on an application that allows the creation of different API's that runs on NodeJs. The UI looks like this:
As you can see, this piece of code contains two endpoints (GET, POST) and as soon as I press "Save", it creates a .js file located in a path where the Nodejs application is looking for its endpoints (e.g: myProject\dynamicRoutes\rule_test.js).
The problem that I have is that being that the Nodejs server is running while I'm developing the code, I'm not able to invoke these new endpoints unless I restart the server once again (and ExpressJs detects the file).
Is there a way to register new routes while the
NodeJs (ExpressJs) is running?
I tried to do the following things with no luck:
app.js
This works if the server is restarted. I tried to include this library (express-dynamic-router, but not working at runtime.)
//this is dynamic routing function
function handleDynamicRoutes(req,res,next) {
var path = req.path; //http://localhost:8080/api/rule_test
//LoadModules(path)
var controllerPath = path.replace("/api/", "./dynamicRoutes/");
var dynamicController = require(controllerPath);
dynamicRouter.index(dynamicController[req.method]).register(app);
dynamicController[req.method] = function(req, res) {
//invocation
}
next();
}
app.all('*', handleDynamicRoutes);
Finally, I readed this article (#NodeJS / #ExpressJS: Adding routes dynamically at runtime), but I couldn't figure out how this can help me.
I believe that this could be possible somehow, but I feel a bit lost. Anyone knows how can I achieve this? I'm getting a CANNOT GET error, after each file creation.
Disclaimer: please know that it is considered as bad design in terms of stability and security to allow the user or even administrator to inject executable code via web forms. Treat this thread as academic discussion and don't use this code in production!
Look at this simple example which adds new route in runtime:
app.get('/subpage', (req, res) => res.send('Hello subpage'))
So basically new route is being registered when app.get is called, no need to walk through routes directory.
All you need to do is simply load your newly created module and pass your app to module.exports function to register new routes. I guess this one-liner should work just fine (not tested):
require('path/to/new/module')(app)
Is req.params enough for you?
app.get('/basebath/:path, (req,res) => {
const content = require('content/' + req.params.path);
res.send(content);
});
So the user can enter whatever after /basepath, for example
http://www.mywebsite.com/basepath/bergur
The router would then try to get the file content/bergur.js
and send it's contents.
I am having two controllers, SocketController and ProjectController
SocketController has method getData(data)
ProjectController has method addProject(data)
I need to call addProject() from getData() method.
I tried using sails.controllers.ProjectController.addProject(data) but I got following error:
Cannot find method addProject of undefined
I searched for alternative ways to call another controller using services in Stack Overflow but that was of no help to me. Is there any other way to get this work?
Controllers are just Node modules that export public methods. You can require them like anything else. So assuming your methods are correctly exposed with module.exports, this will work:
/* ProjectController */
module.exports = {
addProject: function(data) {
// ...
}
};
/* SocketController */
// Assuming ProjectController.js exists in the same directory (default for Sails)
var projectController = require('./ProjectController');
module.exports = {
index: function(req, res) {
// ...
projectController.addProject(...);
}
};
Edit: I will add that using services is a better place to keep common functionality like your example. Services allow complex logic to be decoupled from the controller layer and reused by other areas of the application with ease. Controllers should generally be reserved for handling HTTP requests from the client and passing the data to the service or model layers for manipulating the database. I believe Sails also makes services global by default so you don't have to worry about confusing require paths.
Controller functions are also accessible through the global sails object, without use of require, however a function from ProjectController will be found under:
sails.controllers.project.addProject
instead of
sails.controllers.ProjectController.addProject
Anyways you might want to consider having shared functionality in either services or models, as was pointed out previously.
By "setting" I mean "something that is set", similar to "setters" in Java & other OO languages, not Express's "application settings". Is there a way to access and ideally use "settings" set inside middleware use()d by the app? In particular, some middleware is a full Express app, like vhost and the new Router middleware that comes with Express 4.x. If you do most of your routing in a virtual host and want to access some route param from the main app, that could be a problem. This is especially true if you have several layers, like I'm having, and it would be inconvenient to export the setting all the way out to the main app.
So is there a way to access these settings from the main app?
In particular, some middleware is a full Express app
Express 4.x has a great new feature to get around this problem. You can now use express.Router directly. In cases where you used to use an entire routing path by using a second sub-Express object as middleware, now you can just use Router.
For anything else, I usually add properties to the request object, namespaced by the name of my app.
function (req, res, next) {
req.myApp = req.myApp || {};
req.myApp.someData='whatever';
next();
}
The next middleware in the line will have access to this variable. I use this to track unique connection IDs, assigned by the first piece of middleware and subsequently used by others.
I'm facing the following situation. In order to further modulize my software development, I've written a few standard modules stand alone. Think for instance of an login module based upon Express and Passport, allowing users to login with all kinds of social services. The module also contains UI for user management, login, registration, profile, etc.
Now, the thing I'm trying to do is to just drop the Auth app folder (containing the express app, all it's routes, views, models, settings and dependecies) into another Express app (for instance, a CMS) and then load it with something like require('./lib/auth/app.js'). I know this is possible, take a look at Kue.
How would I go about doing this? And how do I manage namespacing problems? I could of cours append /auth/ to each route, but I can imagine the settings (app.use()'s) and public folder would conflict with the 'parent' app.js' settings and public folder.
Thanks in advance,
Fabian
Think I found my answer. So, I found this question, and this one. Guess my terminology was off.
I solved my problem by doing a few things. First of all, I changed all routes and url's to be "namespaced" (not really, but this does the job). All routes now have /auth/ in front of them. I did the same to all links, so that's all working.
Next, I removed the server part from my app.js. So, in stead of doing:
require('http').createServer(app).listen(app.get('port'));
I just do:
module.exports = app;
And I add some custom methods to the app object:
app.isLoggedIn = auth.isLoggedIn;
app.notLoggedIn = auth.notLoggedIn;
Then, in my root app, I just do the following to load the auth app in. Routing, public files, and all other stuff happens magically. pretty cool.
var auth = require('./vendor/auth/app');
var app = express();
app.configure(function() {
app.use(auth); // use our auth app
// do a lot of root-app related stuff...
});
Things still to do:
My auth app uses some session stuff. According to the second link, if I understand correctly, the app.use(session...) stuff in my auth app gets overridden by app.use. Also, I want to define an EJS helper to generate my urls (something like site_url('/facebook/callback') which then points to /auth/facebook/callback). Finally, I need to include settings from my root app. I'm thinking of wrapping my entire app.js (in auth) in a function, to which I pass a config object. Like this:
module.exports = function(config) {
var app = express();
app.set('config', config);
// various app settings, routes, etc
// return app so it's available in my root.
return app;
}
I hope this helps, if you need a bit more information I'll see if I can post some code to a gist. just let me know!