@thisisagile/easy-express 17.12.2 → 17.13.1

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.
@@ -11,6 +11,7 @@ export declare class ExpressProvider implements AppProvider {
11
11
  protected handle: (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires) => RequestHandler;
12
12
  protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void;
13
13
  protected json(res: Response, result: unknown, options: Required<VerbOptions>): void;
14
+ protected rawJson(res: Response, result: unknown, options: Required<VerbOptions>): void;
14
15
  protected stream(res: Response, result: unknown): void;
15
16
  protected text(res: Response, data: unknown): void;
16
17
  }
@@ -72,6 +72,13 @@ var ExpressProvider = class {
72
72
  res.json(rest.toData(options.onOk, toList(result), result?.total, result?.meta));
73
73
  }
74
74
  }
75
+ rawJson(res, result, options) {
76
+ if (HttpStatus.NoContent.equals(options.onOk)) {
77
+ res.send();
78
+ } else {
79
+ res.json(result);
80
+ }
81
+ }
75
82
  stream(res, result) {
76
83
  res.end(result);
77
84
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/ExpressProvider.ts"],"sourcesContent":["import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport { HttpStatus, isEmpty, PageList, rest, toList, toReq } from '@thisisagile/easy';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n Resource,\n Route,\n RouteRequires,\n routes,\n Service,\n toOriginatedError,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy-service';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n"],"mappings":";;;;;;;;;AAAA,OAAO,aAA2E;AAElF,SAAS,YAAY,SAAmB,MAAM,QAAQ,aAAa;AACn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iBAAW,KAAK,WAAW,SAAS,KAAK,CAAC;AAC9D,QAAI,SAAS;AAAI,iBAAW,KAAK,aAAa,SAAS,EAAE,CAAC;AAC1D,WAAO;AAAA,EACT;AAAA,EAEU,SACR,CAAC,UAAoB,SAAuB,aAC5C,CAAC,KAAc,KAAe,SAC5B,SAAS,MAAM,GAAG,CAAC,EAChB,KAAK,CAAC,MAAW,KAAK,WAAW,KAAK,GAAG,cAAc,OAAO,CAAC,CAAC,EAChE,MAAM,WAAS,KAAK,kBAAkB,OAAO,OAAO,CAAC,CAAC;AAAA,EAEnD,WAAW,KAAe,QAAiB,SAAsC;AACzF,QAAI,OAAO,QAAQ,KAAK,MAAM;AAC9B,QAAI,KAAK,QAAQ,KAAK,IAAI;AAC1B,QAAI,QAAQ,MAAM;AAAS,UAAI,UAAU,QAAQ,MAAM,MAAM,QAAQ,MAAM,MAAM,CAAC;AAElF,KAAE,KAAa,QAAQ,KAAK,IAAI,KAAK,KAAK,MAAM,KAAK,QAAQ,OAAO;AAAA,EACtE;AAAA;AAAA,EAIU,KAAK,KAAe,QAAiB,SAAsC;AACnF,QAAI,WAAW,UAAU,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,KAAK,OAAO,QAAQ,MAAM,OAAY,MAAM,GAAI,QAA0B,OAAQ,QAA0B,IAAI,CAAC;AAAA,IAC5H;AAAA,EACF;AAAA,EAEU,OAAO,KAAe,QAAuB;AACrD,QAAI,IAAI,MAAM;AAAA,EAChB;AAAA,EAEU,KAAK,KAAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,IAAM,UAAU,CAAC,SAA0B,IAAI,QAAQ,MAAM,IAAI,gBAAgB,CAAC;","names":["service","middleware"]}
1
+ {"version":3,"sources":["../../src/express/ExpressProvider.ts"],"sourcesContent":["import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport { HttpStatus, isEmpty, PageList, rest, toList, toReq } from '@thisisagile/easy';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n Resource,\n Route,\n RouteRequires,\n routes,\n Service,\n toOriginatedError,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy-service';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected rawJson(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(result);\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n"],"mappings":";;;;;;;;;AAAA,OAAO,aAA2E;AAElF,SAAS,YAAY,SAAmB,MAAM,QAAQ,aAAa;AACnE;AAAA,EAOE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIA,IAAM,kBAAN,MAA6C;AAAA,EAClD,YAAsB,MAAe,QAAQ,GAAG;AAA1B;AACpB,SAAK,IAAI,IAAI,eAAe,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,EACtE;AAAA,EAEA,MAAM,CAAC,YAA2B;AAChC,SAAK,IAAI,IAAI,OAAO;AAAA,EACtB;AAAA,EAEA,QAAQ,CAACA,UAAkB,aAA6B;AACtD,UAAM,EAAE,OAAO,WAAW,WAAW,IAAI,OAAO,QAAQ;AACxD,UAAM,SAAS,QAAQ,OAAO,EAAE,aAAa,KAAK,CAAC;AACnD,QAAI,CAAC,QAAQ,UAAU;AAAG,aAAO,IAAI,MAAM,MAAMA,SAAQ,IAAI,GAAG,UAAU;AAE1E,cAAU,QAAQ,CAAC,EAAE,UAAU,MAAM,UAAU,YAAAC,YAAW,MAAa;AACrE,cAAQ,IAAI,KAAK,KAAK,MAAM,MAAM,MAAMD,SAAQ,IAAI,CAAC;AACrD,aAAO,KAAK,KAAK,SAAS,CAAg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AAI,WAAW,UAAU,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,KAAK,OAAO,QAAQ,MAAM,OAAY,MAAM,GAAI,QAA0B,OAAQ,QAA0B,IAAI,CAAC;AAAA,IAC5H;AAAA,EACF;AAAA,EAEU,QAAQ,KAAe,QAAiB,SAAsC;AACtF,QAAI,WAAW,UAAU,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,MAAM;AAAA,IACjB;AAAA,EACF;AAAA,EAEU,OAAO,KAAe,QAAuB;AACrD,QAAI,IAAI,MAAM;AAAA,EAChB;AAAA,EAEU,KAAK,KAAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,IAAM,UAAU,CAAC,SAA0B,IAAI,QAAQ,MAAM,IAAI,gBAAgB,CAAC;","names":["service","middleware"]}
package/dist/index.js CHANGED
@@ -177,6 +177,13 @@ var ExpressProvider = class {
177
177
  res.json(import_easy5.rest.toData(options.onOk, (0, import_easy5.toList)(result), result?.total, result?.meta));
178
178
  }
179
179
  }
180
+ rawJson(res, result, options) {
181
+ if (import_easy5.HttpStatus.NoContent.equals(options.onOk)) {
182
+ res.send();
183
+ } else {
184
+ res.json(result);
185
+ }
186
+ }
180
187
  stream(res, result) {
181
188
  res.end(result);
182
189
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/express/AuthError.ts","../src/express/CorrelationHandler.ts","../src/express/ErrorHandler.ts","../src/express/ExpressProvider.ts","../src/express/SecurityHandler.ts","../src/express/NotFoundHandler.ts","../src/express/RequestContextHandler.ts","../src/types/NamespaceContext.ts"],"sourcesContent":["export * from './express';\nexport * from './types';\n","import { HttpStatus, isError } from '@thisisagile/easy';\n\nexport class AuthError extends Error {\n status: number;\n\n constructor({ name, status }: HttpStatus) {\n super(name);\n this.name = 'AuthenticationError';\n this.status = status;\n }\n}\n\nexport const authError = (status: HttpStatus): AuthError => new AuthError(status);\n\nexport const isAuthError = (e?: unknown): e is AuthError => isError(e) && e.name === 'AuthenticationError';\n","import express from 'express';\nimport { ctx, HttpHeader, toUuid } from '@thisisagile/easy';\n\nexport const correlation = (req: express.Request, res: express.Response, next: express.NextFunction): void => {\n res.setHeader(HttpHeader.Correlation, (ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid()));\n next();\n};\n","import express from 'express';\nimport { isAuthError } from './AuthError';\nimport {\n asString,\n choose,\n ctx,\n HttpStatus,\n isDoesNotExist,\n isError,\n isException,\n isResponse,\n isResults,\n isText,\n Response,\n rest,\n Result,\n toHttpStatus,\n toResult,\n tryTo,\n} from '@thisisagile/easy';\nimport { OriginatedError, toOriginatedError } from '@thisisagile/easy-service';\n\nconst toResponse = (status: HttpStatus, errors: Result[] = []): Response => ({\n status,\n body: rest.toError(status, errors),\n});\n\nconst toBody = ({ origin, options }: OriginatedError): Response => {\n return (\n choose(origin)\n .type(isAuthError, ae => toResponse(toHttpStatus(ae.status), [toResult(ae.message)]))\n .type(isDoesNotExist, e => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)]))\n // This service breaks with an error\n .type(isError, e => toResponse(HttpStatus.InternalServerError, [toResult(e.message)]))\n // This service fails\n .type(isResults, r => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results))\n // Underlying service fails\n .type(isResponse, r => toResponse(HttpStatus.InternalServerError, r.body.error?.errors))\n .type(isException, e => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)]))\n // This service fails with a string\n .type(isText, t => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))]))\n .else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]))\n );\n};\n\nexport const error = (e: Error, req: express.Request, res: express.Response, _next: express.NextFunction): void => {\n let response: Response;\n tryTo(() => toOriginatedError(e))\n .map(oe => toBody(oe))\n .accept(r => (response = r))\n .accept(r => (ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : undefined))\n .accept(r => (ctx.request.lastErrorStack = r.status.isServerError ? e.stack : undefined))\n .recover(() => response)\n .accept(r => res.status(r.status.status).json(r.body));\n};\n","import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport { HttpStatus, isEmpty, PageList, rest, toList, toReq } from '@thisisagile/easy';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n Resource,\n Route,\n RouteRequires,\n routes,\n Service,\n toOriginatedError,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy-service';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n","import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n","import { NextFunction, Request, Response } from 'express';\nimport { Exception } from '@thisisagile/easy';\nimport { toOriginatedError } from '@thisisagile/easy-service';\n\nexport const notFound = (req: Request, res: Response, next: NextFunction): void => {\n next(toOriginatedError(Exception.DoesNotExist));\n};\n","import express from 'express';\nimport { ctx } from '@thisisagile/easy';\n\nexport const requestContext = (req: express.Request, res: express.Response, next: express.NextFunction): void => ctx.request.create(() => next());\n","import { createNamespace } from 'cls-hooked';\nimport { BaseRequestContext } from '@thisisagile/easy';\n\nexport class NamespaceContext extends BaseRequestContext {\n protected readonly namespace = createNamespace('context');\n\n public get<T>(key: string): T {\n return this.namespace.get(key) as T;\n }\n\n public set<T>(key: string, value: T): T {\n return this.namespace.set(key, value);\n }\n\n public readonly create = (f: () => void): void => this.namespace.run(f);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAoC;AAE7B,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC;AAAA,EAEA,YAAY,EAAE,MAAM,OAAO,GAAe;AACxC,UAAM,IAAI;AACV,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,IAAM,YAAY,CAAC,WAAkC,IAAI,UAAU,MAAM;AAEzE,IAAM,cAAc,CAAC,UAAgC,qBAAQ,CAAC,KAAK,EAAE,SAAS;;;ACbrF,IAAAA,eAAwC;AAEjC,IAAM,cAAc,CAAC,KAAsB,KAAuB,SAAqC;AAC5G,MAAI,UAAU,wBAAW,aAAc,iBAAI,QAAQ,gBAAgB,KAAK,OAAO,wBAAW,WAAW,SAAK,qBAAO,CAAE;AACnH,OAAK;AACP;;;ACJA,IAAAC,eAiBO;AACP,0BAAmD;AAEnD,IAAM,aAAa,CAAC,QAAoB,SAAmB,CAAC,OAAiB;AAAA,EAC3E;AAA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AAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,IAAM,UAAU,CAAC,SAA0B,IAAI,6BAAQ,MAAM,IAAI,gBAAgB,CAAC;;;AE9FzF,IAAAC,eAA0B;AAC1B,IAAAC,uBAAkC;AAE3B,IAAM,WAAW,CAAC,KAAc,KAAe,SAA6B;AACjF,WAAK,wCAAkB,uBAAU,YAAY,CAAC;AAChD;;;ACLA,IAAAC,eAAoB;AAEb,IAAM,iBAAiB,CAAC,KAAsB,KAAuB,SAAqC,iBAAI,QAAQ,OAAO,MAAM,KAAK,CAAC;;;ACHhJ,wBAAgC;AAChC,IAAAC,eAAmC;AAE5B,IAAM,mBAAN,cAA+B,gCAAmB;AAAA,EACpC,gBAAY,mCAAgB,SAAS;AAAA,EAEjD,IAAO,KAAgB;AAC5B,WAAO,KAAK,UAAU,IAAI,GAAG;AAAA,EAC/B;AAAA,EAEO,IAAO,KAAa,OAAa;AACtC,WAAO,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACtC;AAAA,EAEgB,SAAS,CAAC,MAAwB,KAAK,UAAU,IAAI,CAAC;AACxE;","names":["import_easy","import_easy","import_easy","passport","JwtStrategy","import_easy","import_easy_service","express","service","middleware","error","import_easy","import_easy_service","import_easy","import_easy"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/express/AuthError.ts","../src/express/CorrelationHandler.ts","../src/express/ErrorHandler.ts","../src/express/ExpressProvider.ts","../src/express/SecurityHandler.ts","../src/express/NotFoundHandler.ts","../src/express/RequestContextHandler.ts","../src/types/NamespaceContext.ts"],"sourcesContent":["export * from './express';\nexport * from './types';\n","import { HttpStatus, isError } from '@thisisagile/easy';\n\nexport class AuthError extends Error {\n status: number;\n\n constructor({ name, status }: HttpStatus) {\n super(name);\n this.name = 'AuthenticationError';\n this.status = status;\n }\n}\n\nexport const authError = (status: HttpStatus): AuthError => new AuthError(status);\n\nexport const isAuthError = (e?: unknown): e is AuthError => isError(e) && e.name === 'AuthenticationError';\n","import express from 'express';\nimport { ctx, HttpHeader, toUuid } from '@thisisagile/easy';\n\nexport const correlation = (req: express.Request, res: express.Response, next: express.NextFunction): void => {\n res.setHeader(HttpHeader.Correlation, (ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid()));\n next();\n};\n","import express from 'express';\nimport { isAuthError } from './AuthError';\nimport {\n asString,\n choose,\n ctx,\n HttpStatus,\n isDoesNotExist,\n isError,\n isException,\n isResponse,\n isResults,\n isText,\n Response,\n rest,\n Result,\n toHttpStatus,\n toResult,\n tryTo,\n} from '@thisisagile/easy';\nimport { OriginatedError, toOriginatedError } from '@thisisagile/easy-service';\n\nconst toResponse = (status: HttpStatus, errors: Result[] = []): Response => ({\n status,\n body: rest.toError(status, errors),\n});\n\nconst toBody = ({ origin, options }: OriginatedError): Response => {\n return (\n choose(origin)\n .type(isAuthError, ae => toResponse(toHttpStatus(ae.status), [toResult(ae.message)]))\n .type(isDoesNotExist, e => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)]))\n // This service breaks with an error\n .type(isError, e => toResponse(HttpStatus.InternalServerError, [toResult(e.message)]))\n // This service fails\n .type(isResults, r => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results))\n // Underlying service fails\n .type(isResponse, r => toResponse(HttpStatus.InternalServerError, r.body.error?.errors))\n .type(isException, e => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)]))\n // This service fails with a string\n .type(isText, t => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))]))\n .else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]))\n );\n};\n\nexport const error = (e: Error, req: express.Request, res: express.Response, _next: express.NextFunction): void => {\n let response: Response;\n tryTo(() => toOriginatedError(e))\n .map(oe => toBody(oe))\n .accept(r => (response = r))\n .accept(r => (ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : undefined))\n .accept(r => (ctx.request.lastErrorStack = r.status.isServerError ? e.stack : undefined))\n .recover(() => response)\n .accept(r => res.status(r.status.status).json(r.body));\n};\n","import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport { HttpStatus, isEmpty, PageList, rest, toList, toReq } from '@thisisagile/easy';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n Resource,\n Route,\n RouteRequires,\n routes,\n Service,\n toOriginatedError,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy-service';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected rawJson(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(result);\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n","import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n","import { NextFunction, Request, Response } from 'express';\nimport { Exception } from '@thisisagile/easy';\nimport { toOriginatedError } from '@thisisagile/easy-service';\n\nexport const notFound = (req: Request, res: Response, next: NextFunction): void => {\n next(toOriginatedError(Exception.DoesNotExist));\n};\n","import express from 'express';\nimport { ctx } from '@thisisagile/easy';\n\nexport const requestContext = (req: express.Request, res: express.Response, next: express.NextFunction): void => ctx.request.create(() => next());\n","import { createNamespace } from 'cls-hooked';\nimport { BaseRequestContext } from '@thisisagile/easy';\n\nexport class NamespaceContext extends BaseRequestContext {\n protected readonly namespace = createNamespace('context');\n\n public get<T>(key: string): T {\n return this.namespace.get(key) as T;\n }\n\n public set<T>(key: string, value: T): T {\n return this.namespace.set(key, value);\n }\n\n public readonly create = (f: () => void): void => this.namespace.run(f);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAoC;AAE7B,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC;AAAA,EAEA,YAAY,EAAE,MAAM,OAAO,GAAe;AACxC,UAAM,IAAI;AACV,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,IAAM,YAAY,CAAC,WAAkC,IAAI,UAAU,MAAM;AAEzE,IAAM,cAAc,CAAC,UAAgC,qBAAQ,CAAC,KAAK,EAAE,SAAS;;;ACbrF,IAAAA,eAAwC;AAEjC,IAAM,cAAc,CAAC,KAAsB,KAAuB,SAAqC;AAC5G,MAAI,UAAU,wBAAW,aAAc,iBAAI,QAAQ,gBAAgB,KAAK,OAAO,wBAAW,WAAW,SAAK,qBAAO,CAAE;AACnH,OAAK;AACP;;;ACJA,IAAAC,eAiBO;AACP,0BAAmD;AAEnD,IAAM,aAAa,CAAC,QAAoB,SAAmB,CAAC,OAAiB;AAAA,EAC3E;AAAA,E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AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,MAAM;AAAA,IACjB;AAAA,EACF;AAAA,EAEU,OAAO,KAAe,QAAuB;AACrD,QAAI,IAAI,MAAM;AAAA,EAChB;AAAA,EAEU,KAAK,KAAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,IAAM,UAAU,CAAC,SAA0B,IAAI,6BAAQ,MAAM,IAAI,gBAAgB,CAAC;;;AEtGzF,IAAAC,eAA0B;AAC1B,IAAAC,uBAAkC;AAE3B,IAAM,WAAW,CAAC,KAAc,KAAe,SAA6B;AACjF,WAAK,wCAAkB,uBAAU,YAAY,CAAC;AAChD;;;ACLA,IAAAC,eAAoB;AAEb,IAAM,iBAAiB,CAAC,KAAsB,KAAuB,SAAqC,iBAAI,QAAQ,OAAO,MAAM,KAAK,CAAC;;;ACHhJ,wBAAgC;AAChC,IAAAC,eAAmC;AAE5B,IAAM,mBAAN,cAA+B,gCAAmB;AAAA,EACpC,gBAAY,mCAAgB,SAAS;AAAA,EAEjD,IAAO,KAAgB;AAC5B,WAAO,KAAK,UAAU,IAAI,GAAG;AAAA,EAC/B;AAAA,EAEO,IAAO,KAAa,OAAa;AACtC,WAAO,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACtC;AAAA,EAEgB,SAAS,CAAC,MAAwB,KAAK,UAAU,IAAI,CAAC;AACxE;","names":["import_easy","import_easy","import_easy","passport","JwtStrategy","import_easy","import_easy_service","express","service","middleware","error","import_easy","import_easy_service","import_easy","import_easy"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thisisagile/easy-express",
3
- "version": "17.12.2",
3
+ "version": "17.13.1",
4
4
  "description": "Straightforward library for building domain-driven microservice architectures",
5
5
  "author": "Sander Hoogendoorn",
6
6
  "license": "MIT",
@@ -44,8 +44,8 @@
44
44
  "@types/validator": "^13.12.2"
45
45
  },
46
46
  "dependencies": {
47
- "@thisisagile/easy": "^17.12.2",
48
- "@thisisagile/easy-service": "^17.12.2",
47
+ "@thisisagile/easy": "^17.13.1",
48
+ "@thisisagile/easy-service": "^17.13.1",
49
49
  "@types/express": "^4.17.21",
50
50
  "cls-hooked": "^4.2.2",
51
51
  "express": "^4.21.2",
@@ -84,6 +84,14 @@ export class ExpressProvider implements AppProvider {
84
84
  }
85
85
  }
86
86
 
87
+ protected rawJson(res: Response, result: unknown, options: Required<VerbOptions>): void {
88
+ if (HttpStatus.NoContent.equals(options.onOk)) {
89
+ res.send();
90
+ } else {
91
+ res.json(result);
92
+ }
93
+ }
94
+
87
95
  protected stream(res: Response, result: unknown): void {
88
96
  res.end(result);
89
97
  }