@tsed/common
Version:
A TypeScript Framework on top of Express
101 lines • 3.25 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlatformContext = void 0;
const di_1 = require("@tsed/di");
const PlatformApplication_1 = require("../services/PlatformApplication");
const PlatformRequest_1 = require("../services/PlatformRequest");
const PlatformResponse_1 = require("../services/PlatformResponse");
const RequestLogger_1 = require("./RequestLogger");
class PlatformContext extends Map {
constructor({ id, injector, logger, response, request, endpoint, ...options }) {
super();
/**
* Date when request have been handled by the server. @@RequestLogger@@ use this date to log request duration.
*/
this.dateStart = new Date();
/**
* The request container used by the Ts.ED DI. It contain all services annotated with `@Scope(ProviderScope.REQUEST)`
*/
this.container = new di_1.LocalsContainer();
this.id = id;
injector && (this.injector = injector);
response && (this.response = response);
request && (this.request = request);
endpoint && (this.endpoint = endpoint);
this.logger = new RequestLogger_1.RequestLogger(logger, {
...options,
id,
dateStart: this.dateStart
});
if (this.response) {
this.container.set(PlatformResponse_1.PlatformResponse, this.response);
}
if (this.response) {
this.container.set(PlatformRequest_1.PlatformRequest, this.request);
}
this.container.set(PlatformContext, this);
}
get env() {
return this.injector.settings.env;
}
get app() {
return this.injector.get(PlatformApplication_1.PlatformApplication);
}
async destroy() {
await this.container.destroy();
this.logger.destroy();
this.response.destroy();
this.request.destroy();
// @ts-ignore
delete this.container;
// @ts-ignore
delete this.logger;
// @ts-ignore
delete this.injector;
// @ts-ignore
delete this.endpoint;
// @ts-ignore
delete this.response;
// @ts-ignore
delete this.request;
}
isDone() {
return !this.request || !this.response;
}
async emit(eventName, ...args) {
return this.injector && this.injector.emit(eventName, ...args);
}
/**
* Return the framework request instance (Express, Koa, etc...)
*/
getRequest() {
return this.request.getRequest();
}
/**
* Return the framework response instance (Express, Koa, etc...)
*/
getResponse() {
return this.response.getResponse();
}
/**
* Get Node.js request
*/
getReq() {
return this.request.getReq();
}
/**
* Get Node.js response
*/
getRes() {
return this.response.getRes();
}
/**
* Return the original application instance.
*/
getApp() {
var _a;
return (_a = this.injector.get(PlatformApplication_1.PlatformApplication)) === null || _a === void 0 ? void 0 : _a.getApp();
}
}
exports.PlatformContext = PlatformContext;
//# sourceMappingURL=PlatformContext.js.map