Looking at Massive's documentation, the way to save database connection execution time is to save the connection object once to Express's application settings. My question is, how to access the Express's app variable when the REST API is modularized? An example of the problem:
app.ts:
import express = require('express');
import greeter = require('./api/greeter');
var app = express();
app.get('/api/greeter', greeter.get);
greeter.ts:
import express = require("express");
function get(req: express.Request, res: express.Response, next: Function): any
{
// The this object seems not the Express's app object.
// console.log(this)
// How to access Express's app variable here?
// var db = app.get('db');
db.item.findOne({item_id : 1}, (err, item) => {
res.json(item);
});
}
I checked the this object in get RequestHandler, the this object seems not the Express's app object. Checked the req and res parameters too, looks like Express's app object is not there too.
Thanks @robertklep
The Express TypeScript definition is not updated. For the benefit of TypeScript users, just access the app through indexer. This works:
import express = require("express");
export function get(req: express.Request, res: express.Response, next: Function): any {
var app : express.Application = req["app"];
var db = app.get('db');