I am developing an application using node.js and typescript. I patterned my server.ts file after the approach outlined in this article, http://brianflove.com/2016/11/08/typescript-2-express-node/, here is the sample code for the server.ts file:
import * as bodyParser from "body-parser";
import * as cookieParser from "cookie-parser";
import * as express from "express";
import * as logger from "morgan";
import * as path from "path";
import errorHandler = require("errorhandler");
import methodOverride = require("method-override");
/**
* The server.
*
* @class Server
*/
export class Server {
public app: express.Application;
/**
* Bootstrap the application.
*
* @class Server
* @method bootstrap
* @static
* @return {ng.auto.IInjectorService} Returns the newly created injector for this app.
*/
public static bootstrap(): Server {
return new Server();
}
/**
* Constructor.
*
* @class Server
* @constructor
*/
constructor() {
//create expressjs application
this.app = express();
//configure application
this.config();
//add routes
this.routes();
//add api
this.api();
}
/**
* Create REST API routes
*
* @class Server
* @method api
*/
public api() {
//empty for now
}
/**
* Configure application
*
* @class Server
* @method config
*/
public config() {
//empty for now
}
/**
* Create router
*
* @class Server
* @method api
*/
public routes() {
//empty for now
}
}
and here is the sample code for the routes function:
/**
* Create router.
*
* @class Server
* @method config
* @return void
*/
private routes() {
let router: express.Router;
router = express.Router();
//let mymodel = this.connection.model<IMyModel>("MyModel", MySchema);
//let myservice: MyService = new MyService(this.myRepository(mymodel));
//IndexRoute
IndexRoute.create(router, myservice);
//use router middleware
this.app.use(router);
}
For my particular scenario, I am injecting a service into the route to perform the appropriate actions that may need to be performed. Here is my concern, if I am injecting the service into the controller in this manner. Does this mean each person making a request will receive a different service and repository or the same instance? Ideally, I would imagine it being better if each user receives a different instance. How would this effect the database calls being made in the repository layer? I am new to node.js and am still trying to wrap my head around the relationships between the app.js, server.js and requests being made as node.js is single threaded.