@tsed/platform-serverless 6.114.16 → 6.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.js CHANGED
@@ -6,7 +6,7 @@ module.exports = {
6
6
  coverageThreshold: {
7
7
  global: {
8
8
  branches: 83.33,
9
- functions: 98.63,
9
+ functions: 98.61,
10
10
  lines: 99.28,
11
11
  statements: 98.93
12
12
  }
@@ -35,9 +35,10 @@ const PlatformServerlessHandler_1 = require("./PlatformServerlessHandler");
35
35
  * @platform
36
36
  */
37
37
  class PlatformServerless {
38
- constructor() {
39
- this.name = "PlatformServerless";
40
- }
38
+ name = "PlatformServerless";
39
+ _injector;
40
+ _router;
41
+ _promise;
41
42
  get injector() {
42
43
  return this._injector;
43
44
  }
@@ -81,14 +82,13 @@ class PlatformServerless {
81
82
  .reduce((callbacks, token) => {
82
83
  const routes = (0, schema_1.getOperationsRoutes)(token);
83
84
  return routes.reduce((callbacks, operationRoute) => {
84
- var _a;
85
85
  const { operationId, token, propertyName, method, url } = operationRoute;
86
86
  // istanbul ignore next
87
87
  if (method === "USE") {
88
88
  return callbacks;
89
89
  }
90
90
  const callback = this.callback(token, propertyName);
91
- (_a = this._router) === null || _a === void 0 ? void 0 : _a.on(method, url, callback);
91
+ this._router?.on(method, url, callback);
92
92
  return {
93
93
  ...callbacks,
94
94
  [operationId]: callback
@@ -138,12 +138,11 @@ class PlatformServerless {
138
138
  return this._router;
139
139
  }
140
140
  createInjector(settings) {
141
- var _a;
142
141
  this._injector = new di_1.InjectorService();
143
142
  this.injector.logger = logger_1.$log;
144
143
  this.injector.settings.set(settings);
145
144
  // istanbul ignore next
146
- if (this.injector.settings.get("env") === core_1.Env.TEST && !((_a = settings === null || settings === void 0 ? void 0 : settings.logger) === null || _a === void 0 ? void 0 : _a.level)) {
145
+ if (this.injector.settings.get("env") === core_1.Env.TEST && !settings?.logger?.level) {
147
146
  logger_1.$log.stop();
148
147
  }
149
148
  return this;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, InjectorService, setLoggerConfiguration} from \"@tsed/di\";\nimport {$log, Logger} from \"@tsed/logger\";\nimport {getOperationsRoutes, JsonEntityStore} from \"@tsed/schema\";\nimport type {APIGatewayProxyResult, Handler} from \"aws-lambda\";\nimport type {HTTPMethod, Instance} from \"find-my-way\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {getRequestId} from \"../utils/getRequestId\";\nimport {PlatformServerlessHandler} from \"./PlatformServerlessHandler\";\n\nexport interface PlatformServerlessSettings extends Partial<TsED.Configuration> {\n lambda?: Type[];\n}\n\n/**\n * @platform\n */\nexport class PlatformServerless {\n readonly name: string = \"PlatformServerless\";\n\n private _injector: InjectorService;\n private _router: Instance<any>;\n private _promise: Promise<any>;\n\n get injector(): InjectorService {\n return this._injector;\n }\n\n get settings() {\n return this.injector.settings;\n }\n\n get promise() {\n return this._promise;\n }\n\n static bootstrap(settings: Partial<TsED.Configuration> & {lambda?: Type[]} = {}): PlatformServerless {\n const platform = new PlatformServerless();\n platform.createInjector(settings);\n\n return platform;\n }\n\n public handler(): Handler {\n return async (event, context) => {\n const [router] = await Promise.all([this.initRouter(), this.init()]);\n const result = router.find(event.httpMethod as any, event.path);\n\n if (result) {\n const {handler, params} = result;\n\n event.pathParameters = {\n ...(event.pathParameters || {}),\n ...params\n };\n\n return (handler as any)(event, context);\n }\n\n return {\n statusCode: 404,\n body: \"Not found\",\n headers: {\n \"x-request-id\": getRequestId(event, context)\n },\n isBase64Encoded: false\n };\n };\n }\n\n public callbacks(tokens: Type | Type[] = [], callbacks: any = {}): Record<string, Handler> {\n return this.settings\n .get<Type[]>(\"lambda\", [])\n .concat(tokens)\n .reduce((callbacks, token) => {\n const routes = getOperationsRoutes(token);\n\n return routes.reduce((callbacks, operationRoute) => {\n const {operationId, token, propertyName, method, url} = operationRoute;\n\n // istanbul ignore next\n if (method === \"USE\") {\n return callbacks;\n }\n\n const callback = this.callback(token, propertyName);\n\n this._router?.on(method as HTTPMethod, url as string, callback as any);\n\n return {\n ...callbacks,\n [operationId]: callback\n };\n }, callbacks);\n }, callbacks);\n }\n\n public async ready() {\n await this.injector.emit(\"$onReady\");\n }\n\n public async stop() {\n await this.injector.emit(\"$onDestroy\");\n return this.injector.destroy();\n }\n\n public async init() {\n if (!this._promise) {\n this._promise = this.loadInjector().then(() => this.ready());\n }\n\n return this._promise;\n }\n\n protected callback(token: Type<any>, propertyKey: string): Handler {\n const entity = JsonEntityStore.fromMethod(token, propertyKey);\n let handler: ($ctx: ServerlessContext) => Promise<APIGatewayProxyResult>;\n\n return async (event, context) => {\n await this.init();\n\n if (!handler) {\n const platformHandler = this.injector.get<PlatformServerlessHandler>(PlatformServerlessHandler)!;\n handler = await platformHandler.createHandler(token, propertyKey);\n }\n\n const $ctx = new ServerlessContext({\n event,\n context,\n id: getRequestId(event, context),\n logger: this.injector.logger as Logger,\n injector: this.injector,\n endpoint: entity\n });\n\n return handler($ctx);\n };\n }\n\n protected async initRouter() {\n if (!this._router) {\n const {default: FindMyMay} = await import(\"find-my-way\");\n\n this._router = FindMyMay({caseSensitive: false, ignoreTrailingSlash: true});\n\n this.callbacks();\n }\n\n return this._router;\n }\n\n protected createInjector(settings: any) {\n this._injector = new InjectorService();\n this.injector.logger = $log;\n this.injector.settings.set(settings);\n\n // istanbul ignore next\n if (this.injector.settings.get(\"env\") === Env.TEST && !settings?.logger?.level) {\n $log.stop();\n }\n\n return this;\n }\n\n protected async loadInjector() {\n const container = createContainer();\n\n setLoggerConfiguration(this.injector);\n\n await this.injector.emit(\"$beforeInit\");\n\n await this.injector.load(container);\n\n await this.injector.emit(\"$afterInit\");\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformServerless.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerless.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAqC;AACrC,iCAAkF;AAClF,yCAA0C;AAC1C,yCAAkE;AAGlE,mEAA8D;AAC9D,wDAAmD;AACnD,2EAAsE;AAMtE;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IAAI,EAAC,CAAC,CAAC;YAE5E,IAAI,CAAC,SAAS,EAAE,CAAC;SAClB;QAED,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAES,cAAc,CAAC,QAAa;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,oBAAe,EAAE,CAAC;QACvC,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,aAAI,CAAC;QAC5B,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAErC,uBAAuB;QACvB,IAAI,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,UAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE;YAC9E,aAAI,CAAC,IAAI,EAAE,CAAC;SACb;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAES,KAAK,CAAC,YAAY;QAC1B,MAAM,SAAS,GAAG,IAAA,oBAAe,GAAE,CAAC;QAEpC,IAAA,2BAAsB,EAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAEtC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAExC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEpC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACzC,CAAC;CACF;AA9JD,gDA8JC","sourcesContent":["import {Env, Type} from \"@tsed/core\";\nimport {createContainer, InjectorService, setLoggerConfiguration} from \"@tsed/di\";\nimport {$log, Logger} from \"@tsed/logger\";\nimport {getOperationsRoutes, JsonEntityStore} from \"@tsed/schema\";\nimport type {APIGatewayProxyResult, Handler} from \"aws-lambda\";\nimport type {HTTPMethod, Instance} from \"find-my-way\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {getRequestId} from \"../utils/getRequestId\";\nimport {PlatformServerlessHandler} from \"./PlatformServerlessHandler\";\n\nexport interface PlatformServerlessSettings extends Partial<TsED.Configuration> {\n lambda?: Type[];\n}\n\n/**\n * @platform\n */\nexport class PlatformServerless {\n readonly name: string = \"PlatformServerless\";\n\n private _injector: InjectorService;\n private _router: Instance<any>;\n private _promise: Promise<any>;\n\n get injector(): InjectorService {\n return this._injector;\n }\n\n get settings() {\n return this.injector.settings;\n }\n\n get promise() {\n return this._promise;\n }\n\n static bootstrap(settings: Partial<TsED.Configuration> & {lambda?: Type[]} = {}): PlatformServerless {\n const platform = new PlatformServerless();\n platform.createInjector(settings);\n\n return platform;\n }\n\n public handler(): Handler {\n return async (event, context) => {\n const [router] = await Promise.all([this.initRouter(), this.init()]);\n const result = router.find(event.httpMethod as any, event.path);\n\n if (result) {\n const {handler, params} = result;\n\n event.pathParameters = {\n ...(event.pathParameters || {}),\n ...params\n };\n\n return (handler as any)(event, context);\n }\n\n return {\n statusCode: 404,\n body: \"Not found\",\n headers: {\n \"x-request-id\": getRequestId(event, context)\n },\n isBase64Encoded: false\n };\n };\n }\n\n public callbacks(tokens: Type | Type[] = [], callbacks: any = {}): Record<string, Handler> {\n return this.settings\n .get<Type[]>(\"lambda\", [])\n .concat(tokens)\n .reduce((callbacks, token) => {\n const routes = getOperationsRoutes(token);\n\n return routes.reduce((callbacks, operationRoute) => {\n const {operationId, token, propertyName, method, url} = operationRoute;\n\n // istanbul ignore next\n if (method === \"USE\") {\n return callbacks;\n }\n\n const callback = this.callback(token, propertyName);\n\n this._router?.on(method as HTTPMethod, url as string, callback as any);\n\n return {\n ...callbacks,\n [operationId]: callback\n };\n }, callbacks);\n }, callbacks);\n }\n\n public async ready() {\n await this.injector.emit(\"$onReady\");\n }\n\n public async stop() {\n await this.injector.emit(\"$onDestroy\");\n return this.injector.destroy();\n }\n\n public async init() {\n if (!this._promise) {\n this._promise = this.loadInjector().then(() => this.ready());\n }\n\n return this._promise;\n }\n\n protected callback(token: Type<any>, propertyKey: string): Handler {\n const entity = JsonEntityStore.fromMethod(token, propertyKey);\n let handler: ($ctx: ServerlessContext) => Promise<APIGatewayProxyResult>;\n\n return async (event, context) => {\n await this.init();\n\n if (!handler) {\n const platformHandler = this.injector.get<PlatformServerlessHandler>(PlatformServerlessHandler)!;\n handler = await platformHandler.createHandler(token, propertyKey);\n }\n\n const $ctx = new ServerlessContext({\n event,\n context,\n id: getRequestId(event, context),\n logger: this.injector.logger as Logger,\n injector: this.injector,\n endpoint: entity\n });\n\n return handler($ctx);\n };\n }\n\n protected async initRouter() {\n if (!this._router) {\n const {default: FindMyMay} = await import(\"find-my-way\");\n\n this._router = FindMyMay({caseSensitive: false, ignoreTrailingSlash: true});\n\n this.callbacks();\n }\n\n return this._router;\n }\n\n protected createInjector(settings: any) {\n this._injector = new InjectorService();\n this.injector.logger = $log;\n this.injector.settings.set(settings);\n\n // istanbul ignore next\n if (this.injector.settings.get(\"env\") === Env.TEST && !settings?.logger?.level) {\n $log.stop();\n }\n\n return this;\n }\n\n protected async loadInjector() {\n const container = createContainer();\n\n setLoggerConfiguration(this.injector);\n\n await this.injector.emit(\"$beforeInit\");\n\n await this.injector.load(container);\n\n await this.injector.emit(\"$afterInit\");\n }\n}\n"]}
@@ -8,14 +8,17 @@ const json_mapper_1 = require("@tsed/json-mapper");
8
8
  const platform_params_1 = require("@tsed/platform-params");
9
9
  const setResponseHeaders_1 = require("../utils/setResponseHeaders");
10
10
  let PlatformServerlessHandler = class PlatformServerlessHandler {
11
+ injector;
12
+ params;
13
+ exceptionsManager;
11
14
  createHandler(token, propertyKey) {
12
15
  const promisedHandler = this.params.compileHandler({
13
16
  token,
14
17
  propertyKey
15
18
  });
16
19
  return async ($ctx) => {
17
- await this.injector.emit("$onRequest", $ctx);
18
- await (0, di_1.runInContext)($ctx, async () => {
20
+ await $ctx.runInContext(async () => {
21
+ await this.injector.emit("$onRequest", $ctx);
19
22
  try {
20
23
  const resolver = new core_1.AnyToPromise();
21
24
  const handler = await promisedHandler;
@@ -27,8 +30,8 @@ let PlatformServerlessHandler = class PlatformServerlessHandler {
27
30
  const exceptions = await this.exceptionsManager;
28
31
  await exceptions.catch(er, $ctx);
29
32
  }
33
+ await this.injector.emit("$onResponse", $ctx);
30
34
  });
31
- await this.injector.emit("$onResponse", $ctx);
32
35
  return this.flush($ctx);
33
36
  };
34
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformServerlessHandler.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerlessHandler.ts"],"names":[],"mappings":";;;;AAAA,qCAA0E;AAC1E,iCAAkI;AAClI,mDAA4C;AAC5C,2DAAuF;AAGvF,oEAA+D;AAM/D,IAAa,yBAAyB,GAAtC,MAAa,yBAAyB;IAUpC,aAAa,CAAC,KAAoB,EAAE,WAA4B;QAC9D,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC;YACjD,KAAK;YACL,WAAW;SACZ,CAAC,CAAC;QAEH,OAAO,KAAK,EAAE,IAAuB,EAAE,EAAE;YACvC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;YAE7C,MAAM,IAAA,iBAAY,EAAC,IAAI,EAAE,KAAK,IAAI,EAAE;gBAClC,IAAI;oBACF,MAAM,QAAQ,GAAG,IAAI,mBAAY,EAAE,CAAC;oBACpC,MAAM,OAAO,GAAG,MAAM,eAAe,CAAC;oBACtC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,EAAC,IAAI,EAAC,CAAC,CAAC,CAAC;oBAE1D,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;iBAClC;gBAAC,OAAO,EAAE,EAAE;oBACX,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;oBACnC,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,iBAAiB,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AAC;SACnC;QAED,IAAI,IAAI,KAAK,SAAS,EAAE;YACtB,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAErD,IAAI,IAAA,qBAAc,EAAC,IAAI,CAAC,EAAE;gBACxB,IAAI,GAAG,IAAA,uBAAS,EAAC,IAAI,EAAE;oBACrB,GAAG,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;oBAC9D,QAAQ,EAAE,IAAI;oBACd,QAAQ,EAAE,IAAI;iBACf,CAAC,CAAC;aACJ;YAED,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SAC1B;IACH,CAAC;CACF,CAAA;AAtFC;IADC,IAAA,WAAM,GAAE;sCACW,oBAAe;2DAAC;AAGpC;IADC,IAAA,WAAM,GAAE;sCACS,gCAAc;yDAAC;AAGjC;IADC,IAAA,eAAU,EAAC,oBAAoB,EAAE,GAAG,EAAE,2DAAQ,2BAA2B,GAAC,CAAC;;oEACnB;AAR9C,yBAAyB;IAJrC,IAAA,eAAU,EAAC;QACV,KAAK,EAAE,kBAAa,CAAC,SAAS;QAC9B,OAAO,EAAE,CAAC,kCAAgB,EAAE,gCAAc,CAAC;KAC5C,CAAC;GACW,yBAAyB,CAwFrC;AAxFY,8DAAyB","sourcesContent":["import {AnyPromiseResult, AnyToPromise, isSerializable} from \"@tsed/core\";\nimport {BaseContext, Inject, Injectable, InjectorService, LazyInject, ProviderScope, runInContext, TokenProvider} from \"@tsed/di\";\nimport {serialize} from \"@tsed/json-mapper\";\nimport {DeserializerPipe, PlatformParams, ValidationPipe} from \"@tsed/platform-params\";\nimport type {PlatformExceptions} from \"@tsed/platform-exceptions\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {setResponseHeaders} from \"../utils/setResponseHeaders\";\n\n@Injectable({\n scope: ProviderScope.SINGLETON,\n imports: [DeserializerPipe, ValidationPipe]\n})\nexport class PlatformServerlessHandler {\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected params: PlatformParams;\n\n @LazyInject(\"PlatformExceptions\", () => import(\"@tsed/platform-exceptions\"))\n protected exceptionsManager: Promise<PlatformExceptions>;\n\n createHandler(token: TokenProvider, propertyKey: string | symbol) {\n const promisedHandler = this.params.compileHandler({\n token,\n propertyKey\n });\n\n return async ($ctx: ServerlessContext) => {\n await this.injector.emit(\"$onRequest\", $ctx);\n\n await runInContext($ctx, async () => {\n try {\n const resolver = new AnyToPromise();\n const handler = await promisedHandler;\n const result = await resolver.call(() => handler({$ctx}));\n\n this.processResult(result, $ctx);\n } catch (er) {\n $ctx.response.status(500).body(er);\n const exceptions = await this.exceptionsManager;\n\n await exceptions.catch(er, $ctx as unknown as BaseContext);\n }\n });\n\n await this.injector.emit(\"$onResponse\", $ctx);\n\n return this.flush($ctx);\n };\n }\n\n private flush($ctx: ServerlessContext) {\n setResponseHeaders($ctx);\n\n let body: any = $ctx.response.getBody();\n\n if (isSerializable(body)) {\n $ctx.response.set(\"content-type\", \"application/json\");\n body = JSON.stringify(body);\n }\n\n const response = {\n statusCode: $ctx.response.getStatus(),\n body: body === undefined ? \"\" : body,\n headers: {\n ...$ctx.response.getHeaders(),\n \"x-request-id\": $ctx.id\n },\n isBase64Encoded: false\n };\n\n $ctx.destroy();\n\n return response;\n }\n\n private processResult({status, headers, data}: AnyPromiseResult, $ctx: ServerlessContext) {\n if (status) {\n $ctx.response.status(status);\n }\n\n if (headers) {\n $ctx.response.setHeaders(headers);\n }\n\n if (data !== undefined) {\n data = $ctx.response.getStatus() !== 204 ? data : \"\";\n\n if (isSerializable(data)) {\n data = serialize(data, {\n ...$ctx.endpoint.getResponseOptions($ctx.response.getStatus()),\n useAlias: true,\n endpoint: true\n });\n }\n\n $ctx.response.body(data);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformServer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AAc,EAAC,IAAI,CAAC,EAAE;gBACxB,IAAI,GAAG,IAAA,uBAAS,EAAC,IAAI,EAAE;oBACrB,GAAG,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;oBAC9D,QAAQ,EAAE,IAAI;oBACd,QAAQ,EAAE,IAAI;iBACf,CAAC,CAAC;aACJ;YAED,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SAC1B;IACH,CAAC;CACF,CAAA;AAtFC;IADC,IAAA,WAAM,GAAE;sCACW,oBAAe;2DAAC;AAGpC;IADC,IAAA,WAAM,GAAE;sCACS,gCAAc;yDAAC;AAGjC;IADC,IAAA,eAAU,EAAC,oBAAoB,EAAE,GAAG,EAAE,2DAAQ,2BAA2B,GAAC,CAAC;;oEACnB;AAR9C,yBAAyB;IAJrC,IAAA,eAAU,EAAC;QACV,KAAK,EAAE,kBAAa,CAAC,SAAS;QAC9B,OAAO,EAAE,CAAC,kCAAgB,EAAE,gCAAc,CAAC;KAC5C,CAAC;GACW,yBAAyB,CAwFrC;AAxFY,8DAAyB","sourcesContent":["import {AnyPromiseResult, AnyToPromise, isSerializable} from \"@tsed/core\";\nimport {BaseContext, Inject, Injectable, InjectorService, LazyInject, ProviderScope, runInContext, TokenProvider} from \"@tsed/di\";\nimport {serialize} from \"@tsed/json-mapper\";\nimport {DeserializerPipe, PlatformParams, ValidationPipe} from \"@tsed/platform-params\";\nimport type {PlatformExceptions} from \"@tsed/platform-exceptions\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {setResponseHeaders} from \"../utils/setResponseHeaders\";\n\n@Injectable({\n scope: ProviderScope.SINGLETON,\n imports: [DeserializerPipe, ValidationPipe]\n})\nexport class PlatformServerlessHandler {\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected params: PlatformParams;\n\n @LazyInject(\"PlatformExceptions\", () => import(\"@tsed/platform-exceptions\"))\n protected exceptionsManager: Promise<PlatformExceptions>;\n\n createHandler(token: TokenProvider, propertyKey: string | symbol) {\n const promisedHandler = this.params.compileHandler({\n token,\n propertyKey\n });\n\n return async ($ctx: ServerlessContext) => {\n await $ctx.runInContext(async () => {\n await this.injector.emit(\"$onRequest\", $ctx);\n\n try {\n const resolver = new AnyToPromise();\n const handler = await promisedHandler;\n const result = await resolver.call(() => handler({$ctx}));\n\n this.processResult(result, $ctx);\n } catch (er) {\n $ctx.response.status(500).body(er);\n const exceptions = await this.exceptionsManager;\n\n await exceptions.catch(er, $ctx as unknown as BaseContext);\n }\n\n await this.injector.emit(\"$onResponse\", $ctx);\n });\n\n return this.flush($ctx);\n };\n }\n\n private flush($ctx: ServerlessContext) {\n setResponseHeaders($ctx);\n\n let body: any = $ctx.response.getBody();\n\n if (isSerializable(body)) {\n $ctx.response.set(\"content-type\", \"application/json\");\n body = JSON.stringify(body);\n }\n\n const response = {\n statusCode: $ctx.response.getStatus(),\n body: body === undefined ? \"\" : body,\n headers: {\n ...$ctx.response.getHeaders(),\n \"x-request-id\": $ctx.id\n },\n isBase64Encoded: false\n };\n\n $ctx.destroy();\n\n return response;\n }\n\n private processResult({status, headers, data}: AnyPromiseResult, $ctx: ServerlessContext) {\n if (status) {\n $ctx.response.status(status);\n }\n\n if (headers) {\n $ctx.response.setHeaders(headers);\n }\n\n if (data !== undefined) {\n data = $ctx.response.getStatus() !== 204 ? data : \"\";\n\n if (isSerializable(data)) {\n data = serialize(data, {\n ...$ctx.endpoint.getResponseOptions($ctx.response.getStatus()),\n useAlias: true,\n endpoint: true\n });\n }\n\n $ctx.response.body(data);\n }\n }\n}\n"]}
@@ -5,6 +5,11 @@ const di_1 = require("@tsed/di");
5
5
  const ServerlessRequest_1 = require("./ServerlessRequest");
6
6
  const ServerlessResponse_1 = require("./ServerlessResponse");
7
7
  class ServerlessContext extends di_1.DIContext {
8
+ response;
9
+ request;
10
+ context;
11
+ event;
12
+ endpoint;
8
13
  constructor({ event, context, endpoint, ...options }) {
9
14
  super({
10
15
  ...options,
@@ -1 +1 @@
1
- {"version":3,"file":"ServerlessContext.js","sourceRoot":"","sources":["../../../src/domain/ServerlessContext.ts"],"names":[],"mappings":";;;AAAA,iCAAqD;AAGrD,2DAAsD;AACtD,6DAAwD;AAQxD,MAAa,iBAAkB,SAAQ,cAAS;IAO9C,YAAY,EAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAA2B;QAC1E,KAAK,CAAC;YACJ,GAAG,OAAO;YACV,YAAY,EAAE,CAAC;SAChB,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,IAAI,qCAAiB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAC,CAAC,CAAC;QACvD,IAAI,CAAC,QAAQ,GAAG,IAAI,uCAAkB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAC,CAAC,CAAC;QAChF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;CACF;AAzBD,8CAyBC","sourcesContent":["import {DIContext, DIContextOptions} from \"@tsed/di\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {ServerlessRequest} from \"./ServerlessRequest\";\nimport {ServerlessResponse} from \"./ServerlessResponse\";\n\nexport interface ServerlessContextOptions extends DIContextOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n endpoint: JsonEntityStore;\n}\n\nexport class ServerlessContext extends DIContext {\n readonly response: ServerlessResponse;\n readonly request: ServerlessRequest;\n readonly context: Context;\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly endpoint: JsonEntityStore;\n\n constructor({event, context, endpoint, ...options}: ServerlessContextOptions) {\n super({\n ...options,\n maxStackSize: 0\n });\n this.context = context;\n this.event = event;\n this.request = new ServerlessRequest({event, context});\n this.response = new ServerlessResponse({event, context, request: this.request});\n this.endpoint = endpoint;\n }\n\n async destroy() {\n await super.destroy();\n\n this.request.destroy();\n this.response.destroy();\n }\n}\n"]}
1
+ {"version":3,"file":"ServerlessContext.js","sourceRoot":"","sources":["../../../src/domain/ServerlessContext.ts"],"names":[],"mappings":";;;AAAA,iCAAqD;AAGrD,2DAAsD;AACtD,6DAAwD;AAQxD,MAAa,iBAAkB,SAAQ,cAAS;IACrC,QAAQ,CAAqB;IAC7B,OAAO,CAAoB;IAC3B,OAAO,CAAU;IACjB,KAAK,CAAoE;IACzE,QAAQ,CAAkB;IAEnC,YAAY,EAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAA2B;QAC1E,KAAK,CAAC;YACJ,GAAG,OAAO;YACV,YAAY,EAAE,CAAC;SAChB,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,IAAI,qCAAiB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAC,CAAC,CAAC;QACvD,IAAI,CAAC,QAAQ,GAAG,IAAI,uCAAkB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAC,CAAC,CAAC;QAChF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;CACF;AAzBD,8CAyBC","sourcesContent":["import {DIContext, DIContextOptions} from \"@tsed/di\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {ServerlessRequest} from \"./ServerlessRequest\";\nimport {ServerlessResponse} from \"./ServerlessResponse\";\n\nexport interface ServerlessContextOptions extends DIContextOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n endpoint: JsonEntityStore;\n}\n\nexport class ServerlessContext extends DIContext {\n readonly response: ServerlessResponse;\n readonly request: ServerlessRequest;\n readonly context: Context;\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly endpoint: JsonEntityStore;\n\n constructor({event, context, endpoint, ...options}: ServerlessContextOptions) {\n super({\n ...options,\n maxStackSize: 0\n });\n this.context = context;\n this.event = event;\n this.request = new ServerlessRequest({event, context});\n this.response = new ServerlessResponse({event, context, request: this.request});\n this.endpoint = endpoint;\n }\n\n async destroy() {\n await super.destroy();\n\n this.request.destroy();\n this.response.destroy();\n }\n}\n"]}
@@ -6,6 +6,7 @@ const core_1 = require("@tsed/core");
6
6
  * @platform
7
7
  */
8
8
  class ServerlessRequest {
9
+ raw;
9
10
  constructor({ event }) {
10
11
  this.raw = event;
11
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ServerlessRequest.js","sourceRoot":"","sources":["../../../src/domain/ServerlessRequest.ts"],"names":[],"mappings":";;;AACA,qCAAoC;AAMpC;;GAEG;AACH,MAAa,iBAAiB;IAG5B,YAAY,EAAC,KAAK,EAA2B;QAC3C,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC;IACnB,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;OAIG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;IACvB,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;IAC1B,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC;IAC7B,CAAC;IAED;;;OAGG;IACH,IAAI,IAAI;QACN,IAAI;YACF,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;SACvD;QAAC,OAAO,EAAE,EAAE;YACX,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;SACtB;IACH,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;IACvB,CAAC;IAED;;;;OAIG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,GAAG,CAAC,cAAc,IAAI,EAAE,CAAC;IACvC,CAAC;IAED;;;OAGG;IACH,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,GAAG,CAAC,qBAAqB,IAAI,EAAE,CAAC;IAC9C,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAAC,IAAY;QACd,OAAO,IAAA,eAAQ,EAAC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,KAAI,CAAC;CACb;AAnFD,8CAmFC","sourcesContent":["import type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {getValue} from \"@tsed/core\";\n\nexport interface ServerlessRequestOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n}\n/**\n * @platform\n */\nexport class ServerlessRequest {\n readonly raw: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n\n constructor({event}: ServerlessRequestOptions) {\n this.raw = event;\n }\n\n get secure(): boolean {\n return true;\n }\n\n get host(): string {\n return this.get(\"host\");\n }\n\n get protocol(): string {\n return \"https\";\n }\n\n /**\n * Get the url of the request.\n *\n * Is equivalent of `express.response.originalUrl || express.response.url`.\n */\n get url(): string {\n return this.raw.path;\n }\n\n get headers() {\n return this.raw.headers;\n }\n\n get method(): string {\n return this.raw.httpMethod;\n }\n\n /**\n * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use\n * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.\n */\n get body(): any {\n try {\n return this.raw.body ? JSON.parse(this.raw.body) : {};\n } catch (er) {\n return this.raw.body;\n }\n }\n\n get rawBody(): any {\n return this.raw.body;\n }\n\n /**\n * This property is an object containing properties mapped to the named route `parameters`.\n * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.\n * This object defaults to `{}`.\n */\n get params(): {[key: string]: any} {\n return this.raw.pathParameters || {};\n }\n\n /**\n * This property is an object containing a property for each query string parameter in the route.\n * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.\n */\n get query(): {[key: string]: any} {\n return this.raw.queryStringParameters || {};\n }\n\n /**\n * Returns the HTTP request header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * request.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string) {\n return getValue(this.raw.headers, name);\n }\n\n destroy() {}\n}\n"]}
1
+ {"version":3,"file":"ServerlessRequest.js","sourceRoot":"","sources":["../../../src/domain/ServerlessRequest.ts"],"names":[],"mappings":";;;AACA,qCAAoC;AAMpC;;GAEG;AACH,MAAa,iBAAiB;IACnB,G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AAC;IAED,OAAO,KAAI,CAAC;CACb;AAnFD,8CAmFC","sourcesContent":["import type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {getValue} from \"@tsed/core\";\n\nexport interface ServerlessRequestOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n}\n/**\n * @platform\n */\nexport class ServerlessRequest {\n readonly raw: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n\n constructor({event}: ServerlessRequestOptions) {\n this.raw = event;\n }\n\n get secure(): boolean {\n return true;\n }\n\n get host(): string {\n return this.get(\"host\");\n }\n\n get protocol(): string {\n return \"https\";\n }\n\n /**\n * Get the url of the request.\n *\n * Is equivalent of `express.response.originalUrl || express.response.url`.\n */\n get url(): string {\n return this.raw.path;\n }\n\n get headers() {\n return this.raw.headers;\n }\n\n get method(): string {\n return this.raw.httpMethod;\n }\n\n /**\n * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use\n * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.\n */\n get body(): any {\n try {\n return this.raw.body ? JSON.parse(this.raw.body) : {};\n } catch (er) {\n return this.raw.body;\n }\n }\n\n get rawBody(): any {\n return this.raw.body;\n }\n\n /**\n * This property is an object containing properties mapped to the named route `parameters`.\n * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.\n * This object defaults to `{}`.\n */\n get params(): {[key: string]: any} {\n return this.raw.pathParameters || {};\n }\n\n /**\n * This property is an object containing a property for each query string parameter in the route.\n * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.\n */\n get query(): {[key: string]: any} {\n return this.raw.queryStringParameters || {};\n }\n\n /**\n * Returns the HTTP request header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * request.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string) {\n return getValue(this.raw.headers, name);\n }\n\n destroy() {}\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- var _ServerlessResponse_status, _ServerlessResponse_body, _ServerlessResponse_headers, _ServerlessResponse_locals, _ServerlessResponse_isHeadersSent, _ServerlessResponse_endListeners;
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  exports.ServerlessResponse = void 0;
5
4
  const tslib_1 = require("tslib");
@@ -11,13 +10,15 @@ const mime = tslib_1.__importStar(require("mime"));
11
10
  * @platform
12
11
  */
13
12
  class ServerlessResponse {
13
+ event;
14
+ request;
15
+ #status = 200;
16
+ #body = undefined;
17
+ #headers = {};
18
+ #locals = {};
19
+ #isHeadersSent = false;
20
+ #endListeners = [];
14
21
  constructor({ event, request }) {
15
- _ServerlessResponse_status.set(this, 200);
16
- _ServerlessResponse_body.set(this, undefined);
17
- _ServerlessResponse_headers.set(this, {});
18
- _ServerlessResponse_locals.set(this, {});
19
- _ServerlessResponse_isHeadersSent.set(this, false);
20
- _ServerlessResponse_endListeners.set(this, []);
21
22
  this.event = event;
22
23
  this.request = request;
23
24
  }
@@ -25,10 +26,10 @@ class ServerlessResponse {
25
26
  * Get the current statusCode
26
27
  */
27
28
  get statusCode() {
28
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_status, "f");
29
+ return this.#status;
29
30
  }
30
31
  set statusCode(status) {
31
- tslib_1.__classPrivateFieldSet(this, _ServerlessResponse_status, status, "f");
32
+ this.#status = status;
32
33
  }
33
34
  /**
34
35
  * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
@@ -36,13 +37,13 @@ class ServerlessResponse {
36
37
  * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
37
38
  */
38
39
  get locals() {
39
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_locals, "f");
40
+ return this.#locals;
40
41
  }
41
42
  get isHeadersSent() {
42
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_isHeadersSent, "f");
43
+ return this.#isHeadersSent;
43
44
  }
44
45
  getStatus() {
45
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_status, "f");
46
+ return this.#status;
46
47
  }
47
48
  /**
48
49
  * Sets the HTTP status for the response.
@@ -50,7 +51,7 @@ class ServerlessResponse {
50
51
  * @param status
51
52
  */
52
53
  status(status) {
53
- tslib_1.__classPrivateFieldSet(this, _ServerlessResponse_status, status, "f");
54
+ this.#status = status;
54
55
  return this;
55
56
  }
56
57
  set(name, value) {
@@ -66,15 +67,15 @@ class ServerlessResponse {
66
67
  * @param name
67
68
  */
68
69
  get(name) {
69
- return (0, core_1.getValue)(tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_headers, "f"), name.toLowerCase());
70
+ return (0, core_1.getValue)(this.#headers, name.toLowerCase());
70
71
  }
71
72
  getHeaders() {
72
73
  return {
73
- ...tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_headers, "f")
74
+ ...this.#headers
74
75
  };
75
76
  }
76
77
  hasStatus() {
77
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_status, "f") !== 200;
78
+ return this.#status !== 200;
78
79
  }
79
80
  /**
80
81
  * Set header `field` to `val`, or pass
@@ -104,10 +105,10 @@ class ServerlessResponse {
104
105
  }
105
106
  item = (0, encodeurl_1.default)(String(item));
106
107
  }
107
- tslib_1.__classPrivateFieldSet(this, _ServerlessResponse_headers, {
108
- ...tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_headers, "f"),
108
+ this.#headers = {
109
+ ...this.#headers,
109
110
  [key.toLowerCase()]: item
110
- }, "f");
111
+ };
111
112
  }
112
113
  return this;
113
114
  }
@@ -170,24 +171,23 @@ class ServerlessResponse {
170
171
  * @param body
171
172
  */
172
173
  body(body) {
173
- tslib_1.__classPrivateFieldSet(this, _ServerlessResponse_body, body, "f");
174
+ this.#body = body;
174
175
  return this;
175
176
  }
176
177
  getBody() {
177
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_body, "f");
178
+ return this.#body;
178
179
  }
179
180
  isDone() {
180
- return tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_isHeadersSent, "f");
181
+ return this.#isHeadersSent;
181
182
  }
182
183
  onEnd(cb) {
183
- tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_endListeners, "f").push(cb);
184
+ this.#endListeners.push(cb);
184
185
  return this;
185
186
  }
186
187
  destroy() {
187
- tslib_1.__classPrivateFieldGet(this, _ServerlessResponse_endListeners, "f").forEach((cb) => cb());
188
- tslib_1.__classPrivateFieldSet(this, _ServerlessResponse_isHeadersSent, true, "f");
188
+ this.#endListeners.forEach((cb) => cb());
189
+ this.#isHeadersSent = true;
189
190
  }
190
191
  }
191
192
  exports.ServerlessResponse = ServerlessResponse;
192
- _ServerlessResponse_status = new WeakMap(), _ServerlessResponse_body = new WeakMap(), _ServerlessResponse_headers = new WeakMap(), _ServerlessResponse_locals = new WeakMap(), _ServerlessResponse_isHeadersSent = new WeakMap(), _ServerlessResponse_endListeners = new WeakMap();
193
193
  //# sourceMappingURL=ServerlessResponse.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServerlessResponse.js","sourceRoot":"","sources":["../../../src/domain/ServerlessResponse.ts"],"names":[],"mappings":";;;;;AAAA,qCAAoC;AACpC,yCAA8C;AAE9C,kEAAkC;AAClC,mDAA6B;AAW7B;;GAEG;AACH,MAAa,kBAAkB;IAW7B,YAAY,EAAC,KAAK,EAAE,OAAO,EAA4B;QAPvD,qCAAkB,GAAG,EAAC;QACtB,mCAAa,SAAS,EAAC;QACvB,sCAAwC,EAAE,EAAC;QAC3C,qCAA+B,EAAE,EAAC;QAClC,4CAAiB,KAAK,EAAC;QACvB,2CAA4B,EAAE,EAAC;QAG7B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACZ,OAAO,+BAAA,IAAI,kCAAQ,CAAC;IACtB,CAAC;IAED,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GAAG,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,IAAI,GAAG,GAAG,IAAA,yBAAgB,EAAC,MAAM,CAAC,oBAAoB,OAAO,EAAE,CAAC;QAEtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAE9E,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,GAAW;QAClB,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IACnC,CAAC;IAED;;;;;;;OAOG;IACH,IAAI,CAAC,IAAS;QACZ,+BAAA,IAAI,4BAAS,IAAI,MAAA,CAAC;QAElB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,+BAAA,IAAI,gCAAM,CAAC;IACpB,CAAC;IAED,MAAM;QACJ,OAAO,+BAAA,IAAI,yCAAe,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,EAAY;QAChB,+BAAA,IAAI,wCAAc,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,+BAAA,IAAI,wCAAc,CAAC,OAAO,CAAC,CAAC,EAAY,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QACnD,+BAAA,IAAI,qCAAkB,IAAI,MAAA,CAAC;IAC7B,CAAC;CACF;AAtND,gDAsNC","sourcesContent":["import {getValue} from \"@tsed/core\";\nimport {getStatusMessage} from \"@tsed/schema\";\nimport type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport encodeUrl from \"encodeurl\";\nimport * as mime from \"mime\";\nimport type {ServerlessRequest} from \"./ServerlessRequest\";\n\nexport interface ServerlessResponseOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n request: ServerlessRequest;\n}\n\nexport type HeaderValue = boolean | number | string;\n\n/**\n * @platform\n */\nexport class ServerlessResponse {\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly request: ServerlessRequest;\n\n #status: number = 200;\n #body: any = undefined;\n #headers: Record<string, HeaderValue> = {};\n #locals: Record<string, any> = {};\n #isHeadersSent = false;\n #endListeners: Function[] = [];\n\n constructor({event, request}: ServerlessResponseOptions) {\n this.event = event;\n this.request = request;\n }\n\n /**\n * Get the current statusCode\n */\n get statusCode() {\n return this.#status;\n }\n\n set statusCode(status) {\n this.#status = status;\n }\n\n /**\n * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.\n *\n * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.\n */\n get locals() {\n return this.#locals;\n }\n\n get isHeadersSent() {\n return this.#isHeadersSent;\n }\n\n getStatus() {\n return this.#status;\n }\n\n /**\n * Sets the HTTP status for the response.\n *\n * @param status\n */\n status(status: number) {\n this.#status = status;\n return this;\n }\n\n set(name: string, value: any) {\n return this.setHeader(name, value);\n }\n\n /**\n * Returns the HTTP response header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * response.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string): string | number | boolean | undefined {\n return getValue(this.#headers, name.toLowerCase());\n }\n\n getHeaders(): Record<string, HeaderValue> {\n return {\n ...this.#headers\n };\n }\n\n hasStatus() {\n return this.#status !== 200;\n }\n\n /**\n * Set header `field` to `val`, or pass\n * an object of header fields.\n *\n * Examples:\n * ```typescript\n * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });\n * ```\n *\n * Aliased as `res.header()`.\n */\n setHeaders(headers: Record<string, HeaderValue>) {\n // apply headers\n Object.entries(headers).forEach(([key, item]) => {\n this.setHeader(key, item);\n });\n\n return this;\n }\n\n setHeader(key: string, item: HeaderValue | null | undefined) {\n if (item !== null && item !== undefined) {\n key = key.toLowerCase();\n\n if (key === \"location\") {\n // \"back\" is an alias for the referrer\n if (item === \"back\") {\n item = this.request.get(\"Referrer\") || \"/\";\n }\n\n item = encodeUrl(String(item));\n }\n\n this.#headers = {\n ...this.#headers,\n [key.toLowerCase()]: item as any\n };\n }\n\n return this;\n }\n\n /**\n * Set `Content-Type` response header with `type` through `mime.lookup()`\n * when it does not contain \"/\", or set the Content-Type to `type` otherwise.\n *\n * Examples:\n *\n * res.type('.html');\n * res.type('html');\n * res.type('json');\n * res.type('application/json');\n * res.type('png');\n */\n contentType(contentType: string) {\n this.setHeader(\"Content-Type\", mime.getType(contentType));\n\n return this;\n }\n\n contentLength(length: number) {\n this.setHeader(\"Content-Length\", length);\n return this;\n }\n\n getContentLength() {\n if (this.get(\"Content-Length\")) {\n return parseInt(this.get(\"Content-Length\") as any, 10) || 0;\n }\n }\n\n getContentType() {\n return String(this.get(\"Content-Type\") || \"\").split(\";\")[0];\n }\n\n /**\n * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).\n * If not specified, status defaults to `302 Found`.\n *\n * @param status\n * @param url\n */\n redirect(status: number, url: string) {\n // Set location header\n const address = this.location(url).get(\"Location\");\n const body = `${getStatusMessage(status)}. Redirecting to ${address}`;\n\n this.status(status).set(\"Content-Length\", Buffer.byteLength(body)).body(body);\n\n return this;\n }\n\n /**\n * Sets the response Location HTTP header to the specified path parameter.\n *\n * @param url\n */\n location(url: string) {\n return this.set(\"Location\", url);\n }\n\n /**\n * Send any data to your consumer.\n *\n * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.\n * It choose the better way to send the data.\n *\n * @param body\n */\n body(body: any) {\n this.#body = body;\n\n return this;\n }\n\n getBody() {\n return this.#body;\n }\n\n isDone(): boolean {\n return this.#isHeadersSent;\n }\n\n onEnd(cb: Function) {\n this.#endListeners.push(cb);\n\n return this;\n }\n\n destroy() {\n this.#endListeners.forEach((cb: Function) => cb());\n this.#isHeadersSent = true;\n }\n}\n"]}
1
+ {"version":3,"file":"ServerlessResponse.js","sourceRoot":"","sources":["../../../src/domain/ServerlessResponse.ts"],"names":[],"mappings":";;;;AAAA,qCAAoC;AACpC,yCAA8C;AAE9C,kEAAkC;AAClC,mDAA6B;AAW7B;;GAEG;AACH,MAAa,kBAAkB;IACpB,KAAK,CAAoE;IACzE,OAAO,CAAoB;IAEpC,OAAO,GAAW,GAAG,CAAC;IACtB,KAAK,GAAQ,SAAS,CAAC;IACvB,QAAQ,GAAgC,EAAE,CAAC;IAC3C,OAAO,GAAwB,EAAE,CAAC;IAClC,cAAc,GAAG,KAAK,CAAC;IACvB,aAAa,GAAe,EAAE,CAAC;IAE/B,YAAY,EAAC,KAAK,EAAE,OAAO,EAA4B;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,IAAI,UAAU,CAAC,MAAM;QACnB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED;;;;OAIG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAc;QACnB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,GAAG,CAAC,IAAY,EAAE,KAAU;QAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrC,CAAC;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C;IACd,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,EAAY;QAChB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,EAAY,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QACnD,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;IAC7B,CAAC;CACF;AAtND,gDAsNC","sourcesContent":["import {getValue} from \"@tsed/core\";\nimport {getStatusMessage} from \"@tsed/schema\";\nimport type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport encodeUrl from \"encodeurl\";\nimport * as mime from \"mime\";\nimport type {ServerlessRequest} from \"./ServerlessRequest\";\n\nexport interface ServerlessResponseOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n request: ServerlessRequest;\n}\n\nexport type HeaderValue = boolean | number | string;\n\n/**\n * @platform\n */\nexport class ServerlessResponse {\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly request: ServerlessRequest;\n\n #status: number = 200;\n #body: any = undefined;\n #headers: Record<string, HeaderValue> = {};\n #locals: Record<string, any> = {};\n #isHeadersSent = false;\n #endListeners: Function[] = [];\n\n constructor({event, request}: ServerlessResponseOptions) {\n this.event = event;\n this.request = request;\n }\n\n /**\n * Get the current statusCode\n */\n get statusCode() {\n return this.#status;\n }\n\n set statusCode(status) {\n this.#status = status;\n }\n\n /**\n * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.\n *\n * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.\n */\n get locals() {\n return this.#locals;\n }\n\n get isHeadersSent() {\n return this.#isHeadersSent;\n }\n\n getStatus() {\n return this.#status;\n }\n\n /**\n * Sets the HTTP status for the response.\n *\n * @param status\n */\n status(status: number) {\n this.#status = status;\n return this;\n }\n\n set(name: string, value: any) {\n return this.setHeader(name, value);\n }\n\n /**\n * Returns the HTTP response header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * response.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string): string | number | boolean | undefined {\n return getValue(this.#headers, name.toLowerCase());\n }\n\n getHeaders(): Record<string, HeaderValue> {\n return {\n ...this.#headers\n };\n }\n\n hasStatus() {\n return this.#status !== 200;\n }\n\n /**\n * Set header `field` to `val`, or pass\n * an object of header fields.\n *\n * Examples:\n * ```typescript\n * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });\n * ```\n *\n * Aliased as `res.header()`.\n */\n setHeaders(headers: Record<string, HeaderValue>) {\n // apply headers\n Object.entries(headers).forEach(([key, item]) => {\n this.setHeader(key, item);\n });\n\n return this;\n }\n\n setHeader(key: string, item: HeaderValue | null | undefined) {\n if (item !== null && item !== undefined) {\n key = key.toLowerCase();\n\n if (key === \"location\") {\n // \"back\" is an alias for the referrer\n if (item === \"back\") {\n item = this.request.get(\"Referrer\") || \"/\";\n }\n\n item = encodeUrl(String(item));\n }\n\n this.#headers = {\n ...this.#headers,\n [key.toLowerCase()]: item as any\n };\n }\n\n return this;\n }\n\n /**\n * Set `Content-Type` response header with `type` through `mime.lookup()`\n * when it does not contain \"/\", or set the Content-Type to `type` otherwise.\n *\n * Examples:\n *\n * res.type('.html');\n * res.type('html');\n * res.type('json');\n * res.type('application/json');\n * res.type('png');\n */\n contentType(contentType: string) {\n this.setHeader(\"Content-Type\", mime.getType(contentType));\n\n return this;\n }\n\n contentLength(length: number) {\n this.setHeader(\"Content-Length\", length);\n return this;\n }\n\n getContentLength() {\n if (this.get(\"Content-Length\")) {\n return parseInt(this.get(\"Content-Length\") as any, 10) || 0;\n }\n }\n\n getContentType() {\n return String(this.get(\"Content-Type\") || \"\").split(\";\")[0];\n }\n\n /**\n * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).\n * If not specified, status defaults to `302 Found`.\n *\n * @param status\n * @param url\n */\n redirect(status: number, url: string) {\n // Set location header\n const address = this.location(url).get(\"Location\");\n const body = `${getStatusMessage(status)}. Redirecting to ${address}`;\n\n this.status(status).set(\"Content-Length\", Buffer.byteLength(body)).body(body);\n\n return this;\n }\n\n /**\n * Sets the response Location HTTP header to the specified path parameter.\n *\n * @param url\n */\n location(url: string) {\n return this.set(\"Location\", url);\n }\n\n /**\n * Send any data to your consumer.\n *\n * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.\n * It choose the better way to send the data.\n *\n * @param body\n */\n body(body: any) {\n this.#body = body;\n\n return this;\n }\n\n getBody() {\n return this.#body;\n }\n\n isDone(): boolean {\n return this.#isHeadersSent;\n }\n\n onEnd(cb: Function) {\n this.#endListeners.push(cb);\n\n return this;\n }\n\n destroy() {\n this.#endListeners.forEach((cb: Function) => cb());\n this.#isHeadersSent = true;\n }\n}\n"]}
@@ -3,11 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getRequestId = void 0;
4
4
  const uuid_1 = require("uuid");
5
5
  function getRequestId(event, context) {
6
- var _a;
7
- if ((event === null || event === void 0 ? void 0 : event.headers) && event.headers["x-request-id"]) {
6
+ if (event?.headers && event.headers["x-request-id"]) {
8
7
  return event.headers["x-request-id"];
9
8
  }
10
- return ((_a = event === null || event === void 0 ? void 0 : event.requestContext) === null || _a === void 0 ? void 0 : _a.requestId) || (context === null || context === void 0 ? void 0 : context.awsRequestId) || (0, uuid_1.v4)().replace(/-/gi, "");
9
+ return event?.requestContext?.requestId || context?.awsRequestId || (0, uuid_1.v4)().replace(/-/gi, "");
11
10
  }
12
11
  exports.getRequestId = getRequestId;
13
12
  //# sourceMappingURL=getRequestId.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"getRequestId.js","sourceRoot":"","sources":["../../../src/utils/getRequestId.ts"],"names":[],"mappings":";;;AACA,+BAAwB;AAExB,SAAgB,YAAY,CAAC,KAAwE,EAAE,OAAgB;;IACrH,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,KAAI,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;KACtC;IAED,OAAO,CAAA,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,cAAc,0CAAE,SAAS,MAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,CAAA,IAAI,IAAA,SAAE,GAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC;AAND,oCAMC","sourcesContent":["import {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {v4} from \"uuid\";\n\nexport function getRequestId(event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>, context: Context) {\n if (event?.headers && event.headers[\"x-request-id\"]) {\n return event.headers[\"x-request-id\"];\n }\n\n return event?.requestContext?.requestId || context?.awsRequestId || v4().replace(/-/gi, \"\");\n}\n"]}
1
+ {"version":3,"file":"getRequestId.js","sourceRoot":"","sources":["../../../src/utils/getRequestId.ts"],"names":[],"mappings":";;;AACA,+BAAwB;AAExB,SAAgB,YAAY,CAAC,KAAwE,EAAE,OAAgB;IACrH,IAAI,KAAK,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;KACtC;IAED,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,IAAI,OAAO,EAAE,YAAY,IAAI,IAAA,SAAE,GAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC;AAND,oCAMC","sourcesContent":["import {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {v4} from \"uuid\";\n\nexport function getRequestId(event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>, context: Context) {\n if (event?.headers && event.headers[\"x-request-id\"]) {\n return event.headers[\"x-request-id\"];\n }\n\n return event?.requestContext?.requestId || context?.awsRequestId || v4().replace(/-/gi, \"\");\n}\n"]}
@@ -9,9 +9,10 @@ import { PlatformServerlessHandler } from "./PlatformServerlessHandler.js";
9
9
  * @platform
10
10
  */
11
11
  export class PlatformServerless {
12
- constructor() {
13
- this.name = "PlatformServerless";
14
- }
12
+ name = "PlatformServerless";
13
+ _injector;
14
+ _router;
15
+ _promise;
15
16
  get injector() {
16
17
  return this._injector;
17
18
  }
@@ -55,14 +56,13 @@ export class PlatformServerless {
55
56
  .reduce((callbacks, token) => {
56
57
  const routes = getOperationsRoutes(token);
57
58
  return routes.reduce((callbacks, operationRoute) => {
58
- var _a;
59
59
  const { operationId, token, propertyName, method, url } = operationRoute;
60
60
  // istanbul ignore next
61
61
  if (method === "USE") {
62
62
  return callbacks;
63
63
  }
64
64
  const callback = this.callback(token, propertyName);
65
- (_a = this._router) === null || _a === void 0 ? void 0 : _a.on(method, url, callback);
65
+ this._router?.on(method, url, callback);
66
66
  return {
67
67
  ...callbacks,
68
68
  [operationId]: callback
@@ -112,12 +112,11 @@ export class PlatformServerless {
112
112
  return this._router;
113
113
  }
114
114
  createInjector(settings) {
115
- var _a;
116
115
  this._injector = new InjectorService();
117
116
  this.injector.logger = $log;
118
117
  this.injector.settings.set(settings);
119
118
  // istanbul ignore next
120
- if (this.injector.settings.get("env") === Env.TEST && !((_a = settings === null || settings === void 0 ? void 0 : settings.logger) === null || _a === void 0 ? void 0 : _a.level)) {
119
+ if (this.injector.settings.get("env") === Env.TEST && !settings?.logger?.level) {
121
120
  $log.stop();
122
121
  }
123
122
  return this;
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformServerless.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerless.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAO,MAAM,YAAY,CAAC;AACrC,OAAO,EAAC,eAAe,EAAE,eAAe,EAAE,sBAAsB,EAAC,MAAM,UAAU,CAAC;AAClF,OAAO,EAAC,IAAI,EAAS,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAC,mBAAmB,EAAE,eAAe,EAAC,MAAM,cAAc,CAAC;AAGlE,OAAO,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAC,YAAY,EAAC,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAC,yBAAyB,EAAC,MAAM,6BAA6B,CAAC;AAMtE;;GAEG;AACH,MAAM,OAAO,kBAAkB;IAA/B;QACW,SAAI,GAAW,oBAAoB,CAAC;IA6J/C,CAAC;IAvJC,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC;IAChC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,MAAM,CAAC,SAAS,CAAC,WAA4D,EAAE;QAC7E,MAAM,QAAQ,GAAG,IAAI,kBAAkB,EAAE,CAAC;QAC1C,QAAQ,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QAElC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAEM,OAAO;QACZ,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;YAC9B,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,IAAI,CAAC,IAAI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,CAAC,QAAQ,CAAC,CAAC;QAEtC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAExC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEpC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACzC,CAAC;CACF","sourcesContent":["import {Env, Type} from \"@tsed/core\";\nimport {createContainer, InjectorService, setLoggerConfiguration} from \"@tsed/di\";\nimport {$log, Logger} from \"@tsed/logger\";\nimport {getOperationsRoutes, JsonEntityStore} from \"@tsed/schema\";\nimport type {APIGatewayProxyResult, Handler} from \"aws-lambda\";\nimport type {HTTPMethod, Instance} from \"find-my-way\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {getRequestId} from \"../utils/getRequestId\";\nimport {PlatformServerlessHandler} from \"./PlatformServerlessHandler\";\n\nexport interface PlatformServerlessSettings extends Partial<TsED.Configuration> {\n lambda?: Type[];\n}\n\n/**\n * @platform\n */\nexport class PlatformServerless {\n readonly name: string = \"PlatformServerless\";\n\n private _injector: InjectorService;\n private _router: Instance<any>;\n private _promise: Promise<any>;\n\n get injector(): InjectorService {\n return this._injector;\n }\n\n get settings() {\n return this.injector.settings;\n }\n\n get promise() {\n return this._promise;\n }\n\n static bootstrap(settings: Partial<TsED.Configuration> & {lambda?: Type[]} = {}): PlatformServerless {\n const platform = new PlatformServerless();\n platform.createInjector(settings);\n\n return platform;\n }\n\n public handler(): Handler {\n return async (event, context) => {\n const [router] = await Promise.all([this.initRouter(), this.init()]);\n const result = router.find(event.httpMethod as any, event.path);\n\n if (result) {\n const {handler, params} = result;\n\n event.pathParameters = {\n ...(event.pathParameters || {}),\n ...params\n };\n\n return (handler as any)(event, context);\n }\n\n return {\n statusCode: 404,\n body: \"Not found\",\n headers: {\n \"x-request-id\": getRequestId(event, context)\n },\n isBase64Encoded: false\n };\n };\n }\n\n public callbacks(tokens: Type | Type[] = [], callbacks: any = {}): Record<string, Handler> {\n return this.settings\n .get<Type[]>(\"lambda\", [])\n .concat(tokens)\n .reduce((callbacks, token) => {\n const routes = getOperationsRoutes(token);\n\n return routes.reduce((callbacks, operationRoute) => {\n const {operationId, token, propertyName, method, url} = operationRoute;\n\n // istanbul ignore next\n if (method === \"USE\") {\n return callbacks;\n }\n\n const callback = this.callback(token, propertyName);\n\n this._router?.on(method as HTTPMethod, url as string, callback as any);\n\n return {\n ...callbacks,\n [operationId]: callback\n };\n }, callbacks);\n }, callbacks);\n }\n\n public async ready() {\n await this.injector.emit(\"$onReady\");\n }\n\n public async stop() {\n await this.injector.emit(\"$onDestroy\");\n return this.injector.destroy();\n }\n\n public async init() {\n if (!this._promise) {\n this._promise = this.loadInjector().then(() => this.ready());\n }\n\n return this._promise;\n }\n\n protected callback(token: Type<any>, propertyKey: string): Handler {\n const entity = JsonEntityStore.fromMethod(token, propertyKey);\n let handler: ($ctx: ServerlessContext) => Promise<APIGatewayProxyResult>;\n\n return async (event, context) => {\n await this.init();\n\n if (!handler) {\n const platformHandler = this.injector.get<PlatformServerlessHandler>(PlatformServerlessHandler)!;\n handler = await platformHandler.createHandler(token, propertyKey);\n }\n\n const $ctx = new ServerlessContext({\n event,\n context,\n id: getRequestId(event, context),\n logger: this.injector.logger as Logger,\n injector: this.injector,\n endpoint: entity\n });\n\n return handler($ctx);\n };\n }\n\n protected async initRouter() {\n if (!this._router) {\n const {default: FindMyMay} = await import(\"find-my-way\");\n\n this._router = FindMyMay({caseSensitive: false, ignoreTrailingSlash: true});\n\n this.callbacks();\n }\n\n return this._router;\n }\n\n protected createInjector(settings: any) {\n this._injector = new InjectorService();\n this.injector.logger = $log;\n this.injector.settings.set(settings);\n\n // istanbul ignore next\n if (this.injector.settings.get(\"env\") === Env.TEST && !settings?.logger?.level) {\n $log.stop();\n }\n\n return this;\n }\n\n protected async loadInjector() {\n const container = createContainer();\n\n setLoggerConfiguration(this.injector);\n\n await this.injector.emit(\"$beforeInit\");\n\n await this.injector.load(container);\n\n await this.injector.emit(\"$afterInit\");\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformServerless.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerless.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAO,MAAM,YAAY,CAAC;AACrC,OAAO,EAAC,eAAe,EAAE,eAAe,EAAE,sBAAsB,EAAC,MAAM,UAAU,CAAC;AAClF,OAAO,EAAC,IAAI,EAAS,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAC,mBAAmB,EAAE,eAAe,EAAC,MAAM,cAAc,CAAC;AAGlE,OAAO,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAC,YAAY,EAAC,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAC,yBAAyB,EAAC,MAAM,6BAA6B,CAAC;AAMtE;;GAEG;AACH,MAAM,OAAO,kBAAkB;IACpB,IAAI,GAAW,oBAAoB,CAAC;IAErC,SAAS,CAAkB;IAC3B,OAAO,CAAgB;IACvB,QAAQ,CAAe;IAE/B,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC;IAChC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,MAAM,CAAC,SAAS,CAAC,WAA4D,EAAE;QAC7E,MAAM,QAAQ,GAAG,IAAI,kBAAkB,EAAE,CAAC;QAC1C,QAAQ,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QAElC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAEM,OAAO;QACZ,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;YAC9B,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,EAAE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,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAExC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEpC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACzC,CAAC;CACF","sourcesContent":["import {Env, Type} from \"@tsed/core\";\nimport {createContainer, InjectorService, setLoggerConfiguration} from \"@tsed/di\";\nimport {$log, Logger} from \"@tsed/logger\";\nimport {getOperationsRoutes, JsonEntityStore} from \"@tsed/schema\";\nimport type {APIGatewayProxyResult, Handler} from \"aws-lambda\";\nimport type {HTTPMethod, Instance} from \"find-my-way\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {getRequestId} from \"../utils/getRequestId\";\nimport {PlatformServerlessHandler} from \"./PlatformServerlessHandler\";\n\nexport interface PlatformServerlessSettings extends Partial<TsED.Configuration> {\n lambda?: Type[];\n}\n\n/**\n * @platform\n */\nexport class PlatformServerless {\n readonly name: string = \"PlatformServerless\";\n\n private _injector: InjectorService;\n private _router: Instance<any>;\n private _promise: Promise<any>;\n\n get injector(): InjectorService {\n return this._injector;\n }\n\n get settings() {\n return this.injector.settings;\n }\n\n get promise() {\n return this._promise;\n }\n\n static bootstrap(settings: Partial<TsED.Configuration> & {lambda?: Type[]} = {}): PlatformServerless {\n const platform = new PlatformServerless();\n platform.createInjector(settings);\n\n return platform;\n }\n\n public handler(): Handler {\n return async (event, context) => {\n const [router] = await Promise.all([this.initRouter(), this.init()]);\n const result = router.find(event.httpMethod as any, event.path);\n\n if (result) {\n const {handler, params} = result;\n\n event.pathParameters = {\n ...(event.pathParameters || {}),\n ...params\n };\n\n return (handler as any)(event, context);\n }\n\n return {\n statusCode: 404,\n body: \"Not found\",\n headers: {\n \"x-request-id\": getRequestId(event, context)\n },\n isBase64Encoded: false\n };\n };\n }\n\n public callbacks(tokens: Type | Type[] = [], callbacks: any = {}): Record<string, Handler> {\n return this.settings\n .get<Type[]>(\"lambda\", [])\n .concat(tokens)\n .reduce((callbacks, token) => {\n const routes = getOperationsRoutes(token);\n\n return routes.reduce((callbacks, operationRoute) => {\n const {operationId, token, propertyName, method, url} = operationRoute;\n\n // istanbul ignore next\n if (method === \"USE\") {\n return callbacks;\n }\n\n const callback = this.callback(token, propertyName);\n\n this._router?.on(method as HTTPMethod, url as string, callback as any);\n\n return {\n ...callbacks,\n [operationId]: callback\n };\n }, callbacks);\n }, callbacks);\n }\n\n public async ready() {\n await this.injector.emit(\"$onReady\");\n }\n\n public async stop() {\n await this.injector.emit(\"$onDestroy\");\n return this.injector.destroy();\n }\n\n public async init() {\n if (!this._promise) {\n this._promise = this.loadInjector().then(() => this.ready());\n }\n\n return this._promise;\n }\n\n protected callback(token: Type<any>, propertyKey: string): Handler {\n const entity = JsonEntityStore.fromMethod(token, propertyKey);\n let handler: ($ctx: ServerlessContext) => Promise<APIGatewayProxyResult>;\n\n return async (event, context) => {\n await this.init();\n\n if (!handler) {\n const platformHandler = this.injector.get<PlatformServerlessHandler>(PlatformServerlessHandler)!;\n handler = await platformHandler.createHandler(token, propertyKey);\n }\n\n const $ctx = new ServerlessContext({\n event,\n context,\n id: getRequestId(event, context),\n logger: this.injector.logger as Logger,\n injector: this.injector,\n endpoint: entity\n });\n\n return handler($ctx);\n };\n }\n\n protected async initRouter() {\n if (!this._router) {\n const {default: FindMyMay} = await import(\"find-my-way\");\n\n this._router = FindMyMay({caseSensitive: false, ignoreTrailingSlash: true});\n\n this.callbacks();\n }\n\n return this._router;\n }\n\n protected createInjector(settings: any) {\n this._injector = new InjectorService();\n this.injector.logger = $log;\n this.injector.settings.set(settings);\n\n // istanbul ignore next\n if (this.injector.settings.get(\"env\") === Env.TEST && !settings?.logger?.level) {\n $log.stop();\n }\n\n return this;\n }\n\n protected async loadInjector() {\n const container = createContainer();\n\n setLoggerConfiguration(this.injector);\n\n await this.injector.emit(\"$beforeInit\");\n\n await this.injector.load(container);\n\n await this.injector.emit(\"$afterInit\");\n }\n}\n"]}
@@ -1,18 +1,21 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
2
  import { AnyToPromise, isSerializable } from "@tsed/core";
3
- import { Inject, Injectable, InjectorService, LazyInject, ProviderScope, runInContext } from "@tsed/di";
3
+ import { Inject, Injectable, InjectorService, LazyInject, ProviderScope } from "@tsed/di";
4
4
  import { serialize } from "@tsed/json-mapper";
5
5
  import { DeserializerPipe, PlatformParams, ValidationPipe } from "@tsed/platform-params";
6
6
  import { setResponseHeaders } from "../utils/setResponseHeaders.js";
7
7
  let PlatformServerlessHandler = class PlatformServerlessHandler {
8
+ injector;
9
+ params;
10
+ exceptionsManager;
8
11
  createHandler(token, propertyKey) {
9
12
  const promisedHandler = this.params.compileHandler({
10
13
  token,
11
14
  propertyKey
12
15
  });
13
16
  return async ($ctx) => {
14
- await this.injector.emit("$onRequest", $ctx);
15
- await runInContext($ctx, async () => {
17
+ await $ctx.runInContext(async () => {
18
+ await this.injector.emit("$onRequest", $ctx);
16
19
  try {
17
20
  const resolver = new AnyToPromise();
18
21
  const handler = await promisedHandler;
@@ -24,8 +27,8 @@ let PlatformServerlessHandler = class PlatformServerlessHandler {
24
27
  const exceptions = await this.exceptionsManager;
25
28
  await exceptions.catch(er, $ctx);
26
29
  }
30
+ await this.injector.emit("$onResponse", $ctx);
27
31
  });
28
- await this.injector.emit("$onResponse", $ctx);
29
32
  return this.flush($ctx);
30
33
  };
31
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformServerlessHandler.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerlessHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAmB,YAAY,EAAE,cAAc,EAAC,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAc,MAAM,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAgB,MAAM,UAAU,CAAC;AAClI,OAAO,EAAC,SAAS,EAAC,MAAM,mBAAmB,CA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AAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;oBAC9D,QAAQ,EAAE,IAAI;oBACd,QAAQ,EAAE,IAAI;iBACf,CAAC,CAAC;aACJ;YAED,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SAC1B;IACH,CAAC;CACF,CAAA;AAtFC;IADC,MAAM,EAAE;8BACW,eAAe;2DAAC;AAGpC;IADC,MAAM,EAAE;8BACS,cAAc;yDAAC;AAGjC;IADC,UAAU,CAAC,oBAAoB,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC;;oEACnB;AAR9C,yBAAyB;IAJrC,UAAU,CAAC;QACV,KAAK,EAAE,aAAa,CAAC,SAAS;QAC9B,OAAO,EAAE,CAAC,gBAAgB,EAAE,cAAc,CAAC;KAC5C,CAAC;GACW,yBAAyB,CAwFrC;SAxFY,yBAAyB","sourcesContent":["import {AnyPromiseResult, AnyToPromise, isSerializable} from \"@tsed/core\";\nimport {BaseContext, Inject, Injectable, InjectorService, LazyInject, ProviderScope, runInContext, TokenProvider} from \"@tsed/di\";\nimport {serialize} from \"@tsed/json-mapper\";\nimport {DeserializerPipe, PlatformParams, ValidationPipe} from \"@tsed/platform-params\";\nimport type {PlatformExceptions} from \"@tsed/platform-exceptions\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {setResponseHeaders} from \"../utils/setResponseHeaders\";\n\n@Injectable({\n scope: ProviderScope.SINGLETON,\n imports: [DeserializerPipe, ValidationPipe]\n})\nexport class PlatformServerlessHandler {\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected params: PlatformParams;\n\n @LazyInject(\"PlatformExceptions\", () => import(\"@tsed/platform-exceptions\"))\n protected exceptionsManager: Promise<PlatformExceptions>;\n\n createHandler(token: TokenProvider, propertyKey: string | symbol) {\n const promisedHandler = this.params.compileHandler({\n token,\n propertyKey\n });\n\n return async ($ctx: ServerlessContext) => {\n await this.injector.emit(\"$onRequest\", $ctx);\n\n await runInContext($ctx, async () => {\n try {\n const resolver = new AnyToPromise();\n const handler = await promisedHandler;\n const result = await resolver.call(() => handler({$ctx}));\n\n this.processResult(result, $ctx);\n } catch (er) {\n $ctx.response.status(500).body(er);\n const exceptions = await this.exceptionsManager;\n\n await exceptions.catch(er, $ctx as unknown as BaseContext);\n }\n });\n\n await this.injector.emit(\"$onResponse\", $ctx);\n\n return this.flush($ctx);\n };\n }\n\n private flush($ctx: ServerlessContext) {\n setResponseHeaders($ctx);\n\n let body: any = $ctx.response.getBody();\n\n if (isSerializable(body)) {\n $ctx.response.set(\"content-type\", \"application/json\");\n body = JSON.stringify(body);\n }\n\n const response = {\n statusCode: $ctx.response.getStatus(),\n body: body === undefined ? \"\" : body,\n headers: {\n ...$ctx.response.getHeaders(),\n \"x-request-id\": $ctx.id\n },\n isBase64Encoded: false\n };\n\n $ctx.destroy();\n\n return response;\n }\n\n private processResult({status, headers, data}: AnyPromiseResult, $ctx: ServerlessContext) {\n if (status) {\n $ctx.response.status(status);\n }\n\n if (headers) {\n $ctx.response.setHeaders(headers);\n }\n\n if (data !== undefined) {\n data = $ctx.response.getStatus() !== 204 ? data : \"\";\n\n if (isSerializable(data)) {\n data = serialize(data, {\n ...$ctx.endpoint.getResponseOptions($ctx.response.getStatus()),\n useAlias: true,\n endpoint: true\n });\n }\n\n $ctx.response.body(data);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformServerlessHandler.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerlessHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAmB,YAAY,EAAE,cAAc,EAAC,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAc,MAAM,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,EAAE,aAAa,EAA8B,MAAM,UAAU,CAAC;AAClI,OAAO,EAAC,SAAS,EAAC,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAC,gBAAgB,EAAE,c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;oBACrB,GAAG,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;oBAC9D,QAAQ,EAAE,IAAI;oBACd,QAAQ,EAAE,IAAI;iBACf,CAAC,CAAC;aACJ;YAED,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SAC1B;IACH,CAAC;CACF,CAAA;AAtFC;IADC,MAAM,EAAE;8BACW,eAAe;2DAAC;AAGpC;IADC,MAAM,EAAE;8BACS,cAAc;yDAAC;AAGjC;IADC,UAAU,CAAC,oBAAoB,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC;;oEACnB;AAR9C,yBAAyB;IAJrC,UAAU,CAAC;QACV,KAAK,EAAE,aAAa,CAAC,SAAS;QAC9B,OAAO,EAAE,CAAC,gBAAgB,EAAE,cAAc,CAAC;KAC5C,CAAC;GACW,yBAAyB,CAwFrC;SAxFY,yBAAyB","sourcesContent":["import {AnyPromiseResult, AnyToPromise, isSerializable} from \"@tsed/core\";\nimport {BaseContext, Inject, Injectable, InjectorService, LazyInject, ProviderScope, runInContext, TokenProvider} from \"@tsed/di\";\nimport {serialize} from \"@tsed/json-mapper\";\nimport {DeserializerPipe, PlatformParams, ValidationPipe} from \"@tsed/platform-params\";\nimport type {PlatformExceptions} from \"@tsed/platform-exceptions\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {setResponseHeaders} from \"../utils/setResponseHeaders\";\n\n@Injectable({\n scope: ProviderScope.SINGLETON,\n imports: [DeserializerPipe, ValidationPipe]\n})\nexport class PlatformServerlessHandler {\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected params: PlatformParams;\n\n @LazyInject(\"PlatformExceptions\", () => import(\"@tsed/platform-exceptions\"))\n protected exceptionsManager: Promise<PlatformExceptions>;\n\n createHandler(token: TokenProvider, propertyKey: string | symbol) {\n const promisedHandler = this.params.compileHandler({\n token,\n propertyKey\n });\n\n return async ($ctx: ServerlessContext) => {\n await $ctx.runInContext(async () => {\n await this.injector.emit(\"$onRequest\", $ctx);\n\n try {\n const resolver = new AnyToPromise();\n const handler = await promisedHandler;\n const result = await resolver.call(() => handler({$ctx}));\n\n this.processResult(result, $ctx);\n } catch (er) {\n $ctx.response.status(500).body(er);\n const exceptions = await this.exceptionsManager;\n\n await exceptions.catch(er, $ctx as unknown as BaseContext);\n }\n\n await this.injector.emit(\"$onResponse\", $ctx);\n });\n\n return this.flush($ctx);\n };\n }\n\n private flush($ctx: ServerlessContext) {\n setResponseHeaders($ctx);\n\n let body: any = $ctx.response.getBody();\n\n if (isSerializable(body)) {\n $ctx.response.set(\"content-type\", \"application/json\");\n body = JSON.stringify(body);\n }\n\n const response = {\n statusCode: $ctx.response.getStatus(),\n body: body === undefined ? \"\" : body,\n headers: {\n ...$ctx.response.getHeaders(),\n \"x-request-id\": $ctx.id\n },\n isBase64Encoded: false\n };\n\n $ctx.destroy();\n\n return response;\n }\n\n private processResult({status, headers, data}: AnyPromiseResult, $ctx: ServerlessContext) {\n if (status) {\n $ctx.response.status(status);\n }\n\n if (headers) {\n $ctx.response.setHeaders(headers);\n }\n\n if (data !== undefined) {\n data = $ctx.response.getStatus() !== 204 ? data : \"\";\n\n if (isSerializable(data)) {\n data = serialize(data, {\n ...$ctx.endpoint.getResponseOptions($ctx.response.getStatus()),\n useAlias: true,\n endpoint: true\n });\n }\n\n $ctx.response.body(data);\n }\n }\n}\n"]}
@@ -2,6 +2,11 @@ import { DIContext } from "@tsed/di";
2
2
  import { ServerlessRequest } from "./ServerlessRequest.js";
3
3
  import { ServerlessResponse } from "./ServerlessResponse.js";
4
4
  export class ServerlessContext extends DIContext {
5
+ response;
6
+ request;
7
+ context;
8
+ event;
9
+ endpoint;
5
10
  constructor({ event, context, endpoint, ...options }) {
6
11
  super({
7
12
  ...options,
@@ -1 +1 @@
1
- {"version":3,"file":"ServerlessContext.js","sourceRoot":"","sources":["../../../src/domain/ServerlessContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAmB,MAAM,UAAU,CAAC;AAGrD,OAAO,EAAC,iBAAiB,EAAC,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAC,kBAAkB,EAAC,MAAM,sBAAsB,CAAC;AAQxD,MAAM,OAAO,iBAAkB,SAAQ,SAAS;IAO9C,YAAY,EAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAA2B;QAC1E,KAAK,CAAC;YACJ,GAAG,OAAO;YACV,YAAY,EAAE,CAAC;SAChB,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,IAAI,iBAAiB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAC,CAAC,CAAC;QACvD,IAAI,CAAC,QAAQ,GAAG,IAAI,kBAAkB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAC,CAAC,CAAC;QAChF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {DIContext, DIContextOptions} from \"@tsed/di\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {ServerlessRequest} from \"./ServerlessRequest\";\nimport {ServerlessResponse} from \"./ServerlessResponse\";\n\nexport interface ServerlessContextOptions extends DIContextOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n endpoint: JsonEntityStore;\n}\n\nexport class ServerlessContext extends DIContext {\n readonly response: ServerlessResponse;\n readonly request: ServerlessRequest;\n readonly context: Context;\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly endpoint: JsonEntityStore;\n\n constructor({event, context, endpoint, ...options}: ServerlessContextOptions) {\n super({\n ...options,\n maxStackSize: 0\n });\n this.context = context;\n this.event = event;\n this.request = new ServerlessRequest({event, context});\n this.response = new ServerlessResponse({event, context, request: this.request});\n this.endpoint = endpoint;\n }\n\n async destroy() {\n await super.destroy();\n\n this.request.destroy();\n this.response.destroy();\n }\n}\n"]}
1
+ {"version":3,"file":"ServerlessContext.js","sourceRoot":"","sources":["../../../src/domain/ServerlessContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAmB,MAAM,UAAU,CAAC;AAGrD,OAAO,EAAC,iBAAiB,EAAC,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAC,kBAAkB,EAAC,MAAM,sBAAsB,CAAC;AAQxD,MAAM,OAAO,iBAAkB,SAAQ,SAAS;IACrC,QAAQ,CAAqB;IAC7B,OAAO,CAAoB;IAC3B,OAAO,CAAU;IACjB,KAAK,CAAoE;IACzE,QAAQ,CAAkB;IAEnC,YAAY,EAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAA2B;QAC1E,KAAK,CAAC;YACJ,GAAG,OAAO;YACV,YAAY,EAAE,CAAC;SAChB,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,IAAI,iBAAiB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAC,CAAC,CAAC;QACvD,IAAI,CAAC,QAAQ,GAAG,IAAI,kBAAkB,CAAC,EAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAC,CAAC,CAAC;QAChF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {DIContext, DIContextOptions} from \"@tsed/di\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {ServerlessRequest} from \"./ServerlessRequest\";\nimport {ServerlessResponse} from \"./ServerlessResponse\";\n\nexport interface ServerlessContextOptions extends DIContextOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n endpoint: JsonEntityStore;\n}\n\nexport class ServerlessContext extends DIContext {\n readonly response: ServerlessResponse;\n readonly request: ServerlessRequest;\n readonly context: Context;\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly endpoint: JsonEntityStore;\n\n constructor({event, context, endpoint, ...options}: ServerlessContextOptions) {\n super({\n ...options,\n maxStackSize: 0\n });\n this.context = context;\n this.event = event;\n this.request = new ServerlessRequest({event, context});\n this.response = new ServerlessResponse({event, context, request: this.request});\n this.endpoint = endpoint;\n }\n\n async destroy() {\n await super.destroy();\n\n this.request.destroy();\n this.response.destroy();\n }\n}\n"]}
@@ -3,6 +3,7 @@ import { getValue } from "@tsed/core";
3
3
  * @platform
4
4
  */
5
5
  export class ServerlessRequest {
6
+ raw;
6
7
  constructor({ event }) {
7
8
  this.raw = event;
8
9
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ServerlessRequest.js","sourceRoot":"","sources":["../../../src/domain/ServerlessRequest.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAC;AAMpC;;GAEG;AACH,MAAM,OA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AED,OAAO,KAAI,CAAC;CACb","sourcesContent":["import type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {getValue} from \"@tsed/core\";\n\nexport interface ServerlessRequestOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n}\n/**\n * @platform\n */\nexport class ServerlessRequest {\n readonly raw: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n\n constructor({event}: ServerlessRequestOptions) {\n this.raw = event;\n }\n\n get secure(): boolean {\n return true;\n }\n\n get host(): string {\n return this.get(\"host\");\n }\n\n get protocol(): string {\n return \"https\";\n }\n\n /**\n * Get the url of the request.\n *\n * Is equivalent of `express.response.originalUrl || express.response.url`.\n */\n get url(): string {\n return this.raw.path;\n }\n\n get headers() {\n return this.raw.headers;\n }\n\n get method(): string {\n return this.raw.httpMethod;\n }\n\n /**\n * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use\n * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.\n */\n get body(): any {\n try {\n return this.raw.body ? JSON.parse(this.raw.body) : {};\n } catch (er) {\n return this.raw.body;\n }\n }\n\n get rawBody(): any {\n return this.raw.body;\n }\n\n /**\n * This property is an object containing properties mapped to the named route `parameters`.\n * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.\n * This object defaults to `{}`.\n */\n get params(): {[key: string]: any} {\n return this.raw.pathParameters || {};\n }\n\n /**\n * This property is an object containing a property for each query string parameter in the route.\n * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.\n */\n get query(): {[key: string]: any} {\n return this.raw.queryStringParameters || {};\n }\n\n /**\n * Returns the HTTP request header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * request.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string) {\n return getValue(this.raw.headers, name);\n }\n\n destroy() {}\n}\n"]}
1
+ {"version":3,"file":"Serverless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E,CAAC;IAC9C,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CAAC,IAAY;QACd,OAAO,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,KAAI,CAAC;CACb","sourcesContent":["import type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {getValue} from \"@tsed/core\";\n\nexport interface ServerlessRequestOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n}\n/**\n * @platform\n */\nexport class ServerlessRequest {\n readonly raw: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n\n constructor({event}: ServerlessRequestOptions) {\n this.raw = event;\n }\n\n get secure(): boolean {\n return true;\n }\n\n get host(): string {\n return this.get(\"host\");\n }\n\n get protocol(): string {\n return \"https\";\n }\n\n /**\n * Get the url of the request.\n *\n * Is equivalent of `express.response.originalUrl || express.response.url`.\n */\n get url(): string {\n return this.raw.path;\n }\n\n get headers() {\n return this.raw.headers;\n }\n\n get method(): string {\n return this.raw.httpMethod;\n }\n\n /**\n * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use\n * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.\n */\n get body(): any {\n try {\n return this.raw.body ? JSON.parse(this.raw.body) : {};\n } catch (er) {\n return this.raw.body;\n }\n }\n\n get rawBody(): any {\n return this.raw.body;\n }\n\n /**\n * This property is an object containing properties mapped to the named route `parameters`.\n * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.\n * This object defaults to `{}`.\n */\n get params(): {[key: string]: any} {\n return this.raw.pathParameters || {};\n }\n\n /**\n * This property is an object containing a property for each query string parameter in the route.\n * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.\n */\n get query(): {[key: string]: any} {\n return this.raw.queryStringParameters || {};\n }\n\n /**\n * Returns the HTTP request header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * request.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string) {\n return getValue(this.raw.headers, name);\n }\n\n destroy() {}\n}\n"]}
@@ -1,5 +1,3 @@
1
- var _ServerlessResponse_status, _ServerlessResponse_body, _ServerlessResponse_headers, _ServerlessResponse_locals, _ServerlessResponse_isHeadersSent, _ServerlessResponse_endListeners;
2
- import { __classPrivateFieldGet, __classPrivateFieldSet } from "tslib";
3
1
  import { getValue } from "@tsed/core";
4
2
  import { getStatusMessage } from "@tsed/schema";
5
3
  import encodeUrl from "encodeurl";
@@ -8,13 +6,15 @@ import * as mime from "mime";
8
6
  * @platform
9
7
  */
10
8
  export class ServerlessResponse {
9
+ event;
10
+ request;
11
+ #status = 200;
12
+ #body = undefined;
13
+ #headers = {};
14
+ #locals = {};
15
+ #isHeadersSent = false;
16
+ #endListeners = [];
11
17
  constructor({ event, request }) {
12
- _ServerlessResponse_status.set(this, 200);
13
- _ServerlessResponse_body.set(this, undefined);
14
- _ServerlessResponse_headers.set(this, {});
15
- _ServerlessResponse_locals.set(this, {});
16
- _ServerlessResponse_isHeadersSent.set(this, false);
17
- _ServerlessResponse_endListeners.set(this, []);
18
18
  this.event = event;
19
19
  this.request = request;
20
20
  }
@@ -22,10 +22,10 @@ export class ServerlessResponse {
22
22
  * Get the current statusCode
23
23
  */
24
24
  get statusCode() {
25
- return __classPrivateFieldGet(this, _ServerlessResponse_status, "f");
25
+ return this.#status;
26
26
  }
27
27
  set statusCode(status) {
28
- __classPrivateFieldSet(this, _ServerlessResponse_status, status, "f");
28
+ this.#status = status;
29
29
  }
30
30
  /**
31
31
  * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
@@ -33,13 +33,13 @@ export class ServerlessResponse {
33
33
  * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
34
34
  */
35
35
  get locals() {
36
- return __classPrivateFieldGet(this, _ServerlessResponse_locals, "f");
36
+ return this.#locals;
37
37
  }
38
38
  get isHeadersSent() {
39
- return __classPrivateFieldGet(this, _ServerlessResponse_isHeadersSent, "f");
39
+ return this.#isHeadersSent;
40
40
  }
41
41
  getStatus() {
42
- return __classPrivateFieldGet(this, _ServerlessResponse_status, "f");
42
+ return this.#status;
43
43
  }
44
44
  /**
45
45
  * Sets the HTTP status for the response.
@@ -47,7 +47,7 @@ export class ServerlessResponse {
47
47
  * @param status
48
48
  */
49
49
  status(status) {
50
- __classPrivateFieldSet(this, _ServerlessResponse_status, status, "f");
50
+ this.#status = status;
51
51
  return this;
52
52
  }
53
53
  set(name, value) {
@@ -63,15 +63,15 @@ export class ServerlessResponse {
63
63
  * @param name
64
64
  */
65
65
  get(name) {
66
- return getValue(__classPrivateFieldGet(this, _ServerlessResponse_headers, "f"), name.toLowerCase());
66
+ return getValue(this.#headers, name.toLowerCase());
67
67
  }
68
68
  getHeaders() {
69
69
  return {
70
- ...__classPrivateFieldGet(this, _ServerlessResponse_headers, "f")
70
+ ...this.#headers
71
71
  };
72
72
  }
73
73
  hasStatus() {
74
- return __classPrivateFieldGet(this, _ServerlessResponse_status, "f") !== 200;
74
+ return this.#status !== 200;
75
75
  }
76
76
  /**
77
77
  * Set header `field` to `val`, or pass
@@ -101,10 +101,10 @@ export class ServerlessResponse {
101
101
  }
102
102
  item = encodeUrl(String(item));
103
103
  }
104
- __classPrivateFieldSet(this, _ServerlessResponse_headers, {
105
- ...__classPrivateFieldGet(this, _ServerlessResponse_headers, "f"),
104
+ this.#headers = {
105
+ ...this.#headers,
106
106
  [key.toLowerCase()]: item
107
- }, "f");
107
+ };
108
108
  }
109
109
  return this;
110
110
  }
@@ -167,23 +167,22 @@ export class ServerlessResponse {
167
167
  * @param body
168
168
  */
169
169
  body(body) {
170
- __classPrivateFieldSet(this, _ServerlessResponse_body, body, "f");
170
+ this.#body = body;
171
171
  return this;
172
172
  }
173
173
  getBody() {
174
- return __classPrivateFieldGet(this, _ServerlessResponse_body, "f");
174
+ return this.#body;
175
175
  }
176
176
  isDone() {
177
- return __classPrivateFieldGet(this, _ServerlessResponse_isHeadersSent, "f");
177
+ return this.#isHeadersSent;
178
178
  }
179
179
  onEnd(cb) {
180
- __classPrivateFieldGet(this, _ServerlessResponse_endListeners, "f").push(cb);
180
+ this.#endListeners.push(cb);
181
181
  return this;
182
182
  }
183
183
  destroy() {
184
- __classPrivateFieldGet(this, _ServerlessResponse_endListeners, "f").forEach((cb) => cb());
185
- __classPrivateFieldSet(this, _ServerlessResponse_isHeadersSent, true, "f");
184
+ this.#endListeners.forEach((cb) => cb());
185
+ this.#isHeadersSent = true;
186
186
  }
187
187
  }
188
- _ServerlessResponse_status = new WeakMap(), _ServerlessResponse_body = new WeakMap(), _ServerlessResponse_headers = new WeakMap(), _ServerlessResponse_locals = new WeakMap(), _ServerlessResponse_isHeadersSent = new WeakMap(), _ServerlessResponse_endListeners = new WeakMap();
189
188
  //# sourceMappingURL=ServerlessResponse.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServerlessResponse.js","sourceRoot":"","sources":["../../../src/domain/ServerlessResponse.ts"],"names":[],"mappings":";;AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAC;AACpC,OAAO,EAAC,gBAAgB,EAAC,MAAM,cAAc,CAAC;AAE9C,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAW7B;;GAEG;AACH,MAAM,OAAO,kBAAkB;IAW7B,YAAY,EAAC,KAAK,EAAE,OAAO,EAA4B;QAPvD,qCAAkB,GAAG,EAAC;QACtB,mCAAa,SAAS,EAAC;QACvB,sCAAwC,EAAE,EAAC;QAC3C,qCAA+B,EAAE,EAAC;QAClC,4CAAiB,KAAK,EAAC;QACvB,2CAA4B,EAAE,EAAC;QAG7B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;I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;QAClC,sBAAsB;QACtB,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,IAAI,GAAG,GAAG,gBAAgB,CAAC,MAAM,CAAC,oBAAoB,OAAO,EAAE,CAAC;QAEtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAE9E,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,GAAW;QAClB,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IACnC,CAAC;IAED;;;;;;;OAOG;IACH,IAAI,CAAC,IAAS;QACZ,uBAAA,IAAI,4BAAS,IAAI,MAAA,CAAC;QAElB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,uBAAA,IAAI,gCAAM,CAAC;IACpB,CAAC;IAED,MAAM;QACJ,OAAO,uBAAA,IAAI,yCAAe,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,EAAY;QAChB,uBAAA,IAAI,wCAAc,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,uBAAA,IAAI,wCAAc,CAAC,OAAO,CAAC,CAAC,EAAY,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QACnD,uBAAA,IAAI,qCAAkB,IAAI,MAAA,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import {getValue} from \"@tsed/core\";\nimport {getStatusMessage} from \"@tsed/schema\";\nimport type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport encodeUrl from \"encodeurl\";\nimport * as mime from \"mime\";\nimport type {ServerlessRequest} from \"./ServerlessRequest\";\n\nexport interface ServerlessResponseOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n request: ServerlessRequest;\n}\n\nexport type HeaderValue = boolean | number | string;\n\n/**\n * @platform\n */\nexport class ServerlessResponse {\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly request: ServerlessRequest;\n\n #status: number = 200;\n #body: any = undefined;\n #headers: Record<string, HeaderValue> = {};\n #locals: Record<string, any> = {};\n #isHeadersSent = false;\n #endListeners: Function[] = [];\n\n constructor({event, request}: ServerlessResponseOptions) {\n this.event = event;\n this.request = request;\n }\n\n /**\n * Get the current statusCode\n */\n get statusCode() {\n return this.#status;\n }\n\n set statusCode(status) {\n this.#status = status;\n }\n\n /**\n * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.\n *\n * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.\n */\n get locals() {\n return this.#locals;\n }\n\n get isHeadersSent() {\n return this.#isHeadersSent;\n }\n\n getStatus() {\n return this.#status;\n }\n\n /**\n * Sets the HTTP status for the response.\n *\n * @param status\n */\n status(status: number) {\n this.#status = status;\n return this;\n }\n\n set(name: string, value: any) {\n return this.setHeader(name, value);\n }\n\n /**\n * Returns the HTTP response header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * response.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string): string | number | boolean | undefined {\n return getValue(this.#headers, name.toLowerCase());\n }\n\n getHeaders(): Record<string, HeaderValue> {\n return {\n ...this.#headers\n };\n }\n\n hasStatus() {\n return this.#status !== 200;\n }\n\n /**\n * Set header `field` to `val`, or pass\n * an object of header fields.\n *\n * Examples:\n * ```typescript\n * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });\n * ```\n *\n * Aliased as `res.header()`.\n */\n setHeaders(headers: Record<string, HeaderValue>) {\n // apply headers\n Object.entries(headers).forEach(([key, item]) => {\n this.setHeader(key, item);\n });\n\n return this;\n }\n\n setHeader(key: string, item: HeaderValue | null | undefined) {\n if (item !== null && item !== undefined) {\n key = key.toLowerCase();\n\n if (key === \"location\") {\n // \"back\" is an alias for the referrer\n if (item === \"back\") {\n item = this.request.get(\"Referrer\") || \"/\";\n }\n\n item = encodeUrl(String(item));\n }\n\n this.#headers = {\n ...this.#headers,\n [key.toLowerCase()]: item as any\n };\n }\n\n return this;\n }\n\n /**\n * Set `Content-Type` response header with `type` through `mime.lookup()`\n * when it does not contain \"/\", or set the Content-Type to `type` otherwise.\n *\n * Examples:\n *\n * res.type('.html');\n * res.type('html');\n * res.type('json');\n * res.type('application/json');\n * res.type('png');\n */\n contentType(contentType: string) {\n this.setHeader(\"Content-Type\", mime.getType(contentType));\n\n return this;\n }\n\n contentLength(length: number) {\n this.setHeader(\"Content-Length\", length);\n return this;\n }\n\n getContentLength() {\n if (this.get(\"Content-Length\")) {\n return parseInt(this.get(\"Content-Length\") as any, 10) || 0;\n }\n }\n\n getContentType() {\n return String(this.get(\"Content-Type\") || \"\").split(\";\")[0];\n }\n\n /**\n * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).\n * If not specified, status defaults to `302 Found`.\n *\n * @param status\n * @param url\n */\n redirect(status: number, url: string) {\n // Set location header\n const address = this.location(url).get(\"Location\");\n const body = `${getStatusMessage(status)}. Redirecting to ${address}`;\n\n this.status(status).set(\"Content-Length\", Buffer.byteLength(body)).body(body);\n\n return this;\n }\n\n /**\n * Sets the response Location HTTP header to the specified path parameter.\n *\n * @param url\n */\n location(url: string) {\n return this.set(\"Location\", url);\n }\n\n /**\n * Send any data to your consumer.\n *\n * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.\n * It choose the better way to send the data.\n *\n * @param body\n */\n body(body: any) {\n this.#body = body;\n\n return this;\n }\n\n getBody() {\n return this.#body;\n }\n\n isDone(): boolean {\n return this.#isHeadersSent;\n }\n\n onEnd(cb: Function) {\n this.#endListeners.push(cb);\n\n return this;\n }\n\n destroy() {\n this.#endListeners.forEach((cb: Function) => cb());\n this.#isHeadersSent = true;\n }\n}\n"]}
1
+ {"version":3,"file":"ServerlessResponse.js","sourceRoot":"","sources":["../../../src/domain/ServerlessResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAC;AACpC,OAAO,EAAC,gBAAgB,EAAC,MAAM,cAAc,CAAC;AAE9C,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAW7B;;GAEG;AACH,MAAM,OAAO,kBAAkB;IACpB,KAAK,CAAoE;IACzE,OAAO,CAAoB;IAEpC,OAAO,GAAW,GAAG,CAAC;IACtB,KAAK,GAAQ,SAAS,CAAC;IACvB,QAAQ,GAAgC,EAAE,CAAC;IAC3C,OAAO,GAAwB,EAAE,CAAC;IAClC,cAAc,GAAG,KAAK,CAAC;IACvB,aAAa,GAAe,EAAE,CAAC;IAE/B,YAAY,EAAC,KAAK,EAAE,OAAO,EAA4B;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,IAAI,UAAU,CAAC,MAAM;QACnB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED;;;;OAIG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAc;QACnB,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,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IACnC,CAAC;IAED;;;;;;;OAOG;IACH,IAAI,CAAC,IAAS;QACZ,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAElB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,EAAY;QAChB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,EAAY,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QACnD,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import {getValue} from \"@tsed/core\";\nimport {getStatusMessage} from \"@tsed/schema\";\nimport type {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport encodeUrl from \"encodeurl\";\nimport * as mime from \"mime\";\nimport type {ServerlessRequest} from \"./ServerlessRequest\";\n\nexport interface ServerlessResponseOptions {\n event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n context: Context;\n request: ServerlessRequest;\n}\n\nexport type HeaderValue = boolean | number | string;\n\n/**\n * @platform\n */\nexport class ServerlessResponse {\n readonly event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>;\n readonly request: ServerlessRequest;\n\n #status: number = 200;\n #body: any = undefined;\n #headers: Record<string, HeaderValue> = {};\n #locals: Record<string, any> = {};\n #isHeadersSent = false;\n #endListeners: Function[] = [];\n\n constructor({event, request}: ServerlessResponseOptions) {\n this.event = event;\n this.request = request;\n }\n\n /**\n * Get the current statusCode\n */\n get statusCode() {\n return this.#status;\n }\n\n set statusCode(status) {\n this.#status = status;\n }\n\n /**\n * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.\n *\n * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.\n */\n get locals() {\n return this.#locals;\n }\n\n get isHeadersSent() {\n return this.#isHeadersSent;\n }\n\n getStatus() {\n return this.#status;\n }\n\n /**\n * Sets the HTTP status for the response.\n *\n * @param status\n */\n status(status: number) {\n this.#status = status;\n return this;\n }\n\n set(name: string, value: any) {\n return this.setHeader(name, value);\n }\n\n /**\n * Returns the HTTP response header specified by field. The match is case-insensitive.\n *\n * ```typescript\n * response.get('Content-Type') // => \"text/plain\"\n * ```\n *\n * @param name\n */\n get(name: string): string | number | boolean | undefined {\n return getValue(this.#headers, name.toLowerCase());\n }\n\n getHeaders(): Record<string, HeaderValue> {\n return {\n ...this.#headers\n };\n }\n\n hasStatus() {\n return this.#status !== 200;\n }\n\n /**\n * Set header `field` to `val`, or pass\n * an object of header fields.\n *\n * Examples:\n * ```typescript\n * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });\n * ```\n *\n * Aliased as `res.header()`.\n */\n setHeaders(headers: Record<string, HeaderValue>) {\n // apply headers\n Object.entries(headers).forEach(([key, item]) => {\n this.setHeader(key, item);\n });\n\n return this;\n }\n\n setHeader(key: string, item: HeaderValue | null | undefined) {\n if (item !== null && item !== undefined) {\n key = key.toLowerCase();\n\n if (key === \"location\") {\n // \"back\" is an alias for the referrer\n if (item === \"back\") {\n item = this.request.get(\"Referrer\") || \"/\";\n }\n\n item = encodeUrl(String(item));\n }\n\n this.#headers = {\n ...this.#headers,\n [key.toLowerCase()]: item as any\n };\n }\n\n return this;\n }\n\n /**\n * Set `Content-Type` response header with `type` through `mime.lookup()`\n * when it does not contain \"/\", or set the Content-Type to `type` otherwise.\n *\n * Examples:\n *\n * res.type('.html');\n * res.type('html');\n * res.type('json');\n * res.type('application/json');\n * res.type('png');\n */\n contentType(contentType: string) {\n this.setHeader(\"Content-Type\", mime.getType(contentType));\n\n return this;\n }\n\n contentLength(length: number) {\n this.setHeader(\"Content-Length\", length);\n return this;\n }\n\n getContentLength() {\n if (this.get(\"Content-Length\")) {\n return parseInt(this.get(\"Content-Length\") as any, 10) || 0;\n }\n }\n\n getContentType() {\n return String(this.get(\"Content-Type\") || \"\").split(\";\")[0];\n }\n\n /**\n * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).\n * If not specified, status defaults to `302 Found`.\n *\n * @param status\n * @param url\n */\n redirect(status: number, url: string) {\n // Set location header\n const address = this.location(url).get(\"Location\");\n const body = `${getStatusMessage(status)}. Redirecting to ${address}`;\n\n this.status(status).set(\"Content-Length\", Buffer.byteLength(body)).body(body);\n\n return this;\n }\n\n /**\n * Sets the response Location HTTP header to the specified path parameter.\n *\n * @param url\n */\n location(url: string) {\n return this.set(\"Location\", url);\n }\n\n /**\n * Send any data to your consumer.\n *\n * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.\n * It choose the better way to send the data.\n *\n * @param body\n */\n body(body: any) {\n this.#body = body;\n\n return this;\n }\n\n getBody() {\n return this.#body;\n }\n\n isDone(): boolean {\n return this.#isHeadersSent;\n }\n\n onEnd(cb: Function) {\n this.#endListeners.push(cb);\n\n return this;\n }\n\n destroy() {\n this.#endListeners.forEach((cb: Function) => cb());\n this.#isHeadersSent = true;\n }\n}\n"]}
@@ -1,9 +1,8 @@
1
1
  import { v4 } from "uuid";
2
2
  export function getRequestId(event, context) {
3
- var _a;
4
- if ((event === null || event === void 0 ? void 0 : event.headers) && event.headers["x-request-id"]) {
3
+ if (event?.headers && event.headers["x-request-id"]) {
5
4
  return event.headers["x-request-id"];
6
5
  }
7
- return ((_a = event === null || event === void 0 ? void 0 : event.requestContext) === null || _a === void 0 ? void 0 : _a.requestId) || (context === null || context === void 0 ? void 0 : context.awsRequestId) || v4().replace(/-/gi, "");
6
+ return event?.requestContext?.requestId || context?.awsRequestId || v4().replace(/-/gi, "");
8
7
  }
9
8
  //# sourceMappingURL=getRequestId.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"getRequestId.js","sourceRoot":"","sources":["../../../src/utils/getRequestId.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,EAAE,EAAC,MAAM,MAAM,CAAC;AAExB,MAAM,UAAU,YAAY,CAAC,KAAwE,EAAE,OAAgB;;IACrH,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,KAAI,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;KACtC;IAED,OAAO,CAAA,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,cAAc,0CAAE,SAAS,MAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,CAAA,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["import {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {v4} from \"uuid\";\n\nexport function getRequestId(event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>, context: Context) {\n if (event?.headers && event.headers[\"x-request-id\"]) {\n return event.headers[\"x-request-id\"];\n }\n\n return event?.requestContext?.requestId || context?.awsRequestId || v4().replace(/-/gi, \"\");\n}\n"]}
1
+ {"version":3,"file":"getRequestId.js","sourceRoot":"","sources":["../../../src/utils/getRequestId.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,EAAE,EAAC,MAAM,MAAM,CAAC;AAExB,MAAM,UAAU,YAAY,CAAC,KAAwE,EAAE,OAAgB;IACrH,IAAI,KAAK,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;KACtC;IAED,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,IAAI,OAAO,EAAE,YAAY,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["import {APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context} from \"aws-lambda\";\nimport {v4} from \"uuid\";\n\nexport function getRequestId(event: APIGatewayProxyEventBase<APIGatewayEventDefaultAuthorizerContext>, context: Context) {\n if (event?.headers && event.headers[\"x-request-id\"]) {\n return event.headers[\"x-request-id\"];\n }\n\n return event?.requestContext?.requestId || context?.awsRequestId || v4().replace(/-/gi, \"\");\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsed/platform-serverless",
3
- "version": "6.114.16",
3
+ "version": "6.115.0",
4
4
  "description": "Platform serverless module for Ts.ED Framework",
5
5
  "private": false,
6
6
  "source": "./src/index.ts",
@@ -21,25 +21,25 @@
21
21
  "test": "cross-env NODE_ENV=test jest"
22
22
  },
23
23
  "dependencies": {
24
- "@tsed/core": "6.114.16",
25
- "@tsed/exceptions": "6.114.16",
26
- "@tsed/json-mapper": "6.114.16",
27
- "@tsed/platform-exceptions": "6.114.16",
28
- "@tsed/platform-params": "6.114.16",
29
- "@tsed/schema": "6.114.16",
24
+ "@tsed/core": "6.115.0",
25
+ "@tsed/exceptions": "6.115.0",
26
+ "@tsed/json-mapper": "6.115.0",
27
+ "@tsed/platform-exceptions": "6.115.0",
28
+ "@tsed/platform-params": "6.115.0",
29
+ "@tsed/schema": "6.115.0",
30
30
  "encodeurl": "^1.0.2",
31
31
  "mime": "^2.5.2",
32
32
  "tslib": "2.4.0",
33
33
  "uuid": "^8.3.2"
34
34
  },
35
35
  "devDependencies": {
36
- "@tsed/platform-serverless-testing": "6.114.16",
36
+ "@tsed/platform-serverless-testing": "6.115.0",
37
37
  "@types/aws-lambda": "^8.10.83",
38
38
  "@types/encodeurl": "^1.0.0",
39
39
  "@types/mime": "^2.0.3"
40
40
  },
41
41
  "peerDependencies": {
42
- "@tsed/di": "^6.114.16",
42
+ "@tsed/di": "^6.115.0",
43
43
  "@tsed/logger": ">=6.1.4"
44
44
  },
45
45
  "peerDependenciesMeta": {