@orion-js/http 4.0.18 → 4.0.19
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 +18 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +18 -1
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -128,6 +128,9 @@ var getServer = () => {
|
|
|
128
128
|
// src/index.ts
|
|
129
129
|
var import_express2 = __toESM(require("express"), 1);
|
|
130
130
|
|
|
131
|
+
// src/routes/executeRequest.ts
|
|
132
|
+
var import_logger2 = require("@orion-js/logger");
|
|
133
|
+
|
|
131
134
|
// ../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js
|
|
132
135
|
function type(input) {
|
|
133
136
|
if (input === null) {
|
|
@@ -168,7 +171,21 @@ async function executeRequest(route2, req, res) {
|
|
|
168
171
|
if (route2.bodyParams) {
|
|
169
172
|
req.body = await (0, import_schema.cleanAndValidate)(route2.bodyParams ?? {}, req.body);
|
|
170
173
|
}
|
|
171
|
-
const
|
|
174
|
+
const context = {
|
|
175
|
+
controllerType: "route",
|
|
176
|
+
routeName: route2.path,
|
|
177
|
+
pathname: req.path,
|
|
178
|
+
viewer,
|
|
179
|
+
params: {
|
|
180
|
+
body: req.body,
|
|
181
|
+
query: req.query,
|
|
182
|
+
params: req.params
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
const result = await (0, import_logger2.runWithOrionAsyncContext)(context, async () => {
|
|
186
|
+
(0, import_logger2.updateOrionAsyncContext)({ viewer });
|
|
187
|
+
return await route2.resolve(req, res, viewer);
|
|
188
|
+
});
|
|
172
189
|
if (!result) return;
|
|
173
190
|
if (result.statusCode) {
|
|
174
191
|
res.status(result.statusCode);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 'node:crypto'\nimport {logger} from '@orion-js/logger'\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 logger.error(`[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 logger.error(`[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 logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAAA;AAAA,EAAA;AAAA,iCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,yBAAmB;AACnB,oBAAqB;AAIrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,2BAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;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,yBAAO,MAAM,mCAAmC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,EACtE,OAAO;AACL,UAAM,OAAO,mBAAAC,QACV,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,UA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AAErD,SAAS,SAAS;AACvB,SAAO,CAAC,QAAa,YAAwC;AAC3D,iCAAQ,EAAE,QAAQ,OAAO;AAEzB,YAAQ,eAAe,WAAgB;AACrC,sBAAgB,IAAI,MAAM,EAAC,cAAc,SAAQ,CAAC;AAAA,IACpD,CAAC;AAAA,EACH;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,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/routes/executeRequest.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/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 'node:crypto'\nimport {logger} from '@orion-js/logger'\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 logger.error(`[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 logger.error(`[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 logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\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 {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\nimport {runWithOrionAsyncContext, updateOrionAsyncContext} from '@orion-js/logger'\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 context = {\n controllerType: 'route' as const,\n routeName: route.path,\n pathname: req.path,\n viewer,\n params: {\n body: req.body,\n query: req.query,\n params: req.params,\n },\n }\n\n const result = await runWithOrionAsyncContext(context, async () => {\n updateOrionAsyncContext({viewer})\n return await route.resolve(req, res, viewer)\n })\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","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 {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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAAA;AAAA,EAAA;AAAA,iCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,yBAAmB;AACnB,oBAAqB;AAIrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,2BAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;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,yBAAO,MAAM,mCAAmC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,EACtE,OAAO;AACL,UAAM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,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_logger","import_env","import_helpers","route","route","bodyParser","route","import_body_parser","bodyParserLib","bodyParser"]}
|
package/dist/index.js
CHANGED
|
@@ -78,6 +78,9 @@ var getServer = () => {
|
|
|
78
78
|
// src/index.ts
|
|
79
79
|
import express2 from "express";
|
|
80
80
|
|
|
81
|
+
// src/routes/executeRequest.ts
|
|
82
|
+
import { runWithOrionAsyncContext, updateOrionAsyncContext } from "@orion-js/logger";
|
|
83
|
+
|
|
81
84
|
// ../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js
|
|
82
85
|
function type(input) {
|
|
83
86
|
if (input === null) {
|
|
@@ -118,7 +121,21 @@ async function executeRequest(route2, req, res) {
|
|
|
118
121
|
if (route2.bodyParams) {
|
|
119
122
|
req.body = await cleanAndValidate(route2.bodyParams ?? {}, req.body);
|
|
120
123
|
}
|
|
121
|
-
const
|
|
124
|
+
const context = {
|
|
125
|
+
controllerType: "route",
|
|
126
|
+
routeName: route2.path,
|
|
127
|
+
pathname: req.path,
|
|
128
|
+
viewer,
|
|
129
|
+
params: {
|
|
130
|
+
body: req.body,
|
|
131
|
+
query: req.query,
|
|
132
|
+
params: req.params
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const result = await runWithOrionAsyncContext(context, async () => {
|
|
136
|
+
updateOrionAsyncContext({ viewer });
|
|
137
|
+
return await route2.resolve(req, res, viewer);
|
|
138
|
+
});
|
|
122
139
|
if (!result) return;
|
|
123
140
|
if (result.statusCode) {
|
|
124
141
|
res.status(result.statusCode);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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 'node:crypto'\nimport {logger} from '@orion-js/logger'\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 logger.error(`[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 logger.error(`[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 logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\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;AACnB,SAAQ,cAAa;AAIrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,aAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;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,WAAO,MAAM,mCAAmC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,EACtE,OAAO;AACL,UAAM,OAAO,OACV,WAAW,MAAM,EACjB,OAAO,MAAM,SAAS,MAAM,EAC5B,OAAO,KAAK,EACZ,UAAU,GAAG,EAA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AAM,KAAK,MAAM,WAAU,IAAI;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["express","internalGetEnv","internalGetEnv","route","route","route","bodyParser"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/index.ts","../src/routes/executeRequest.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/registerRoute.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import express from 'express'\nimport crypto from 'node:crypto'\nimport {logger} from '@orion-js/logger'\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 logger.error(`[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 logger.error(`[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 logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\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","import {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\nimport {runWithOrionAsyncContext, updateOrionAsyncContext} from '@orion-js/logger'\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 context = {\n controllerType: 'route' as const,\n routeName: route.path,\n pathname: req.path,\n viewer,\n params: {\n body: req.body,\n query: req.query,\n params: req.params,\n },\n }\n\n const result = await runWithOrionAsyncContext(context, async () => {\n updateOrionAsyncContext({viewer})\n return await route.resolve(req, res, viewer)\n })\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","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 {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;AACnB,SAAQ,cAAa;AAIrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,aAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;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,WAAO,MAAM,mCAAmC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,EACtE,OAAO;AACL,UAAM,OAAO,OACV,WAAW,MAAM,EACjB,OAAO,MAAM,SAAS,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T;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.
|
|
3
|
+
"version": "4.0.19",
|
|
4
4
|
"main": "./dist/index.cjs",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"files": [
|
|
@@ -11,14 +11,14 @@
|
|
|
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/
|
|
17
|
-
"@orion-js/schema": "4.0.
|
|
18
|
-
"@orion-js/services": "4.0.
|
|
14
|
+
"@orion-js/helpers": "4.0.3",
|
|
15
|
+
"@orion-js/env": "4.0.5",
|
|
16
|
+
"@orion-js/resolvers": "4.0.14",
|
|
17
|
+
"@orion-js/schema": "4.0.14",
|
|
18
|
+
"@orion-js/services": "4.0.4"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
|
-
"@orion-js/logger": "4.0.
|
|
21
|
+
"@orion-js/logger": "4.0.6"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@types/body-parser": "^1.19.1",
|