@tsed/platform-serverless 6.88.1 → 6.89.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/lib/{builder → cjs/builder}/PlatformServerless.d.ts +0 -0
- package/lib/cjs/builder/PlatformServerless.js +156 -0
- package/lib/cjs/builder/PlatformServerless.js.map +1 -0
- package/lib/{builder → cjs/builder}/PlatformServerlessHandler.d.ts +0 -0
- package/lib/cjs/builder/PlatformServerlessHandler.js +93 -0
- package/lib/cjs/builder/PlatformServerlessHandler.js.map +1 -0
- package/lib/{domain → cjs/domain}/ServerlessContext.d.ts +0 -0
- package/lib/cjs/domain/ServerlessContext.js +26 -0
- package/lib/cjs/domain/ServerlessContext.js.map +1 -0
- package/lib/{domain → cjs/domain}/ServerlessRequest.d.ts +0 -0
- package/lib/cjs/domain/ServerlessRequest.js +80 -0
- package/lib/cjs/domain/ServerlessRequest.js.map +1 -0
- package/lib/{domain → cjs/domain}/ServerlessResponse.d.ts +0 -0
- package/lib/cjs/domain/ServerlessResponse.js +193 -0
- package/lib/cjs/domain/ServerlessResponse.js.map +1 -0
- package/lib/{index.d.ts → cjs/index.d.ts} +0 -0
- package/lib/cjs/index.js +23 -0
- package/lib/cjs/index.js.map +1 -0
- package/lib/{services → cjs/services}/PlatformServerlessTest.d.ts +0 -0
- package/lib/cjs/services/PlatformServerlessTest.js +196 -0
- package/lib/cjs/services/PlatformServerlessTest.js.map +1 -0
- package/lib/{utils → cjs/utils}/getRequestId.d.ts +0 -0
- package/lib/cjs/utils/getRequestId.js +13 -0
- package/lib/cjs/utils/getRequestId.js.map +1 -0
- package/lib/{utils → cjs/utils}/setResponseHeaders.d.ts +0 -0
- package/lib/cjs/utils/setResponseHeaders.js +35 -0
- package/lib/cjs/utils/setResponseHeaders.js.map +1 -0
- package/lib/esm/builder/PlatformServerless.js +133 -0
- package/lib/esm/builder/PlatformServerless.js.map +1 -0
- package/lib/esm/builder/PlatformServerlessHandler.js +90 -0
- package/lib/esm/builder/PlatformServerlessHandler.js.map +1 -0
- package/lib/esm/domain/ServerlessContext.js +22 -0
- package/lib/esm/domain/ServerlessContext.js.map +1 -0
- package/lib/esm/domain/ServerlessRequest.js +76 -0
- package/lib/esm/domain/ServerlessRequest.js.map +1 -0
- package/lib/esm/domain/ServerlessResponse.js +189 -0
- package/lib/esm/domain/ServerlessResponse.js.map +1 -0
- package/lib/esm/index.js +11 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/services/PlatformServerlessTest.js +191 -0
- package/lib/esm/services/PlatformServerlessTest.js.map +1 -0
- package/lib/esm/utils/getRequestId.js +9 -0
- package/lib/esm/utils/getRequestId.js.map +1 -0
- package/lib/esm/utils/setResponseHeaders.js +31 -0
- package/lib/esm/utils/setResponseHeaders.js.map +1 -0
- package/lib/types/builder/PlatformServerless.d.ts +31 -0
- package/lib/types/builder/PlatformServerlessHandler.d.ts +19 -0
- package/lib/types/domain/ServerlessContext.d.ts +19 -0
- package/lib/types/domain/ServerlessRequest.d.ts +55 -0
- package/lib/types/domain/ServerlessResponse.d.ts +105 -0
- package/lib/types/index.d.ts +9 -0
- package/lib/types/services/PlatformServerlessTest.d.ts +46 -0
- package/lib/types/utils/getRequestId.d.ts +2 -0
- package/lib/types/utils/setResponseHeaders.d.ts +5 -0
- package/package.json +17 -13
- package/tsconfig.compile.esm.json +23 -0
- package/lib/index-a6c91998.js +0 -955
- package/lib/index-a6c91998.js.map +0 -1
- package/lib/index-a7574150.js +0 -975
- package/lib/index-a7574150.js.map +0 -1
- package/lib/index-b255dcf0.js +0 -2350
- package/lib/index-b255dcf0.js.map +0 -1
- package/lib/index-eeb85309.js +0 -2354
- package/lib/index-eeb85309.js.map +0 -1
- package/lib/index.js +0 -90
- package/lib/index.js.map +0 -1
- package/lib/index.modern.js +0 -12
- package/lib/index.modern.js.map +0 -1
|
File without changes
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
5
|
+
}) : (function(o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
o[k2] = m[k];
|
|
8
|
+
}));
|
|
9
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
10
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
11
|
+
}) : function(o, v) {
|
|
12
|
+
o["default"] = v;
|
|
13
|
+
});
|
|
14
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
15
|
+
if (mod && mod.__esModule) return mod;
|
|
16
|
+
var result = {};
|
|
17
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
18
|
+
__setModuleDefault(result, mod);
|
|
19
|
+
return result;
|
|
20
|
+
};
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.PlatformServerless = void 0;
|
|
23
|
+
const core_1 = require("@tsed/core");
|
|
24
|
+
const di_1 = require("@tsed/di");
|
|
25
|
+
const logger_1 = require("@tsed/logger");
|
|
26
|
+
const schema_1 = require("@tsed/schema");
|
|
27
|
+
const ServerlessContext_1 = require("../domain/ServerlessContext");
|
|
28
|
+
const PlatformServerlessHandler_1 = require("./PlatformServerlessHandler");
|
|
29
|
+
const getRequestId_1 = require("../utils/getRequestId");
|
|
30
|
+
/**
|
|
31
|
+
* @platform
|
|
32
|
+
*/
|
|
33
|
+
class PlatformServerless {
|
|
34
|
+
constructor() {
|
|
35
|
+
this.name = "PlatformServerless";
|
|
36
|
+
}
|
|
37
|
+
get injector() {
|
|
38
|
+
return this._injector;
|
|
39
|
+
}
|
|
40
|
+
get settings() {
|
|
41
|
+
return this.injector.settings;
|
|
42
|
+
}
|
|
43
|
+
get promise() {
|
|
44
|
+
return this._promise;
|
|
45
|
+
}
|
|
46
|
+
static bootstrap(settings = {}) {
|
|
47
|
+
const platform = new PlatformServerless();
|
|
48
|
+
platform.createInjector(settings);
|
|
49
|
+
return platform;
|
|
50
|
+
}
|
|
51
|
+
handler() {
|
|
52
|
+
return async (event, context) => {
|
|
53
|
+
const [router] = await Promise.all([this.initRouter(), this.init()]);
|
|
54
|
+
const result = router.find(event.httpMethod, event.path);
|
|
55
|
+
if (result) {
|
|
56
|
+
const { handler, params } = result;
|
|
57
|
+
event.pathParameters = {
|
|
58
|
+
...(event.pathParameters || {}),
|
|
59
|
+
...params
|
|
60
|
+
};
|
|
61
|
+
return handler(event, context);
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
statusCode: 404,
|
|
65
|
+
body: "Not found",
|
|
66
|
+
headers: {
|
|
67
|
+
"x-request-id": (0, getRequestId_1.getRequestId)(event, context)
|
|
68
|
+
},
|
|
69
|
+
isBase64Encoded: false
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
callbacks(tokens = [], callbacks = {}) {
|
|
74
|
+
return this.settings
|
|
75
|
+
.get("lambda", [])
|
|
76
|
+
.concat(tokens)
|
|
77
|
+
.reduce((callbacks, token) => {
|
|
78
|
+
const routes = (0, schema_1.getOperationsRoutes)(token);
|
|
79
|
+
return routes.reduce((callbacks, operationRoute) => {
|
|
80
|
+
var _a;
|
|
81
|
+
const { operationId, token, propertyName, method, url } = operationRoute;
|
|
82
|
+
// istanbul ignore next
|
|
83
|
+
if (method === "USE") {
|
|
84
|
+
return callbacks;
|
|
85
|
+
}
|
|
86
|
+
const callback = this.callback(token, propertyName);
|
|
87
|
+
(_a = this._router) === null || _a === void 0 ? void 0 : _a.on(method, url, callback);
|
|
88
|
+
return {
|
|
89
|
+
...callbacks,
|
|
90
|
+
[operationId]: callback
|
|
91
|
+
};
|
|
92
|
+
}, callbacks);
|
|
93
|
+
}, callbacks);
|
|
94
|
+
}
|
|
95
|
+
async ready() {
|
|
96
|
+
await this.injector.emit("$onReady");
|
|
97
|
+
}
|
|
98
|
+
async stop() {
|
|
99
|
+
await this.injector.emit("$onDestroy");
|
|
100
|
+
return this.injector.destroy();
|
|
101
|
+
}
|
|
102
|
+
async init() {
|
|
103
|
+
if (!this._promise) {
|
|
104
|
+
this._promise = this.loadInjector().then(() => this.ready());
|
|
105
|
+
}
|
|
106
|
+
return this._promise;
|
|
107
|
+
}
|
|
108
|
+
callback(token, propertyKey) {
|
|
109
|
+
const entity = schema_1.JsonEntityStore.fromMethod(token, propertyKey);
|
|
110
|
+
let handler;
|
|
111
|
+
return async (event, context) => {
|
|
112
|
+
await this.init();
|
|
113
|
+
if (!handler) {
|
|
114
|
+
const platformHandler = this.injector.get(PlatformServerlessHandler_1.PlatformServerlessHandler);
|
|
115
|
+
handler = await platformHandler.createHandler(token, propertyKey);
|
|
116
|
+
}
|
|
117
|
+
const $ctx = new ServerlessContext_1.ServerlessContext({
|
|
118
|
+
event,
|
|
119
|
+
context,
|
|
120
|
+
id: (0, getRequestId_1.getRequestId)(event, context),
|
|
121
|
+
logger: this.injector.logger,
|
|
122
|
+
injector: this.injector,
|
|
123
|
+
endpoint: entity
|
|
124
|
+
});
|
|
125
|
+
return handler($ctx);
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async initRouter() {
|
|
129
|
+
if (!this._router) {
|
|
130
|
+
const { default: FindMyMay } = await Promise.resolve().then(() => __importStar(require("find-my-way")));
|
|
131
|
+
this._router = FindMyMay({ caseSensitive: false, ignoreTrailingSlash: true });
|
|
132
|
+
this.callbacks();
|
|
133
|
+
}
|
|
134
|
+
return this._router;
|
|
135
|
+
}
|
|
136
|
+
createInjector(settings) {
|
|
137
|
+
var _a;
|
|
138
|
+
this._injector = new di_1.InjectorService();
|
|
139
|
+
this.injector.logger = logger_1.$log;
|
|
140
|
+
this.injector.settings.set(settings);
|
|
141
|
+
// istanbul ignore next
|
|
142
|
+
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)) {
|
|
143
|
+
logger_1.$log.stop();
|
|
144
|
+
}
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
async loadInjector() {
|
|
148
|
+
const container = (0, di_1.createContainer)();
|
|
149
|
+
(0, di_1.setLoggerLevel)(this.injector);
|
|
150
|
+
await this.injector.emit("$beforeInit");
|
|
151
|
+
await this.injector.load(container);
|
|
152
|
+
await this.injector.emit("$afterInit");
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
exports.PlatformServerless = PlatformServerless;
|
|
156
|
+
//# sourceMappingURL=PlatformServerless.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PlatformServerless.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerless.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAqC;AACrC,iCAA0E;AAC1E,yCAA0C;AAC1C,yCAAkE;AAGlE,mEAA8D;AAC9D,2EAAsE;AACtE,wDAAmD;AAMnD;;GAEG;AACH,MAAa,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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I,EAAE,CAAC;SACb;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAES,KAAK,CAAC,YAAY;QAC1B,MAAM,SAAS,GAAG,IAAA,oBAAe,GAAE,CAAC;QAEpC,IAAA,mBAAc,EAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAE9B,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, setLoggerLevel} from \"@tsed/di\";\nimport {$log, Logger} from \"@tsed/logger\";\nimport {getOperationsRoutes, JsonEntityStore} from \"@tsed/schema\";\nimport type {HTTPMethod, Instance} from \"find-my-way\";\nimport type {APIGatewayProxyResult, Handler} from \"aws-lambda\";\nimport {ServerlessContext} from \"../domain/ServerlessContext\";\nimport {PlatformServerlessHandler} from \"./PlatformServerlessHandler\";\nimport {getRequestId} from \"../utils/getRequestId\";\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 setLoggerLevel(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"]}
|
|
File without changes
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PlatformServerlessHandler = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const core_1 = require("@tsed/core");
|
|
6
|
+
const di_1 = require("@tsed/di");
|
|
7
|
+
const json_mapper_1 = require("@tsed/json-mapper");
|
|
8
|
+
const platform_params_1 = require("@tsed/platform-params");
|
|
9
|
+
const setResponseHeaders_1 = require("../utils/setResponseHeaders");
|
|
10
|
+
let PlatformServerlessHandler = class PlatformServerlessHandler {
|
|
11
|
+
createHandler(token, propertyKey) {
|
|
12
|
+
const promisedHandler = this.params.compileHandler({
|
|
13
|
+
token,
|
|
14
|
+
propertyKey
|
|
15
|
+
});
|
|
16
|
+
return async ($ctx) => {
|
|
17
|
+
await this.injector.emit("$onRequest", $ctx);
|
|
18
|
+
await this.injector.runInContext($ctx, async () => {
|
|
19
|
+
try {
|
|
20
|
+
const resolver = new core_1.AnyToPromise();
|
|
21
|
+
const handler = await promisedHandler;
|
|
22
|
+
const result = await resolver.call(() => handler({ $ctx }));
|
|
23
|
+
this.processResult(result, $ctx);
|
|
24
|
+
}
|
|
25
|
+
catch (er) {
|
|
26
|
+
$ctx.response.status(500).body(er);
|
|
27
|
+
const exceptions = await this.exceptionsManager;
|
|
28
|
+
await exceptions.catch(er, $ctx);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
await this.injector.emit("$onResponse", $ctx);
|
|
32
|
+
return this.flush($ctx);
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
flush($ctx) {
|
|
36
|
+
(0, setResponseHeaders_1.setResponseHeaders)($ctx);
|
|
37
|
+
let body = $ctx.response.getBody();
|
|
38
|
+
if ((0, core_1.isSerializable)(body)) {
|
|
39
|
+
$ctx.response.set("content-type", "application/json");
|
|
40
|
+
body = JSON.stringify(body);
|
|
41
|
+
}
|
|
42
|
+
const response = {
|
|
43
|
+
statusCode: $ctx.response.getStatus(),
|
|
44
|
+
body: body === undefined ? "" : body,
|
|
45
|
+
headers: {
|
|
46
|
+
...$ctx.response.getHeaders(),
|
|
47
|
+
"x-request-id": $ctx.id
|
|
48
|
+
},
|
|
49
|
+
isBase64Encoded: false
|
|
50
|
+
};
|
|
51
|
+
$ctx.destroy();
|
|
52
|
+
return response;
|
|
53
|
+
}
|
|
54
|
+
processResult({ status, headers, data }, $ctx) {
|
|
55
|
+
if (status) {
|
|
56
|
+
$ctx.response.status(status);
|
|
57
|
+
}
|
|
58
|
+
if (headers) {
|
|
59
|
+
$ctx.response.setHeaders(headers);
|
|
60
|
+
}
|
|
61
|
+
if (data !== undefined) {
|
|
62
|
+
data = $ctx.response.getStatus() !== 204 ? data : "";
|
|
63
|
+
if ((0, core_1.isSerializable)(data)) {
|
|
64
|
+
data = (0, json_mapper_1.serialize)(data, {
|
|
65
|
+
...$ctx.endpoint.getResponseOptions($ctx.response.getStatus()),
|
|
66
|
+
useAlias: true,
|
|
67
|
+
endpoint: true
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
$ctx.response.body(data);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
(0, tslib_1.__decorate)([
|
|
75
|
+
(0, di_1.Inject)(),
|
|
76
|
+
(0, tslib_1.__metadata)("design:type", di_1.InjectorService)
|
|
77
|
+
], PlatformServerlessHandler.prototype, "injector", void 0);
|
|
78
|
+
(0, tslib_1.__decorate)([
|
|
79
|
+
(0, di_1.Inject)(),
|
|
80
|
+
(0, tslib_1.__metadata)("design:type", platform_params_1.PlatformParams)
|
|
81
|
+
], PlatformServerlessHandler.prototype, "params", void 0);
|
|
82
|
+
(0, tslib_1.__decorate)([
|
|
83
|
+
(0, di_1.LazyInject)("PlatformExceptions", () => Promise.resolve().then(() => (0, tslib_1.__importStar)(require("@tsed/platform-exceptions")))),
|
|
84
|
+
(0, tslib_1.__metadata)("design:type", Promise)
|
|
85
|
+
], PlatformServerlessHandler.prototype, "exceptionsManager", void 0);
|
|
86
|
+
PlatformServerlessHandler = (0, tslib_1.__decorate)([
|
|
87
|
+
(0, di_1.Injectable)({
|
|
88
|
+
scope: di_1.ProviderScope.SINGLETON,
|
|
89
|
+
imports: [platform_params_1.DeserializerPipe, platform_params_1.ValidationPipe]
|
|
90
|
+
})
|
|
91
|
+
], PlatformServerlessHandler);
|
|
92
|
+
exports.PlatformServerlessHandler = PlatformServerlessHandler;
|
|
93
|
+
//# sourceMappingURL=PlatformServerlessHandler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PlatformServerlessHandler.js","sourceRoot":"","sources":["../../../src/builder/PlatformServerlessHandler.ts"],"names":[],"mappings":";;;;AAAA,qCAA0E;AAC1E,iCAAoH;AACpH,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,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,IAAI,EAAE;gBAChD,IAAI;oBACF,MAAM,QAAQ,GAAG,IAAI,mBAA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,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, 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 this.injector.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"]}
|
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ServerlessContext = void 0;
|
|
4
|
+
const di_1 = require("@tsed/di");
|
|
5
|
+
const ServerlessRequest_1 = require("./ServerlessRequest");
|
|
6
|
+
const ServerlessResponse_1 = require("./ServerlessResponse");
|
|
7
|
+
class ServerlessContext extends di_1.DIContext {
|
|
8
|
+
constructor({ event, context, endpoint, ...options }) {
|
|
9
|
+
super({
|
|
10
|
+
...options,
|
|
11
|
+
maxStackSize: 0
|
|
12
|
+
});
|
|
13
|
+
this.context = context;
|
|
14
|
+
this.event = event;
|
|
15
|
+
this.request = new ServerlessRequest_1.ServerlessRequest({ event, context });
|
|
16
|
+
this.response = new ServerlessResponse_1.ServerlessResponse({ event, context, request: this.request });
|
|
17
|
+
this.endpoint = endpoint;
|
|
18
|
+
}
|
|
19
|
+
async destroy() {
|
|
20
|
+
await super.destroy();
|
|
21
|
+
this.request.destroy();
|
|
22
|
+
this.response.destroy();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.ServerlessContext = ServerlessContext;
|
|
26
|
+
//# sourceMappingURL=ServerlessContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServerlessContext.js","sourceRoot":"","sources":["../../../src/domain/ServerlessContext.ts"],"names":[],"mappings":";;;AAAA,iCAAsE;AAGtE,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, LocalsContainer} 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"]}
|
|
File without changes
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ServerlessRequest = void 0;
|
|
4
|
+
const core_1 = require("@tsed/core");
|
|
5
|
+
/**
|
|
6
|
+
* @platform
|
|
7
|
+
*/
|
|
8
|
+
class ServerlessRequest {
|
|
9
|
+
constructor({ event }) {
|
|
10
|
+
this.raw = event;
|
|
11
|
+
}
|
|
12
|
+
get secure() {
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
get host() {
|
|
16
|
+
return this.get("host");
|
|
17
|
+
}
|
|
18
|
+
get protocol() {
|
|
19
|
+
return "https";
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Get the url of the request.
|
|
23
|
+
*
|
|
24
|
+
* Is equivalent of `express.response.originalUrl || express.response.url`.
|
|
25
|
+
*/
|
|
26
|
+
get url() {
|
|
27
|
+
return this.raw.path;
|
|
28
|
+
}
|
|
29
|
+
get headers() {
|
|
30
|
+
return this.raw.headers;
|
|
31
|
+
}
|
|
32
|
+
get method() {
|
|
33
|
+
return this.raw.httpMethod;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use
|
|
37
|
+
* `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.
|
|
38
|
+
*/
|
|
39
|
+
get body() {
|
|
40
|
+
try {
|
|
41
|
+
return this.raw.body ? JSON.parse(this.raw.body) : {};
|
|
42
|
+
}
|
|
43
|
+
catch (er) {
|
|
44
|
+
return this.raw.body;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
get rawBody() {
|
|
48
|
+
return this.raw.body;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* This property is an object containing properties mapped to the named route `parameters`.
|
|
52
|
+
* For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.
|
|
53
|
+
* This object defaults to `{}`.
|
|
54
|
+
*/
|
|
55
|
+
get params() {
|
|
56
|
+
return this.raw.pathParameters || {};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* This property is an object containing a property for each query string parameter in the route.
|
|
60
|
+
* When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.
|
|
61
|
+
*/
|
|
62
|
+
get query() {
|
|
63
|
+
return this.raw.queryStringParameters || {};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Returns the HTTP request header specified by field. The match is case-insensitive.
|
|
67
|
+
*
|
|
68
|
+
* ```typescript
|
|
69
|
+
* request.get('Content-Type') // => "text/plain"
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @param name
|
|
73
|
+
*/
|
|
74
|
+
get(name) {
|
|
75
|
+
return (0, core_1.getValue)(this.raw.headers, name);
|
|
76
|
+
}
|
|
77
|
+
destroy() { }
|
|
78
|
+
}
|
|
79
|
+
exports.ServerlessRequest = ServerlessRequest;
|
|
80
|
+
//# sourceMappingURL=ServerlessRequest.js.map
|
|
@@ -0,0 +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;I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GatewayProxyEventBase, 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"]}
|
|
File without changes
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var _ServerlessResponse_status, _ServerlessResponse_body, _ServerlessResponse_headers, _ServerlessResponse_locals, _ServerlessResponse_isHeadersSent, _ServerlessResponse_endListeners;
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.ServerlessResponse = void 0;
|
|
5
|
+
const tslib_1 = require("tslib");
|
|
6
|
+
const core_1 = require("@tsed/core");
|
|
7
|
+
const schema_1 = require("@tsed/schema");
|
|
8
|
+
const encodeurl_1 = (0, tslib_1.__importDefault)(require("encodeurl"));
|
|
9
|
+
const mime = (0, tslib_1.__importStar)(require("mime"));
|
|
10
|
+
/**
|
|
11
|
+
* @platform
|
|
12
|
+
*/
|
|
13
|
+
class ServerlessResponse {
|
|
14
|
+
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
|
+
this.event = event;
|
|
22
|
+
this.request = request;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Get the current statusCode
|
|
26
|
+
*/
|
|
27
|
+
get statusCode() {
|
|
28
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_status, "f");
|
|
29
|
+
}
|
|
30
|
+
set statusCode(status) {
|
|
31
|
+
(0, tslib_1.__classPrivateFieldSet)(this, _ServerlessResponse_status, status, "f");
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* 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.
|
|
35
|
+
*
|
|
36
|
+
* This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
|
|
37
|
+
*/
|
|
38
|
+
get locals() {
|
|
39
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_locals, "f");
|
|
40
|
+
}
|
|
41
|
+
get isHeadersSent() {
|
|
42
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_isHeadersSent, "f");
|
|
43
|
+
}
|
|
44
|
+
getStatus() {
|
|
45
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_status, "f");
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Sets the HTTP status for the response.
|
|
49
|
+
*
|
|
50
|
+
* @param status
|
|
51
|
+
*/
|
|
52
|
+
status(status) {
|
|
53
|
+
(0, tslib_1.__classPrivateFieldSet)(this, _ServerlessResponse_status, status, "f");
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
set(name, value) {
|
|
57
|
+
return this.setHeader(name, value);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Returns the HTTP response header specified by field. The match is case-insensitive.
|
|
61
|
+
*
|
|
62
|
+
* ```typescript
|
|
63
|
+
* response.get('Content-Type') // => "text/plain"
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* @param name
|
|
67
|
+
*/
|
|
68
|
+
get(name) {
|
|
69
|
+
return (0, core_1.getValue)((0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_headers, "f"), name.toLowerCase());
|
|
70
|
+
}
|
|
71
|
+
getHeaders() {
|
|
72
|
+
return {
|
|
73
|
+
...(0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_headers, "f")
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
hasStatus() {
|
|
77
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_status, "f") !== 200;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Set header `field` to `val`, or pass
|
|
81
|
+
* an object of header fields.
|
|
82
|
+
*
|
|
83
|
+
* Examples:
|
|
84
|
+
* ```typescript
|
|
85
|
+
* response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
|
|
86
|
+
* ```
|
|
87
|
+
*
|
|
88
|
+
* Aliased as `res.header()`.
|
|
89
|
+
*/
|
|
90
|
+
setHeaders(headers) {
|
|
91
|
+
// apply headers
|
|
92
|
+
Object.entries(headers).forEach(([key, item]) => {
|
|
93
|
+
this.setHeader(key, item);
|
|
94
|
+
});
|
|
95
|
+
return this;
|
|
96
|
+
}
|
|
97
|
+
setHeader(key, item) {
|
|
98
|
+
if (item !== null && item !== undefined) {
|
|
99
|
+
key = key.toLowerCase();
|
|
100
|
+
if (key === "location") {
|
|
101
|
+
// "back" is an alias for the referrer
|
|
102
|
+
if (item === "back") {
|
|
103
|
+
item = this.request.get("Referrer") || "/";
|
|
104
|
+
}
|
|
105
|
+
item = (0, encodeurl_1.default)(String(item));
|
|
106
|
+
}
|
|
107
|
+
(0, tslib_1.__classPrivateFieldSet)(this, _ServerlessResponse_headers, {
|
|
108
|
+
...(0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_headers, "f"),
|
|
109
|
+
[key.toLowerCase()]: item
|
|
110
|
+
}, "f");
|
|
111
|
+
}
|
|
112
|
+
return this;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Set `Content-Type` response header with `type` through `mime.lookup()`
|
|
116
|
+
* when it does not contain "/", or set the Content-Type to `type` otherwise.
|
|
117
|
+
*
|
|
118
|
+
* Examples:
|
|
119
|
+
*
|
|
120
|
+
* res.type('.html');
|
|
121
|
+
* res.type('html');
|
|
122
|
+
* res.type('json');
|
|
123
|
+
* res.type('application/json');
|
|
124
|
+
* res.type('png');
|
|
125
|
+
*/
|
|
126
|
+
contentType(contentType) {
|
|
127
|
+
this.setHeader("Content-Type", mime.getType(contentType));
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
contentLength(length) {
|
|
131
|
+
this.setHeader("Content-Length", length);
|
|
132
|
+
return this;
|
|
133
|
+
}
|
|
134
|
+
getContentLength() {
|
|
135
|
+
if (this.get("Content-Length")) {
|
|
136
|
+
return parseInt(this.get("Content-Length"), 10) || 0;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
getContentType() {
|
|
140
|
+
return String(this.get("Content-Type") || "").split(";")[0];
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* 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).
|
|
144
|
+
* If not specified, status defaults to `302 Found`.
|
|
145
|
+
*
|
|
146
|
+
* @param status
|
|
147
|
+
* @param url
|
|
148
|
+
*/
|
|
149
|
+
redirect(status, url) {
|
|
150
|
+
// Set location header
|
|
151
|
+
const address = this.location(url).get("Location");
|
|
152
|
+
const body = `${(0, schema_1.getStatusMessage)(status)}. Redirecting to ${address}`;
|
|
153
|
+
this.status(status).set("Content-Length", Buffer.byteLength(body)).body(body);
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Sets the response Location HTTP header to the specified path parameter.
|
|
158
|
+
*
|
|
159
|
+
* @param url
|
|
160
|
+
*/
|
|
161
|
+
location(url) {
|
|
162
|
+
return this.set("Location", url);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Send any data to your consumer.
|
|
166
|
+
*
|
|
167
|
+
* This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.
|
|
168
|
+
* It choose the better way to send the data.
|
|
169
|
+
*
|
|
170
|
+
* @param body
|
|
171
|
+
*/
|
|
172
|
+
body(body) {
|
|
173
|
+
(0, tslib_1.__classPrivateFieldSet)(this, _ServerlessResponse_body, body, "f");
|
|
174
|
+
return this;
|
|
175
|
+
}
|
|
176
|
+
getBody() {
|
|
177
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_body, "f");
|
|
178
|
+
}
|
|
179
|
+
isDone() {
|
|
180
|
+
return (0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_isHeadersSent, "f");
|
|
181
|
+
}
|
|
182
|
+
onEnd(cb) {
|
|
183
|
+
(0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_endListeners, "f").push(cb);
|
|
184
|
+
return this;
|
|
185
|
+
}
|
|
186
|
+
destroy() {
|
|
187
|
+
(0, tslib_1.__classPrivateFieldGet)(this, _ServerlessResponse_endListeners, "f").forEach((cb) => cb());
|
|
188
|
+
(0, tslib_1.__classPrivateFieldSet)(this, _ServerlessResponse_isHeadersSent, true, "f");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
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
|
+
//# sourceMappingURL=ServerlessResponse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServerlessResponse.js","sourceRoot":"","sources":["../../../src/domain/ServerlessResponse.ts"],"names":[],"mappings":";;;;;AAAA,qCAAoC;AACpC,yCAA8C;AAE9C,uEAAkC;AAClC,wDAA6B;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,oCAAA,IAAI,kCAAQ,CAAC;IACtB,CAAC;IAED,IAAI,UAAU,CAAC,MAAM;QACnB,oCAAA,IAAI,8BAAW,MAAM,M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G,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,oCAAA,IAAI,4BAAS,IAAI,MAAA,CAAC;QAElB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,oCAAA,IAAI,gCAAM,CAAC;IACpB,CAAC;IAED,MAAM;QACJ,OAAO,oCAAA,IAAI,yCAAe,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,EAAY;QAChB,oCAAA,IAAI,wCAAc,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,oCAAA,IAAI,wCAAc,CAAC,OAAO,CAAC,CAAC,EAAY,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QACnD,oCAAA,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"]}
|
|
File without changes
|