How can I have multiple route files in server file using express (nodejs) - node.js

I am trying to put my routes into multiple files. if I only use one route file in server.ts like this, all works fine
server.ts:
require('./articles/routes/blog-article.routes')(app);
article.route.ts
module.exports = app => {
const article = require('../controllers/artilce.controller');
app.post('/api/blog/addArticle', article.addArticle);
app.get('/api/blog', article.getAllArticles);
app.get('/api/blog/:articleId', article.getArticleById);
app.delete('/api/blog/deleteArticle/:articleId', article.deleteArticle);
app.put('/api/blog/editArticle/:articleId', article.editArticle);
};
But if I add in server.ts require('./tags/routes/article-tags.routes')(app); it doesn't work.
article-tags.routes.ts:
module.exports = app =>
const articleTags = require('../controllers/article-tags.controller');
app.get('/api/blog/articleTags', articleTags.getAllArticleTags);
};

Related

Generic route prefix + specific route in Node Express

I have a system where, before specifying the data you want to access, you need to provide the company you are accessing from, to check for authorization.
For example, to get products, materials and users:
GET company/123123/product
GET company/123123/material
GET company/123123/user
When creating the express routes in node JS, I'm using the prefix "company/:id" in all my routes declarations:
app.get("/company/:id/product", callbackProduct);
app.get("/company/:id/material", callbackMaterial);
app.get("/company/:id/user", callbackUser);
The question is, is there any way to generalize this 'company' part of the route, in a way that I don't need to re-write it in all routes?
For example:
app.something("/company/id:/*", genericCallback);
app.get("/product", callbackProduct);
app.get("/material", callbackMaterial);
app.get("/user", callbackUser);
What you could do is to use express.Router.
In an company.routes.js you would write something like that.
const express = require("express");
const CompanyRouter = express.Router();
CompanyRouter.get("/:id/product", callbackProduct);
CompanyRouter.get("/:id/material", callbackMaterial);
CompanyRouter.get("/:id/user", callbackUser);
module.exports = CompanyRouter;
And in your server.js file you would do the following.
const express = require("express");
const CompanyRouter = require("./path/to/CompanyRouter.js")
const app = express();
app.use("/company", CompanyRouter);
app.listen(3000);

Nodjs swagger auto gen integration

I need to develop an API using NodeJS and also need to develop documentation for API also. I integrated with swagger auto-gen for swagger.json creation. But the swagger.json not generating properly if I used routes.js as below
var express = require('express');
module.exports = function(app) {
var userController = require('../controller/userController');
var apiRouter = express.Router();
var routerV1 = express.Router();
var routerV2 = express.Router();
app.use('/admin', apiRouter);
apiRouter.use("/v1", routerV1);
apiRouter.use("/v2", routerV2);
routerV1.route('/users').get(userController.getUsersV1);
routerV2.route('/users').get(userController.getUsersV2);
}
and also mapped these routes.js in swagger.js
Please suggest the best way to generate swagger.js
Do we need to create routes file for all controller?
Version 2 of swagger-autogen added this feature. Previous versions don't recognize routes. In your case, the best way to generate the file swagger.js is:
file: swagger.js
const swaggerAutogen = require('swagger-autogen')();
const outputFile = './swagger_output.json';
const endpointsFiles = ['./routes.js']; // root file where the route starts.
swaggerAutogen(outputFile, endpointsFiles).then(() => {
require('./index.js'); // Your project's root file
})
Update your module to the latest version.
And run your project with: node swagger.js
And about the routes file for all controller, you don't need to implement it for each one, but it also depends on the structure of your code. If you have a root route file like the example, this is enough for all sub-routes to be scanned. I hope it helps you. Take a look at this example if you need to:
swagger-autogen using router

typescript express get does not work in separate files

I'm currently converting my node code to node-ts to help our development flow for someone that is going to help out.
I tried using this information (typescript node.js express routes separated files best practices) initially but that didn't work, so as of right now I have this below
In my index.ts I have this on the bottom
import Auth from "./routes/Auth";
app.use('/auth', Auth.Routing());
export = app;
Then in my ./routes/Auth.ts I have this
const Routing = function() {
app.get('/session', User.session);
return app;
}
export = { Routing };
When I try to access /auth/session all it returns is index_1.default.get.
Using the link above, I attempted to use const router = express.Router(); and then export = router and what not but was unable to get it to work for that either with the same error.

How can my client get application configuration from the server when using Webpack?

I'm adding Webpack to a Node/Express app that previously used RequireJS. When the client needed some configuration from the server, we previously used a custom Express route that retrieved specific configs as JSON:
server/index.js - Set up Express routes for config files
const app = express();
const configRouter = express.Router();
configRouter.get('/some-config.json', (req, res) => {
const someConfig = {
prop1: getProp1(),
prop2: getProp2()
}
res.json(someConfig);
}
app.use('/config', configRouter);
client/controller.js - Use/config/some-config.json during initialization
define(['text!/config/some-config.json'], function(SomeConfig) {
// do something with SomeConfig
});
But removing RequireJS means I can no longer retrieve the JSON this way as a dependency. And it's not static JSON either, so it's not as simple as just placing it alongside client code and importing it.
So what is the best way to do this with Webpack? Any help greatly appreciated. Thanks!

Can I pass variable to required file?

In express, I'm trying to move my minification to a requierd file:
app.js:
var app = express();
var minify = require("./minify.js");
In that file I try to set my template engine.
minify.js:
var app = express();
app.engine('html', mustacheExpress());
Later when I try to use to use the rendering engine in app.js, I get the error that no template-engine is set. It works if I run it all in the same file. I think the problem is that I declare the app-variable twice. How can I pass the app-variable into minify.js?
The problem is that you define new app variable, and you currently instantiate brand new express instance by calling express().
What you need to do is start using functions so that you can pass params (there are other methods too, but this is one that will work for you):
// app.js
var app = express();
var minify = require('./minify'); // don't include .js!
minify(app); // CALL the function that minify.js exports, passing params
// minify.js
module.exports = function(app) {
// because app comes as a parameter, it's the very same you've created in app.js
app.engine('html', mustacheExpress());
}
Again, there are many different methods and maybe proper approaches, depending on what you want to do, but this will do the job in your case. Read more about NodeJS and it's require system.
You can pass 'app' from app.js to your minify by using function in your module like Andrey said. You can do it like this too for example :
minify.js
module.exports = {
setAppEngine : function(app) {
app.engine( [...] );
}
}
And calling it like this in your app.js:
app.js
var app = express();
var minify = require("./minify.js").setAppEngine(app);
This solution is very useful because you can set and call others methods in minify.js. For example, you can do with the same code in minify.js:
app.js
var app = express();
var minify = require("./minify.js");
minify.setAppEngine(app);

Resources