UNPKG

apitally

Version:

Simple API monitoring & analytics for REST APIs built with Express, Fastify, NestJS, AdonisJS, Hono, H3, Elysia, Hapi, and Koa.

1 lines 3.94 kB
{"version":3,"sources":["../../src/nestjs/index.ts"],"sourcesContent":["import {\n CallHandler,\n ExecutionContext,\n INestApplication,\n Injectable,\n NestInterceptor,\n} from \"@nestjs/common\";\nimport { catchError, throwError } from \"rxjs\";\n\nimport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\n\nlet setConsumerFn:\n | ((\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n ) => void)\n | null = null;\n\nexport async function useApitally(\n app: INestApplication,\n config: ApitallyConfig,\n) {\n const httpAdapter = app.getHttpAdapter();\n const instance = httpAdapter.getInstance();\n const platform = httpAdapter.constructor.name\n .toLowerCase()\n .includes(\"fastify\")\n ? \"fastify\"\n : \"express\";\n\n if (platform === \"express\") {\n const { useApitally, setConsumer } = await import(\"../express/index.js\");\n setConsumerFn = setConsumer;\n useApitally(instance, config);\n } else if (platform === \"fastify\") {\n const { apitallyPlugin, setConsumer } = await import(\"../fastify/index.js\");\n setConsumerFn = setConsumer;\n await instance.register(apitallyPlugin, config);\n }\n\n app.useGlobalInterceptors(new ApitallyInterceptor(platform));\n}\n\nexport function setConsumer(\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n if (setConsumerFn) {\n setConsumerFn(request, consumer);\n }\n}\n\n@Injectable()\nclass ApitallyInterceptor implements NestInterceptor {\n constructor(private readonly platform: \"express\" | \"fastify\") {}\n\n intercept(context: ExecutionContext, next: CallHandler) {\n return next.handle().pipe(\n catchError((exception) => {\n if (context.getType() === \"http\") {\n const ctx = context.switchToHttp();\n const res = ctx.getResponse();\n\n if (this.platform === \"express\" && res.locals) {\n res.locals.serverError = exception;\n } else if (\n this.platform === \"fastify\" &&\n (!exception.statusCode || exception.statusCode === 500)\n ) {\n res.serverError = exception;\n }\n }\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ACnD;AACAJ,cAAIG,cAAcP;QACpB;MACF;AACA,iBAAOS,wBAAW,MAAMT,SAAAA;IAC1B,CAAA,CAAA;EAEJ;AACF,GAvBMT,mCADN;;;;;;;;","names":["setConsumerFn","useApitally","app","config","httpAdapter","getHttpAdapter","instance","getInstance","platform","name","toLowerCase","includes","setConsumer","apitallyPlugin","register","useGlobalInterceptors","ApitallyInterceptor","request","consumer","intercept","context","next","handle","pipe","catchError","exception","getType","ctx","switchToHttp","res","getResponse","locals","serverError","statusCode","throwError"]}