@orion-js/http 4.0.0-next.7 → 4.0.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/dist/index.cjs +39 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +51 -17
- package/dist/index.d.ts +51 -17
- package/dist/index.js +38 -16
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -32,6 +32,7 @@ __export(index_exports, {
|
|
|
32
32
|
Route: () => Route,
|
|
33
33
|
Routes: () => Routes,
|
|
34
34
|
bodyParser: () => bodyParser2,
|
|
35
|
+
createRoute: () => createRoute,
|
|
35
36
|
express: () => import_express2.default,
|
|
36
37
|
getApp: () => getApp,
|
|
37
38
|
getServer: () => getServer,
|
|
@@ -126,13 +127,6 @@ var getServer = () => {
|
|
|
126
127
|
// src/index.ts
|
|
127
128
|
var import_express2 = __toESM(require("express"), 1);
|
|
128
129
|
|
|
129
|
-
// src/routes/route.ts
|
|
130
|
-
function route(options) {
|
|
131
|
-
return {
|
|
132
|
-
...options
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
|
|
136
130
|
// ../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js
|
|
137
131
|
function type(input) {
|
|
138
132
|
if (input === null) {
|
|
@@ -154,6 +148,7 @@ function isNil(x) {
|
|
|
154
148
|
// src/routes/executeRequest.ts
|
|
155
149
|
var import_env2 = require("@orion-js/env");
|
|
156
150
|
var import_helpers2 = require("@orion-js/helpers");
|
|
151
|
+
var import_schema = require("@orion-js/schema");
|
|
157
152
|
var simulateLatency = (0, import_env2.internalGetEnv)("simulate_latency", "SIMULATE_LATENCY");
|
|
158
153
|
async function executeRequest(route2, req, res) {
|
|
159
154
|
if (simulateLatency) {
|
|
@@ -166,21 +161,31 @@ async function executeRequest(route2, req, res) {
|
|
|
166
161
|
}
|
|
167
162
|
try {
|
|
168
163
|
const viewer = await getViewer(req);
|
|
164
|
+
if (route2.queryParams) {
|
|
165
|
+
req.query = await (0, import_schema.cleanAndValidate)(route2.queryParams ?? {}, req.query);
|
|
166
|
+
}
|
|
167
|
+
if (route2.bodyParams) {
|
|
168
|
+
req.body = await (0, import_schema.cleanAndValidate)(route2.bodyParams ?? {}, req.body);
|
|
169
|
+
}
|
|
169
170
|
const result = await route2.resolve(req, res, viewer);
|
|
170
171
|
if (!result) return;
|
|
171
172
|
if (result.statusCode) {
|
|
172
173
|
res.status(result.statusCode);
|
|
173
174
|
}
|
|
174
175
|
if (result.headers) {
|
|
175
|
-
|
|
176
|
+
for (const key in result.headers) {
|
|
176
177
|
res.setHeader(key, result.headers[key]);
|
|
177
|
-
}
|
|
178
|
+
}
|
|
178
179
|
}
|
|
179
180
|
if (!isNil(result.body)) {
|
|
180
|
-
|
|
181
|
-
|
|
181
|
+
let body = result.body;
|
|
182
|
+
if (route2.returns) {
|
|
183
|
+
body = await (0, import_schema.cleanAndValidate)(route2.returns, result.body);
|
|
184
|
+
}
|
|
185
|
+
if (type(body) === "Object") {
|
|
186
|
+
res.json(body);
|
|
182
187
|
} else {
|
|
183
|
-
res.send(
|
|
188
|
+
res.send(body);
|
|
184
189
|
}
|
|
185
190
|
}
|
|
186
191
|
} catch (error) {
|
|
@@ -201,6 +206,10 @@ function registerRoute(route2) {
|
|
|
201
206
|
const parser = import_body_parser.default[route2.bodyParser](route2.bodyParserOptions);
|
|
202
207
|
handlers.unshift(parser);
|
|
203
208
|
}
|
|
209
|
+
if (!route2.bodyParser && route2.bodyParams) {
|
|
210
|
+
const parser = import_body_parser.default.json(route2.bodyParserOptions);
|
|
211
|
+
handlers.unshift(parser);
|
|
212
|
+
}
|
|
204
213
|
if (route2.middlewares) {
|
|
205
214
|
handlers.unshift(...route2.middlewares);
|
|
206
215
|
}
|
|
@@ -218,6 +227,14 @@ function registerRoutes(routesMap) {
|
|
|
218
227
|
// src/index.ts
|
|
219
228
|
var import_body_parser2 = __toESM(require("body-parser"), 1);
|
|
220
229
|
|
|
230
|
+
// src/routes/route.ts
|
|
231
|
+
function createRoute(options) {
|
|
232
|
+
return {
|
|
233
|
+
...options
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
var route = createRoute;
|
|
237
|
+
|
|
221
238
|
// src/service/index.ts
|
|
222
239
|
var import_services = require("@orion-js/services");
|
|
223
240
|
var serviceMetadata = /* @__PURE__ */ new WeakMap();
|
|
@@ -235,10 +252,15 @@ function Route(options) {
|
|
|
235
252
|
const propertyKey = String(context.name);
|
|
236
253
|
context.addInitializer(function() {
|
|
237
254
|
const routes = routeMetadata.get(this) || {};
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
255
|
+
if (context.kind === "method") {
|
|
256
|
+
routes[propertyKey] = createRoute({
|
|
257
|
+
...options,
|
|
258
|
+
resolve: this[propertyKey].bind(this)
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
if (context.kind === "field") {
|
|
262
|
+
routes[propertyKey] = this[propertyKey];
|
|
263
|
+
}
|
|
242
264
|
routeMetadata.set(this, routes);
|
|
243
265
|
});
|
|
244
266
|
return method;
|
|
@@ -265,6 +287,7 @@ var bodyParser2 = { json, raw, text, urlencoded };
|
|
|
265
287
|
Route,
|
|
266
288
|
Routes,
|
|
267
289
|
bodyParser,
|
|
290
|
+
createRoute,
|
|
268
291
|
express,
|
|
269
292
|
getApp,
|
|
270
293
|
getServer,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/routes/route.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isNil.js","../src/routes/executeRequest.ts","../src/routes/registerRoute.ts","../src/routes/registerRoutes.ts","../src/service/index.ts"],"sourcesContent":["import {setOnError, onError} from './errors'\nimport {getViewer, setGetViewer} from './viewer'\nimport {startServer, getApp, getServer} from './start'\nimport express from 'express'\nimport route from './routes/route'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport bodyParserLib from 'body-parser'\nimport {RequestHandler} from 'express'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n route,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport * from './types'\nexport * from './service'\n","import express from 'express'\nimport crypto from 'crypto'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n console.warn(`[route/handler] OrionError in ${req.path}:`, error)\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n console.warn(`[route/handler] GraphQLError in ${req.path}:`, error)\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.writeHead(statusCode)\n res.end(JSON.stringify(data, null, 2))\n\n error.hash = hash\n console.error(`[route/handler] Internal server error in ${req.url}:`, error)\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n await onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import {RouteType, OrionRouteOptions} from '../types'\n\nexport default function route(options: OrionRouteOptions): RouteType {\n return {\n ...options,\n }\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import {RouteType} from './../types'\nimport {onError} from '../errors'\nimport {getViewer} from './../viewer'\nimport express from 'express'\nimport {isNil, type} from 'rambdax'\nimport {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\n\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\n\nexport async function executeRequest(\n route: RouteType,\n req: express.Request,\n res: express.Response,\n) {\n if (simulateLatency) {\n const time = Number.parseInt(simulateLatency)\n if (time) {\n const min = time * 0.9\n const max = time * 1.1\n await sleep(Math.floor(Math.random() * (max - min + 1)) + min)\n }\n }\n\n try {\n const viewer = await getViewer(req)\n const result = await route.resolve(req, res, viewer)\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n Object.keys(result.headers).forEach(key => {\n res.setHeader(key, result.headers[key])\n })\n }\n\n // add body to response\n if (!isNil(result.body)) {\n if (type(result.body) === 'Object') {\n res.json(result.body)\n } else {\n res.send(result.body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\nimport express from 'express'\nimport bodyParser from 'body-parser'\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const method = route.method\n\n const handler = async (req, res) => {\n executeRequest(route, req, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n}\n","import registerRoute from './registerRoute'\nimport {RoutesMap} from '../types'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n const routes = Object.values(routesMap)\n\n for (const route of routes) {\n registerRoute(route)\n }\n}\n","import {getInstance, Service} from '@orion-js/services'\nimport route from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'routes'})\n })\n }\n}\n\nexport function Route<\n This,\n TArgs extends Parameters<OrionRouteOptions['resolve']>,\n TReturn extends ReturnType<OrionRouteOptions['resolve']>,\n>(options: Omit<OrionRouteOptions, 'resolve'>) {\n return (\n method: (this: This, ...args: TArgs) => TReturn,\n context: ClassMethodDecoratorContext<This, typeof method>,\n ) => {\n const propertyKey = String(context.name)\n\n context.addInitializer(function (this: This) {\n const routes = routeMetadata.get(this) || {}\n\n routes[propertyKey] = route({\n ...options,\n resolve: this[propertyKey].bind(this),\n })\n\n routeMetadata.set(this, routes)\n })\n\n return method\n }\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAAA;AAAA,EAAA,+BAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAAmB;AAInB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,cAAQ,KAAK,iCAAiC,IAAI,IAAI,KAAK,KAAK;AAAA,IAClE;AAEA,UAAM,OAAO,MAAM,QAAQ;AAE3B,QAAI,OAAO,UAAU;AACrB,QAAI,KAAK,IAAI;AAAA,EACf,WAAW,MAAM,gBAAgB;AAC/B,QAAI,UAAU,MAAM,UAAU;AAC9B,QAAI,IAAI,MAAM,OAAO;AACrB,YAAQ,KAAK,mCAAmC,IAAI,IAAI,KAAK,KAAK;AAAA,EACpE,OAAO;AACL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EO,SAAS,MAId,SAA6C;AAC7C,SAAO,CACL,QACA,YACG;AACH,UAAM,cAAc,OAAO,QAAQ,IAAI;AAEvC,YAAQ,eAAe,WAAsB;AAC3C,YAAM,SAAS,cAAc,IAAI,IAAI,KAAK,CAAC;AAE3C,aAAO,WAAW,IAAI,MAAM;AAAA,QAC1B,GAAG;AAAA,QACH,SAAS,KAAK,WAAW,EAAE,KAAK,IAAI;AAAA,MACtC,CAAC;AAED,oBAAc,IAAI,MAAM,MAAM;AAAA,IAChC,CAAC;AAED,WAAO;AAAA,EACT;AACF;AAEO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,eAAW,6BAAY,MAAM;AAEnC,MAAI,CAAC,gBAAgB,IAAI,SAAS,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,mBAAmB,gBAAgB,IAAI,SAAS,WAAW;AACjE,MAAI,iBAAiB,iBAAiB,UAAU;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,YAAY,cAAc,IAAI,QAAQ,KAAK,CAAC;AAElD,SAAO;AACT;;;AVjDA,IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI,oBAAAC;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["bodyParser","express","crypto","express","import_express","import_env","import_helpers","route","route","bodyParser","route","import_body_parser","bodyParserLib","bodyParser"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/viewer.ts","../src/start.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isNil.js","../src/routes/executeRequest.ts","../src/routes/registerRoute.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import {setOnError, onError} from './errors'\nimport {getViewer, setGetViewer} from './viewer'\nimport {startServer, getApp, getServer} from './start'\nimport express from 'express'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport bodyParserLib from 'body-parser'\nimport {RequestHandler} from 'express'\n\nexport * from './routes/route'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport * from './types'\nexport * from './service'\n","import express from 'express'\nimport crypto from 'crypto'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n console.warn(`[route/handler] OrionError in ${req.path}:`, error)\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n console.warn(`[route/handler] GraphQLError in ${req.path}:`, error)\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.writeHead(statusCode)\n res.end(JSON.stringify(data, null, 2))\n\n error.hash = hash\n console.error(`[route/handler] Internal server error in ${req.url}:`, error)\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n await onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\nimport express from 'express'\nimport {isNil, type} from 'rambdax'\nimport {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\nimport {cleanAndValidate} from '@orion-js/schema'\nimport {onError} from '../errors'\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\n\nexport async function executeRequest(\n route: RouteType<any>,\n req: OrionRequest,\n res: express.Response,\n) {\n if (simulateLatency) {\n const time = Number.parseInt(simulateLatency)\n if (time) {\n const min = time * 0.9\n const max = time * 1.1\n await sleep(Math.floor(Math.random() * (max - min + 1)) + min)\n }\n }\n\n try {\n const viewer = await getViewer(req)\n\n if (route.queryParams) {\n req.query = await cleanAndValidate(route.queryParams ?? {}, req.query)\n }\n\n if (route.bodyParams) {\n req.body = await cleanAndValidate(route.bodyParams ?? {}, req.body)\n }\n\n const result = await route.resolve(req, res, viewer)\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n for (const key in result.headers) {\n res.setHeader(key, result.headers[key])\n }\n }\n\n // add body to response\n if (!isNil(result.body)) {\n let body = result.body\n\n if (route.returns) {\n body = await cleanAndValidate(route.returns, result.body)\n }\n\n if (type(body) === 'Object') {\n res.json(body)\n } else {\n res.send(body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\nimport express from 'express'\nimport bodyParser from 'body-parser'\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const method = route.method\n\n const handler = async (req, res) => {\n executeRequest(route, req, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (!route.bodyParser && route.bodyParams) {\n const parser = bodyParser.json(route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n}\n","import registerRoute from './registerRoute'\nimport {RoutesMap} from '../types'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n const routes = Object.values(routesMap)\n\n for (const route of routes) {\n registerRoute(route)\n }\n}\n","import {Schema, SchemaFieldType} from '@orion-js/schema'\nimport {RouteType, OrionRouteOptions} from '../types'\n\nexport function createRoute<\n TPath extends string,\n TQueryParamsSchema extends Schema | undefined,\n TBodyParamsSchema extends Schema | undefined,\n TReturnsSchema extends SchemaFieldType | undefined,\n>(\n options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>,\n): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema> {\n return {\n ...options,\n }\n}\n\n/**\n * @deprecated Use createRoute instead\n */\nexport const route = createRoute\n","import {getInstance, Service} from '@orion-js/services'\nimport {createRoute} from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'routes'})\n })\n }\n}\n\nexport function Route(): (method: any, context: ClassFieldDecoratorContext) => any\nexport function Route(\n options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>,\n): (method: any, context: ClassMethodDecoratorContext) => any\nexport function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>) {\n return (method: any, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext) => {\n const propertyKey = String(context.name)\n\n context.addInitializer(function (this) {\n const routes = routeMetadata.get(this) || {}\n\n if (context.kind === 'method') {\n routes[propertyKey] = createRoute({\n ...options,\n resolve: this[propertyKey].bind(this),\n })\n }\n\n if (context.kind === 'field') {\n routes[propertyKey] = this[propertyKey]\n }\n\n routeMetadata.set(this, routes)\n })\n\n return method\n }\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAI,KAAK,CAAC;AAE3C,UAAI,QAAQ,SAAS,UAAU;AAC7B,eAAO,WAAW,IAAI,YAAY;AAAA,UAChC,GAAG;AAAA,UACH,SAAS,KAAK,WAAW,EAAE,KAAK,IAAI;AAAA,QACtC,CAAC;AAAA,MACH;AAEA,UAAI,QAAQ,SAAS,SAAS;AAC5B,eAAO,WAAW,IAAI,KAAK,WAAW;AAAA,MACxC;AAEA,oBAAc,IAAI,MAAM,MAAM;AAAA,IAChC,CAAC;AAED,WAAO;AAAA,EACT;AACF;AAEO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,eAAW,6BAAY,MAAM;AAEnC,MAAI,CAAC,gBAAgB,IAAI,SAAS,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,mBAAmB,gBAAgB,IAAI,SAAS,WAAW;AACjE,MAAI,iBAAiB,iBAAiB,UAAU;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,YAAY,cAAc,IAAI,QAAQ,KAAK,CAAC;AAElD,SAAO;AACT;;;AVnDA,IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI,oBAAAC;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["bodyParser","express","crypto","express","import_express","import_env","import_helpers","route","route","bodyParser","route","import_body_parser","bodyParserLib","bodyParser"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import express, { RequestHandler } from 'express';
|
|
2
2
|
export { default as express } from 'express';
|
|
3
3
|
import { OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';
|
|
4
|
+
import { Schema, SchemaFieldType, InferSchemaType } from '@orion-js/schema';
|
|
4
5
|
|
|
5
6
|
type onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>;
|
|
6
7
|
declare const onError: onErrorFunction;
|
|
@@ -16,24 +17,53 @@ declare const startServer: (port?: number, otherOptions?: StartOrionOptions) =>
|
|
|
16
17
|
declare const getApp: () => express.Express;
|
|
17
18
|
declare const getServer: () => any;
|
|
18
19
|
|
|
19
|
-
interface RouteResponseObject {
|
|
20
|
+
interface RouteResponseObject<TReturnsSchema extends SchemaFieldType | undefined> {
|
|
20
21
|
statusCode?: number;
|
|
21
22
|
headers?: {
|
|
22
23
|
[key: string]: string;
|
|
23
24
|
};
|
|
24
|
-
body: string | object
|
|
25
|
+
body: TReturnsSchema extends undefined ? string | object : InferSchemaType<TReturnsSchema>;
|
|
25
26
|
}
|
|
26
|
-
type RouteResponse = Promise<RouteResponseObject | void>;
|
|
27
|
-
type
|
|
28
|
-
|
|
27
|
+
type RouteResponse<TReturnsSchema extends SchemaFieldType = any> = Promise<RouteResponseObject<TReturnsSchema> | void>;
|
|
28
|
+
type OrionRequest<TPath extends string = string, TQueryParamsSchema extends Schema | undefined = any, TBodyParamsSchema extends Schema | undefined = any> = express.Request<InferPathParams<TPath>, any, InferSchemaType<TBodyParamsSchema>, InferSchemaType<TQueryParamsSchema>>;
|
|
29
|
+
type RouteResolve<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined> = (req?: OrionRequest<TPath, TQueryParamsSchema, TBodyParamsSchema>, res?: express.Response, viewer?: any) => RouteResponse<TReturnsSchema>;
|
|
30
|
+
type InferPathParam<Path, NextPart> = Path extends `:${infer OptionalParam}?` ? {
|
|
31
|
+
[K in OptionalParam]?: string;
|
|
32
|
+
} & NextPart : Path extends `:${infer Param}` ? {
|
|
33
|
+
[K in Param]: string;
|
|
34
|
+
} & NextPart : NextPart;
|
|
35
|
+
type Simplify<T> = T extends object ? T extends infer O ? {
|
|
36
|
+
[K in keyof O]: Simplify<O[K]>;
|
|
37
|
+
} : never : T;
|
|
38
|
+
type InternalPathParams<Path> = Path extends `${infer Segment}/${infer Rest}` ? InferPathParam<Segment, InferPathParams<Rest>> : InferPathParam<Path, {}>;
|
|
39
|
+
type InferPathParams<Path> = Simplify<InternalPathParams<Path>>;
|
|
40
|
+
interface OrionRouteOptions<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined> {
|
|
29
41
|
/**
|
|
30
|
-
* The
|
|
42
|
+
* The path of the requests to match.
|
|
31
43
|
*/
|
|
32
|
-
|
|
44
|
+
path: TPath;
|
|
33
45
|
/**
|
|
34
|
-
* The
|
|
46
|
+
* The schema of the path params. If not provided, the path params will be undefined.
|
|
47
|
+
* Path params will be cleaned and validated using the schema.
|
|
35
48
|
*/
|
|
36
|
-
|
|
49
|
+
/**
|
|
50
|
+
* The schema of the body params. If not provided, the body params will be undefined.
|
|
51
|
+
* Body params will be cleaned and validated using the schema.
|
|
52
|
+
*/
|
|
53
|
+
bodyParams?: TBodyParamsSchema;
|
|
54
|
+
/**
|
|
55
|
+
* The schema of the query params. If not provided, the query params will be undefined.
|
|
56
|
+
* Query params will be cleaned and validated using the schema.
|
|
57
|
+
*/
|
|
58
|
+
queryParams?: TQueryParamsSchema;
|
|
59
|
+
/**
|
|
60
|
+
* The schema of the return body. If provided, the body will be only cleaned agains this schema, not validated.
|
|
61
|
+
*/
|
|
62
|
+
returns?: TReturnsSchema;
|
|
63
|
+
/**
|
|
64
|
+
* The http method of the requests to match.
|
|
65
|
+
*/
|
|
66
|
+
method: 'get' | 'post' | 'put' | 'delete' | 'all';
|
|
37
67
|
/**
|
|
38
68
|
* Select the body parser to use for this route.
|
|
39
69
|
*/
|
|
@@ -48,28 +78,32 @@ interface OrionRouteOptions {
|
|
|
48
78
|
* for more information.
|
|
49
79
|
*/
|
|
50
80
|
middlewares?: Array<express.RequestHandler>;
|
|
51
|
-
resolve: RouteResolve
|
|
81
|
+
resolve: RouteResolve<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>;
|
|
52
82
|
/**
|
|
53
83
|
* Pass another express app
|
|
54
84
|
*/
|
|
55
85
|
app?: express.Application;
|
|
56
86
|
}
|
|
57
|
-
|
|
58
|
-
}
|
|
87
|
+
type RouteType<TPath extends string = string, TQueryParamsSchema extends Schema | undefined = any, TBodyParamsSchema extends Schema | undefined = any, TReturnsSchema extends SchemaFieldType | undefined = any> = OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>;
|
|
59
88
|
interface RoutesMap {
|
|
60
|
-
[key: string]: RouteType
|
|
89
|
+
[key: string]: RouteType<any, any, any, any>;
|
|
61
90
|
}
|
|
62
91
|
type Request = express.Request;
|
|
63
92
|
type Response = express.Response;
|
|
64
93
|
|
|
65
|
-
declare function route(options: OrionRouteOptions): RouteType;
|
|
66
|
-
|
|
67
94
|
declare function registerRoute(route: RouteType): void;
|
|
68
95
|
|
|
69
96
|
declare function registerRoutes(routesMap: RoutesMap): void;
|
|
70
97
|
|
|
98
|
+
declare function createRoute<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined>(options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>;
|
|
99
|
+
/**
|
|
100
|
+
* @deprecated Use createRoute instead
|
|
101
|
+
*/
|
|
102
|
+
declare const route: typeof createRoute;
|
|
103
|
+
|
|
71
104
|
declare function Routes(): (target: any, context: ClassDecoratorContext<any>) => void;
|
|
72
|
-
declare function Route
|
|
105
|
+
declare function Route(): (method: any, context: ClassFieldDecoratorContext) => any;
|
|
106
|
+
declare function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>): (method: any, context: ClassMethodDecoratorContext) => any;
|
|
73
107
|
declare function getServiceRoutes(target: any): RoutesMap;
|
|
74
108
|
|
|
75
109
|
declare const bodyParser: {
|
|
@@ -81,4 +115,4 @@ declare const bodyParser: {
|
|
|
81
115
|
}) => RequestHandler;
|
|
82
116
|
};
|
|
83
117
|
|
|
84
|
-
export { type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, getApp, getServer, getServiceRoutes, getViewer, onError, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer };
|
|
118
|
+
export { type InferPathParams, type OrionRequest, type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, createRoute, getApp, getServer, getServiceRoutes, getViewer, onError, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import express, { RequestHandler } from 'express';
|
|
2
2
|
export { default as express } from 'express';
|
|
3
3
|
import { OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';
|
|
4
|
+
import { Schema, SchemaFieldType, InferSchemaType } from '@orion-js/schema';
|
|
4
5
|
|
|
5
6
|
type onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>;
|
|
6
7
|
declare const onError: onErrorFunction;
|
|
@@ -16,24 +17,53 @@ declare const startServer: (port?: number, otherOptions?: StartOrionOptions) =>
|
|
|
16
17
|
declare const getApp: () => express.Express;
|
|
17
18
|
declare const getServer: () => any;
|
|
18
19
|
|
|
19
|
-
interface RouteResponseObject {
|
|
20
|
+
interface RouteResponseObject<TReturnsSchema extends SchemaFieldType | undefined> {
|
|
20
21
|
statusCode?: number;
|
|
21
22
|
headers?: {
|
|
22
23
|
[key: string]: string;
|
|
23
24
|
};
|
|
24
|
-
body: string | object
|
|
25
|
+
body: TReturnsSchema extends undefined ? string | object : InferSchemaType<TReturnsSchema>;
|
|
25
26
|
}
|
|
26
|
-
type RouteResponse = Promise<RouteResponseObject | void>;
|
|
27
|
-
type
|
|
28
|
-
|
|
27
|
+
type RouteResponse<TReturnsSchema extends SchemaFieldType = any> = Promise<RouteResponseObject<TReturnsSchema> | void>;
|
|
28
|
+
type OrionRequest<TPath extends string = string, TQueryParamsSchema extends Schema | undefined = any, TBodyParamsSchema extends Schema | undefined = any> = express.Request<InferPathParams<TPath>, any, InferSchemaType<TBodyParamsSchema>, InferSchemaType<TQueryParamsSchema>>;
|
|
29
|
+
type RouteResolve<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined> = (req?: OrionRequest<TPath, TQueryParamsSchema, TBodyParamsSchema>, res?: express.Response, viewer?: any) => RouteResponse<TReturnsSchema>;
|
|
30
|
+
type InferPathParam<Path, NextPart> = Path extends `:${infer OptionalParam}?` ? {
|
|
31
|
+
[K in OptionalParam]?: string;
|
|
32
|
+
} & NextPart : Path extends `:${infer Param}` ? {
|
|
33
|
+
[K in Param]: string;
|
|
34
|
+
} & NextPart : NextPart;
|
|
35
|
+
type Simplify<T> = T extends object ? T extends infer O ? {
|
|
36
|
+
[K in keyof O]: Simplify<O[K]>;
|
|
37
|
+
} : never : T;
|
|
38
|
+
type InternalPathParams<Path> = Path extends `${infer Segment}/${infer Rest}` ? InferPathParam<Segment, InferPathParams<Rest>> : InferPathParam<Path, {}>;
|
|
39
|
+
type InferPathParams<Path> = Simplify<InternalPathParams<Path>>;
|
|
40
|
+
interface OrionRouteOptions<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined> {
|
|
29
41
|
/**
|
|
30
|
-
* The
|
|
42
|
+
* The path of the requests to match.
|
|
31
43
|
*/
|
|
32
|
-
|
|
44
|
+
path: TPath;
|
|
33
45
|
/**
|
|
34
|
-
* The
|
|
46
|
+
* The schema of the path params. If not provided, the path params will be undefined.
|
|
47
|
+
* Path params will be cleaned and validated using the schema.
|
|
35
48
|
*/
|
|
36
|
-
|
|
49
|
+
/**
|
|
50
|
+
* The schema of the body params. If not provided, the body params will be undefined.
|
|
51
|
+
* Body params will be cleaned and validated using the schema.
|
|
52
|
+
*/
|
|
53
|
+
bodyParams?: TBodyParamsSchema;
|
|
54
|
+
/**
|
|
55
|
+
* The schema of the query params. If not provided, the query params will be undefined.
|
|
56
|
+
* Query params will be cleaned and validated using the schema.
|
|
57
|
+
*/
|
|
58
|
+
queryParams?: TQueryParamsSchema;
|
|
59
|
+
/**
|
|
60
|
+
* The schema of the return body. If provided, the body will be only cleaned agains this schema, not validated.
|
|
61
|
+
*/
|
|
62
|
+
returns?: TReturnsSchema;
|
|
63
|
+
/**
|
|
64
|
+
* The http method of the requests to match.
|
|
65
|
+
*/
|
|
66
|
+
method: 'get' | 'post' | 'put' | 'delete' | 'all';
|
|
37
67
|
/**
|
|
38
68
|
* Select the body parser to use for this route.
|
|
39
69
|
*/
|
|
@@ -48,28 +78,32 @@ interface OrionRouteOptions {
|
|
|
48
78
|
* for more information.
|
|
49
79
|
*/
|
|
50
80
|
middlewares?: Array<express.RequestHandler>;
|
|
51
|
-
resolve: RouteResolve
|
|
81
|
+
resolve: RouteResolve<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>;
|
|
52
82
|
/**
|
|
53
83
|
* Pass another express app
|
|
54
84
|
*/
|
|
55
85
|
app?: express.Application;
|
|
56
86
|
}
|
|
57
|
-
|
|
58
|
-
}
|
|
87
|
+
type RouteType<TPath extends string = string, TQueryParamsSchema extends Schema | undefined = any, TBodyParamsSchema extends Schema | undefined = any, TReturnsSchema extends SchemaFieldType | undefined = any> = OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>;
|
|
59
88
|
interface RoutesMap {
|
|
60
|
-
[key: string]: RouteType
|
|
89
|
+
[key: string]: RouteType<any, any, any, any>;
|
|
61
90
|
}
|
|
62
91
|
type Request = express.Request;
|
|
63
92
|
type Response = express.Response;
|
|
64
93
|
|
|
65
|
-
declare function route(options: OrionRouteOptions): RouteType;
|
|
66
|
-
|
|
67
94
|
declare function registerRoute(route: RouteType): void;
|
|
68
95
|
|
|
69
96
|
declare function registerRoutes(routesMap: RoutesMap): void;
|
|
70
97
|
|
|
98
|
+
declare function createRoute<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined>(options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>;
|
|
99
|
+
/**
|
|
100
|
+
* @deprecated Use createRoute instead
|
|
101
|
+
*/
|
|
102
|
+
declare const route: typeof createRoute;
|
|
103
|
+
|
|
71
104
|
declare function Routes(): (target: any, context: ClassDecoratorContext<any>) => void;
|
|
72
|
-
declare function Route
|
|
105
|
+
declare function Route(): (method: any, context: ClassFieldDecoratorContext) => any;
|
|
106
|
+
declare function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>): (method: any, context: ClassMethodDecoratorContext) => any;
|
|
73
107
|
declare function getServiceRoutes(target: any): RoutesMap;
|
|
74
108
|
|
|
75
109
|
declare const bodyParser: {
|
|
@@ -81,4 +115,4 @@ declare const bodyParser: {
|
|
|
81
115
|
}) => RequestHandler;
|
|
82
116
|
};
|
|
83
117
|
|
|
84
|
-
export { type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, getApp, getServer, getServiceRoutes, getViewer, onError, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer };
|
|
118
|
+
export { type InferPathParams, type OrionRequest, type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, createRoute, getApp, getServer, getServiceRoutes, getViewer, onError, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer };
|
package/dist/index.js
CHANGED
|
@@ -77,13 +77,6 @@ var getServer = () => {
|
|
|
77
77
|
// src/index.ts
|
|
78
78
|
import express2 from "express";
|
|
79
79
|
|
|
80
|
-
// src/routes/route.ts
|
|
81
|
-
function route(options) {
|
|
82
|
-
return {
|
|
83
|
-
...options
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
|
|
87
80
|
// ../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js
|
|
88
81
|
function type(input) {
|
|
89
82
|
if (input === null) {
|
|
@@ -105,6 +98,7 @@ function isNil(x) {
|
|
|
105
98
|
// src/routes/executeRequest.ts
|
|
106
99
|
import { internalGetEnv as internalGetEnv2 } from "@orion-js/env";
|
|
107
100
|
import { sleep } from "@orion-js/helpers";
|
|
101
|
+
import { cleanAndValidate } from "@orion-js/schema";
|
|
108
102
|
var simulateLatency = internalGetEnv2("simulate_latency", "SIMULATE_LATENCY");
|
|
109
103
|
async function executeRequest(route2, req, res) {
|
|
110
104
|
if (simulateLatency) {
|
|
@@ -117,21 +111,31 @@ async function executeRequest(route2, req, res) {
|
|
|
117
111
|
}
|
|
118
112
|
try {
|
|
119
113
|
const viewer = await getViewer(req);
|
|
114
|
+
if (route2.queryParams) {
|
|
115
|
+
req.query = await cleanAndValidate(route2.queryParams ?? {}, req.query);
|
|
116
|
+
}
|
|
117
|
+
if (route2.bodyParams) {
|
|
118
|
+
req.body = await cleanAndValidate(route2.bodyParams ?? {}, req.body);
|
|
119
|
+
}
|
|
120
120
|
const result = await route2.resolve(req, res, viewer);
|
|
121
121
|
if (!result) return;
|
|
122
122
|
if (result.statusCode) {
|
|
123
123
|
res.status(result.statusCode);
|
|
124
124
|
}
|
|
125
125
|
if (result.headers) {
|
|
126
|
-
|
|
126
|
+
for (const key in result.headers) {
|
|
127
127
|
res.setHeader(key, result.headers[key]);
|
|
128
|
-
}
|
|
128
|
+
}
|
|
129
129
|
}
|
|
130
130
|
if (!isNil(result.body)) {
|
|
131
|
-
|
|
132
|
-
|
|
131
|
+
let body = result.body;
|
|
132
|
+
if (route2.returns) {
|
|
133
|
+
body = await cleanAndValidate(route2.returns, result.body);
|
|
134
|
+
}
|
|
135
|
+
if (type(body) === "Object") {
|
|
136
|
+
res.json(body);
|
|
133
137
|
} else {
|
|
134
|
-
res.send(
|
|
138
|
+
res.send(body);
|
|
135
139
|
}
|
|
136
140
|
}
|
|
137
141
|
} catch (error) {
|
|
@@ -152,6 +156,10 @@ function registerRoute(route2) {
|
|
|
152
156
|
const parser = bodyParser[route2.bodyParser](route2.bodyParserOptions);
|
|
153
157
|
handlers.unshift(parser);
|
|
154
158
|
}
|
|
159
|
+
if (!route2.bodyParser && route2.bodyParams) {
|
|
160
|
+
const parser = bodyParser.json(route2.bodyParserOptions);
|
|
161
|
+
handlers.unshift(parser);
|
|
162
|
+
}
|
|
155
163
|
if (route2.middlewares) {
|
|
156
164
|
handlers.unshift(...route2.middlewares);
|
|
157
165
|
}
|
|
@@ -169,6 +177,14 @@ function registerRoutes(routesMap) {
|
|
|
169
177
|
// src/index.ts
|
|
170
178
|
import bodyParserLib from "body-parser";
|
|
171
179
|
|
|
180
|
+
// src/routes/route.ts
|
|
181
|
+
function createRoute(options) {
|
|
182
|
+
return {
|
|
183
|
+
...options
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
var route = createRoute;
|
|
187
|
+
|
|
172
188
|
// src/service/index.ts
|
|
173
189
|
import { getInstance, Service } from "@orion-js/services";
|
|
174
190
|
var serviceMetadata = /* @__PURE__ */ new WeakMap();
|
|
@@ -186,10 +202,15 @@ function Route(options) {
|
|
|
186
202
|
const propertyKey = String(context.name);
|
|
187
203
|
context.addInitializer(function() {
|
|
188
204
|
const routes = routeMetadata.get(this) || {};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
205
|
+
if (context.kind === "method") {
|
|
206
|
+
routes[propertyKey] = createRoute({
|
|
207
|
+
...options,
|
|
208
|
+
resolve: this[propertyKey].bind(this)
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
if (context.kind === "field") {
|
|
212
|
+
routes[propertyKey] = this[propertyKey];
|
|
213
|
+
}
|
|
193
214
|
routeMetadata.set(this, routes);
|
|
194
215
|
});
|
|
195
216
|
return method;
|
|
@@ -215,6 +236,7 @@ export {
|
|
|
215
236
|
Route,
|
|
216
237
|
Routes,
|
|
217
238
|
bodyParser2 as bodyParser,
|
|
239
|
+
createRoute,
|
|
218
240
|
express2 as express,
|
|
219
241
|
getApp,
|
|
220
242
|
getServer,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/index.ts","../src/routes/route.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isNil.js","../src/routes/executeRequest.ts","../src/routes/registerRoute.ts","../src/routes/registerRoutes.ts","../src/service/index.ts"],"sourcesContent":["import express from 'express'\nimport crypto from 'crypto'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n console.warn(`[route/handler] OrionError in ${req.path}:`, error)\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n console.warn(`[route/handler] GraphQLError in ${req.path}:`, error)\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.writeHead(statusCode)\n res.end(JSON.stringify(data, null, 2))\n\n error.hash = hash\n console.error(`[route/handler] Internal server error in ${req.url}:`, error)\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n await onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import {setOnError, onError} from './errors'\nimport {getViewer, setGetViewer} from './viewer'\nimport {startServer, getApp, getServer} from './start'\nimport express from 'express'\nimport route from './routes/route'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport bodyParserLib from 'body-parser'\nimport {RequestHandler} from 'express'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n route,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport * from './types'\nexport * from './service'\n","import {RouteType, OrionRouteOptions} from '../types'\n\nexport default function route(options: OrionRouteOptions): RouteType {\n return {\n ...options,\n }\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import {RouteType} from './../types'\nimport {onError} from '../errors'\nimport {getViewer} from './../viewer'\nimport express from 'express'\nimport {isNil, type} from 'rambdax'\nimport {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\n\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\n\nexport async function executeRequest(\n route: RouteType,\n req: express.Request,\n res: express.Response,\n) {\n if (simulateLatency) {\n const time = Number.parseInt(simulateLatency)\n if (time) {\n const min = time * 0.9\n const max = time * 1.1\n await sleep(Math.floor(Math.random() * (max - min + 1)) + min)\n }\n }\n\n try {\n const viewer = await getViewer(req)\n const result = await route.resolve(req, res, viewer)\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n Object.keys(result.headers).forEach(key => {\n res.setHeader(key, result.headers[key])\n })\n }\n\n // add body to response\n if (!isNil(result.body)) {\n if (type(result.body) === 'Object') {\n res.json(result.body)\n } else {\n res.send(result.body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\nimport express from 'express'\nimport bodyParser from 'body-parser'\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const method = route.method\n\n const handler = async (req, res) => {\n executeRequest(route, req, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n}\n","import registerRoute from './registerRoute'\nimport {RoutesMap} from '../types'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n const routes = Object.values(routesMap)\n\n for (const route of routes) {\n registerRoute(route)\n }\n}\n","import {getInstance, Service} from '@orion-js/services'\nimport route from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'routes'})\n })\n }\n}\n\nexport function Route<\n This,\n TArgs extends Parameters<OrionRouteOptions['resolve']>,\n TReturn extends ReturnType<OrionRouteOptions['resolve']>,\n>(options: Omit<OrionRouteOptions, 'resolve'>) {\n return (\n method: (this: This, ...args: TArgs) => TReturn,\n context: ClassMethodDecoratorContext<This, typeof method>,\n ) => {\n const propertyKey = String(context.name)\n\n context.addInitializer(function (this: This) {\n const routes = routeMetadata.get(this) || {}\n\n routes[propertyKey] = route({\n ...options,\n resolve: this[propertyKey].bind(this),\n })\n\n routeMetadata.set(this, routes)\n })\n\n return method\n }\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";AACA,OAAO,YAAY;AAInB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,a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|
+
{"version":3,"sources":["../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/index.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isNil.js","../src/routes/executeRequest.ts","../src/routes/registerRoute.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import express from 'express'\nimport crypto from 'crypto'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n console.warn(`[route/handler] OrionError in ${req.path}:`, error)\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n console.warn(`[route/handler] GraphQLError in ${req.path}:`, error)\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.writeHead(statusCode)\n res.end(JSON.stringify(data, null, 2))\n\n error.hash = hash\n console.error(`[route/handler] Internal server error in ${req.url}:`, error)\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n await onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import {setOnError, onError} from './errors'\nimport {getViewer, setGetViewer} from './viewer'\nimport {startServer, getApp, getServer} from './start'\nimport express from 'express'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport bodyParserLib from 'body-parser'\nimport {RequestHandler} from 'express'\n\nexport * from './routes/route'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport * from './types'\nexport * from './service'\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\nimport express from 'express'\nimport {isNil, type} from 'rambdax'\nimport {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\nimport {cleanAndValidate} from '@orion-js/schema'\nimport {onError} from '../errors'\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\n\nexport async function executeRequest(\n route: RouteType<any>,\n req: OrionRequest,\n res: express.Response,\n) {\n if (simulateLatency) {\n const time = Number.parseInt(simulateLatency)\n if (time) {\n const min = time * 0.9\n const max = time * 1.1\n await sleep(Math.floor(Math.random() * (max - min + 1)) + min)\n }\n }\n\n try {\n const viewer = await getViewer(req)\n\n if (route.queryParams) {\n req.query = await cleanAndValidate(route.queryParams ?? {}, req.query)\n }\n\n if (route.bodyParams) {\n req.body = await cleanAndValidate(route.bodyParams ?? {}, req.body)\n }\n\n const result = await route.resolve(req, res, viewer)\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n for (const key in result.headers) {\n res.setHeader(key, result.headers[key])\n }\n }\n\n // add body to response\n if (!isNil(result.body)) {\n let body = result.body\n\n if (route.returns) {\n body = await cleanAndValidate(route.returns, result.body)\n }\n\n if (type(body) === 'Object') {\n res.json(body)\n } else {\n res.send(body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\nimport express from 'express'\nimport bodyParser from 'body-parser'\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const method = route.method\n\n const handler = async (req, res) => {\n executeRequest(route, req, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (!route.bodyParser && route.bodyParams) {\n const parser = bodyParser.json(route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n}\n","import registerRoute from './registerRoute'\nimport {RoutesMap} from '../types'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n const routes = Object.values(routesMap)\n\n for (const route of routes) {\n registerRoute(route)\n }\n}\n","import {Schema, SchemaFieldType} from '@orion-js/schema'\nimport {RouteType, OrionRouteOptions} from '../types'\n\nexport function createRoute<\n TPath extends string,\n TQueryParamsSchema extends Schema | undefined,\n TBodyParamsSchema extends Schema | undefined,\n TReturnsSchema extends SchemaFieldType | undefined,\n>(\n options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>,\n): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema> {\n return {\n ...options,\n }\n}\n\n/**\n * @deprecated Use createRoute instead\n */\nexport const route = createRoute\n","import {getInstance, Service} from '@orion-js/services'\nimport {createRoute} from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'routes'})\n })\n }\n}\n\nexport function Route(): (method: any, context: ClassFieldDecoratorContext) => any\nexport function Route(\n options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>,\n): (method: any, context: ClassMethodDecoratorContext) => any\nexport function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>) {\n return (method: any, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext) => {\n const propertyKey = String(context.name)\n\n context.addInitializer(function (this) {\n const routes = routeMetadata.get(this) || {}\n\n if (context.kind === 'method') {\n routes[propertyKey] = createRoute({\n ...options,\n resolve: this[propertyKey].bind(this),\n })\n }\n\n if (context.kind === 'field') {\n routes[propertyKey] = this[propertyKey]\n }\n\n routeMetadata.set(this, routes)\n })\n\n return method\n }\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";AACA,OAAO,YAAY;AAInB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,cAAQ,KAAK,iCAAiC,IAAI,IAAI,KAAK,KAAK;AAAA,IAClE;AAEA,UAAM,OAAO,MAAM,QAAQ;AAE3B,QAAI,OAAO,UAAU;AACrB,QAAI,KAAK,IAAI;AAAA,EACf,WAAW,MAAM,gBAAgB;AAC/B,QAAI,UAAU,MAAM,UAAU;AAC9B,QAAI,IAAI,MAAM,OAAO;AACrB,YAAQ,KAAK,mCAAmC,IAAI,IAAI,KAAK,KAAK;AAAA,EACpE,OAAO;AACL,UAAM,OAAO,OACV,WAAW,MAAM,EACjB,OAAO,MAAM,SAAS,MAAM,EAC5B,OAAO,KAAK,EACZ,UAAU,GAAG,EAAE;AAClB,UAAM,aAAa;AACnB,UAAM,OAAO,EAAC,OAAO,KAAK,SAAS,yBAAyB,KAAI;AAEhE,QAAI,UAAU,UAAU;AACxB,QAAI,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAErC,UAAM,OAAO;AACb,YAAQ,MAAM,4CAA4C,IAAI,GAAG,KAAK,KAAK;AAAA,EAC7E;AACF;AAEA,IAAI,aAA8B;AAE3B,IAAM,UAA2B,OAAO,KAAK,KAAK,UAAU;AACjE,QAAM,WAAW,KAAK,KAAK,KAAK;AAClC;AAEO,IA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AACF;AAMO,SAAS,MAAM,SAAkE;AACtF,SAAO,CAAC,QAAa,YAAsE;AACzF,UAAM,cAAc,OAAO,QAAQ,IAAI;AAEvC,YAAQ,eAAe,WAAgB;AACrC,YAAM,SAAS,cAAc,IAAI,IAAI,KAAK,CAAC;AAE3C,UAAI,QAAQ,SAAS,UAAU;AAC7B,eAAO,WAAW,IAAI,YAAY;AAAA,UAChC,GAAG;AAAA,UACH,SAAS,KAAK,WAAW,EAAE,KAAK,IAAI;AAAA,QACtC,CAAC;AAAA,MACH;AAEA,UAAI,QAAQ,SAAS,SAAS;AAC5B,eAAO,WAAW,IAAI,KAAK,WAAW;AAAA,MACxC;AAEA,oBAAc,IAAI,MAAM,MAAM;AAAA,IAChC,CAAC;AAED,WAAO;AAAA,EACT;AACF;AAEO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,WAAW,YAAY,MAAM;AAEnC,MAAI,CAAC,gBAAgB,IAAI,SAAS,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,mBAAmB,gBAAgB,IAAI,SAAS,WAAW;AACjE,MAAI,iBAAiB,iBAAiB,UAAU;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,YAAY,cAAc,IAAI,QAAQ,KAAK,CAAC;AAElD,SAAO;AACT;;;APnDA,IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["express","internalGetEnv","internalGetEnv","route","route","route","bodyParser"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orion-js/http",
|
|
3
|
-
"version": "4.0.0
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"main": "./dist/index.cjs",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"files": [
|
|
@@ -11,11 +11,11 @@
|
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"body-parser": "1.20.3",
|
|
13
13
|
"express": "4.21.2",
|
|
14
|
-
"@orion-js/
|
|
15
|
-
"@orion-js/
|
|
16
|
-
"@orion-js/services": "4.0.0
|
|
17
|
-
"@orion-js/resolvers": "4.0.0
|
|
18
|
-
"@orion-js/schema": "4.0.0
|
|
14
|
+
"@orion-js/helpers": "4.0.0",
|
|
15
|
+
"@orion-js/env": "4.0.0",
|
|
16
|
+
"@orion-js/services": "4.0.0",
|
|
17
|
+
"@orion-js/resolvers": "4.0.0",
|
|
18
|
+
"@orion-js/schema": "4.0.0"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
21
|
"@types/body-parser": "^1.19.1",
|