@syswatch/nestjs 1.0.2 → 1.0.4

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.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var I=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var b=(r,t)=>{for(var e in t)I(r,e,{get:t[e],enumerable:!0})},N=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of E(t))!M.call(r,s)&&s!==e&&I(r,s,{get:()=>t[s],enumerable:!(i=H(t,s))||i.enumerable});return r};var D=r=>N(I({},"__esModule",{value:!0}),r),d=(r,t,e,i)=>{for(var s=i>1?void 0:i?H(t,e):t,l=r.length-1,p;l>=0;l--)(p=r[l])&&(s=(i?p(t,e,s):p(s))||s);return i&&s&&I(t,e,s),s},y=(r,t)=>(e,i)=>t(e,i,r);var Y={};b(Y,{LoggerException:()=>O,LoggerInterceptor:()=>v,SYSWATCH_OPTIONS:()=>g,SysWatchModule:()=>m,SysWatchService:()=>a});module.exports=D(Y);var g="SYSWATCH_OPTIONS";var f=require("@nestjs/common"),_=require("@syswatch/core");var a=class extends _.SysWatch{constructor(t){super(t)}async onModuleInit(){this.validateOnFirstUse||await this.init().catch(t=>{f.Logger.error(t.message,"SysWatchService")})}};a=d([(0,f.Injectable)(),y(0,(0,f.Inject)(g))],a);var x=require("@nestjs/common");var m=class{static forRoot(t){return{module:m,providers:[{provide:g,useValue:t},a],exports:[a]}}static forRootAsync(t){return{module:m,imports:t.imports||[],providers:[...this.createAsyncProviders(t),a],exports:[a]}}static createAsyncProviders(t){return t.useExisting||t.useFactory?[this.createAsyncOptionsProvider(t)]:[this.createAsyncOptionsProvider(t),{provide:t.useClass,useClass:t.useClass}]}static createAsyncOptionsProvider(t){return t.useFactory?{provide:g,useFactory:t.useFactory,inject:t.inject||[]}:{provide:g,useFactory:async e=>await e.createSysWatchOptions(),inject:[t.useExisting||t.useClass]}}};m=d([(0,x.Global)(),(0,x.Module)({})],m);var S=require("@nestjs/common"),T=require("rxjs"),R=require("rxjs/operators");var v=class{constructor(t){this.sysWatch=t}intercept(t,e){if(!this.sysWatch||!this.sysWatch.log)return S.Logger.error("SysWatchService not injected. LoggerInterceptor will not log requests."),e.handle();let i=Date.now(),s=t.switchToHttp().getRequest(),l=s.method,p=s.route&&"path"in s.route?s.route.path:s.url,P=s.query,c=s.user?.id||s.user?.sub||s.user?._id,h=s?.id||s.headers?.["x-request-id"]||s.headers?.["x-correlation-id"];return e.handle().pipe((0,R.tap)(o=>{let n=t.switchToHttp().getResponse().statusCode,j=Date.now()-i,q=n.toString().startsWith("2"),C=n.toString().startsWith("4"),w=n.toString().startsWith("5"),A={...h&&{requestId:h},method:l,statusCode:n,url:p,queryParams:P,duration:j,...o&&!q&&{response:typeof o=="string"?o.slice(0,500):o}},F=typeof o=="object"&&!Array.isArray(o)&&"message"in o&&typeof o.message=="string";if(s.logged=!0,q)return this.sysWatch.log.success("http_request",{...c&&{userId:c},meta:A});if(C)return this.sysWatch.log.failure("http_request",{...F?{message:o.message}:{},...c&&{userId:c},meta:A});if(w)return this.sysWatch.log.error("http_request",{...F?{message:o.message}:{},...c&&{userId:c},meta:A});this.sysWatch.log.debug("http_request",{...c&&{userId:c},meta:A})}),(0,R.catchError)(o=>(0,T.throwError)(()=>o)))}};v=d([(0,S.Injectable)(),y(0,(0,S.Inject)(a))],v);var u=require("@nestjs/common");var O=class{constructor(t){this.sysWatch=t}async catch(t,e){if(!this.sysWatch||!this.sysWatch.log)return u.Logger.error("SysWatchService not injected. LoggerInterceptor will not log requests.");let i=e.switchToHttp(),s=i.getRequest(),l=i.getResponse();if(s.logged)return;let p=s.method,P=s.route&&"path"in s.route?s.route.path:s.url,c=s.query,h=s.user?.id||s.user?.sub||s.user?._id,o=s?.id||s.headers?.["x-request-id"]||s.headers?.["x-correlation-id"],W=t.getStatus?t.getStatus():500,n=t instanceof u.HttpException?t.getResponse():{message:"Internal server error"},j=W.toString().startsWith("4"),q=W.toString().startsWith("5"),C={...o&&{requestId:o},method:p,statusCode:W,url:P,queryParams:c,body:typeof n=="string"?n.slice(0,500):n,...t&&t instanceof Error&&!(t instanceof u.HttpException)?{error:t.message}:{}};return j&&this.sysWatch.log.failure("http_request",{...typeof n=="object"&&!Array.isArray(n)&&"message"in n&&typeof n.message=="string"?{message:n.message}:{},...h&&{userId:h},meta:C}),q&&this.sysWatch.log.error("http_request",{...t&&t instanceof Error&&t.message?{message:t.message}:{},...h&&{userId:h},meta:C}),l.status(W).json(n)}};O=d([(0,u.Catch)(),y(0,(0,u.Inject)(a))],O);0&&(module.exports={LoggerException,LoggerInterceptor,SYSWATCH_OPTIONS,SysWatchModule,SysWatchService});
1
+ "use strict";var q=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var b=(r,e)=>{for(var s in e)q(r,s,{get:e[s],enumerable:!0})},E=(r,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of M(e))!T.call(r,t)&&t!==s&&q(r,t,{get:()=>e[t],enumerable:!(n=j(e,t))||n.enumerable});return r};var N=r=>E(q({},"__esModule",{value:!0}),r),u=(r,e,s,n)=>{for(var t=n>1?void 0:n?j(e,s):e,p=r.length-1,m;p>=0;p--)(m=r[p])&&(t=(n?m(e,s,t):m(t))||t);return n&&t&&q(e,s,t),t},g=(r,e)=>(s,n)=>e(s,n,r);var _={};b(_,{LoggerException:()=>v,LoggerInterceptor:()=>S,SYSWATCH_OPTIONS:()=>l,SysWatchModule:()=>d,SysWatchService:()=>i});module.exports=N(_);var l="SYSWATCH_OPTIONS";var y=require("@nestjs/common"),w=require("@syswatch/core");var i=class extends w.SysWatch{constructor(e){super(e)}async onModuleInit(){this.validateOnFirstUse||await this.init().catch(e=>{y.Logger.error(e.message,"SysWatchService")})}};i=u([(0,y.Injectable)(),g(0,(0,y.Inject)(l))],i);var A=require("@nestjs/common");var d=class{static forRoot(e){return{module:d,providers:[{provide:l,useValue:e},i],exports:[i]}}static forRootAsync(e){return{module:d,imports:e.imports||[],providers:[...this.createAsyncProviders(e),i],exports:[i]}}static createAsyncProviders(e){return e.useExisting||e.useFactory?[this.createAsyncOptionsProvider(e)]:[this.createAsyncOptionsProvider(e),{provide:e.useClass,useClass:e.useClass}]}static createAsyncOptionsProvider(e){return e.useFactory?{provide:l,useFactory:e.useFactory,inject:e.inject||[]}:{provide:l,useFactory:async s=>await s.createSysWatchOptions(),inject:[e.useExisting||e.useClass]}}};d=u([(0,A.Global)(),(0,A.Module)({})],d);var h=require("@nestjs/common"),F=require("rxjs"),I=require("rxjs/operators");var S=class{constructor(e){this.sysWatch=e}intercept(e,s){if(!this.sysWatch||!this.sysWatch.log)return h.Logger.error("SysWatchService not injected. LoggerInterceptor will not log requests."),s.handle();let n=Date.now(),t=e.switchToHttp().getRequest(),p=t.method,m=t.route&&"path"in t.route?t.route.path:t.url,x=t.query,O=t.user?.id||t.user?.sub||t.user?._id,f=t?.id||t.headers?.["x-request-id"]||t.headers?.["x-correlation-id"];return s.handle().pipe((0,I.tap)(o=>{let a=e.switchToHttp().getResponse().statusCode,W=Date.now()-n,R=/^(2|3)/.test(a.toString()),P=typeof o=="object"&&o!==null&&!Array.isArray(o)&&"message"in o&&typeof o.message=="string";t.logged=!0,this.sysWatch.log.httpRequest({method:p,url:m,statusCode:a,duration:W,queryParams:x,requestId:typeof f=="string"?f:void 0,...O&&{userId:O},...P&&{message:o.message},...o&&!R&&{response:typeof o=="string"?o.slice(0,500):o}}).catch(H=>{h.Logger.warn(`Falha ao reportar request ao SysWatch: ${H.message}`)})}),(0,I.catchError)(o=>(0,F.throwError)(()=>o)))}};S=u([(0,h.Injectable)(),g(0,(0,h.Inject)(i))],S);var c=require("@nestjs/common");var v=class{constructor(e){this.sysWatch=e}async catch(e,s){if(!this.sysWatch||!this.sysWatch.log)return c.Logger.error("SysWatchService not injected. LoggerInterceptor will not log requests.");let n=s.switchToHttp(),t=n.getRequest(),p=n.getResponse();if(t.logged)return;let m=t.method,x=t.route&&"path"in t.route?t.route.path:t.url,O=t.query,f=t.user?.id||t.user?.sub||t.user?._id,o=t?.id||t.headers?.["x-request-id"]||t.headers?.["x-correlation-id"],C=e.getStatus?e.getStatus():500,a=e instanceof c.HttpException?e.getResponse():{message:"Internal server error"},W=e instanceof Error&&!(e instanceof c.HttpException),R=typeof a=="object"&&a!==null&&!Array.isArray(a)&&typeof a.message=="string"?a.message:void 0;return this.sysWatch.log.httpRequest({method:m,url:x,statusCode:C,queryParams:O,requestId:typeof o=="string"?o:void 0,...f&&{userId:f},message:R??(W&&e.message?e.message:void 0),response:typeof a=="string"?a.slice(0,500):a,...W&&{error:e.message}}).catch(P=>{c.Logger.warn(`Falha ao reportar exce\xE7\xE3o ao SysWatch: ${P.message}`)}),p.status(C).json(a)}};v=u([(0,c.Catch)(),g(0,(0,c.Inject)(i))],v);0&&(module.exports={LoggerException,LoggerInterceptor,SYSWATCH_OPTIONS,SysWatchModule,SysWatchService});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/syswatch.service.ts","../src/syswatch.module.ts","../src/interceptors/logger.interceptor.ts","../src/exceptions/logger.exception.ts"],"sourcesContent":["export * from \"./interfaces\";\nexport * from \"./constants\";\nexport * from \"./syswatch.service\";\nexport * from \"./syswatch.module\";\n\nexport * from \"./interceptors\";\nexport * from \"./exceptions\";\n","export const SYSWATCH_OPTIONS = 'SYSWATCH_OPTIONS';\n","import { Inject, Injectable, Logger, OnModuleInit } from \"@nestjs/common\";\nimport { SysWatch } from \"@syswatch/core\";\nimport { SYSWATCH_OPTIONS } from \"./constants\";\nimport { SysWatchModuleOptions } from \"./interfaces\";\n\n@Injectable()\nexport class SysWatchService extends SysWatch implements OnModuleInit {\n constructor(@Inject(SYSWATCH_OPTIONS) options: SysWatchModuleOptions) {\n super(options);\n }\n\n async onModuleInit() {\n if (this.validateOnFirstUse) {\n return;\n }\n\n await this.init().catch((error) => {\n Logger.error(error.message, \"SysWatchService\");\n });\n }\n}\n","import { DynamicModule, Global, Module, Provider } from '@nestjs/common';\nimport { SysWatchService } from './syswatch.service';\nimport { SYSWATCH_OPTIONS } from './constants';\nimport { SysWatchModuleAsyncOptions, SysWatchModuleOptions, SysWatchOptionsFactory } from './interfaces';\n\n@Global()\n@Module({})\nexport class SysWatchModule {\n static forRoot(options: SysWatchModuleOptions): DynamicModule {\n return {\n module: SysWatchModule,\n providers: [\n {\n provide: SYSWATCH_OPTIONS,\n useValue: options,\n },\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n static forRootAsync(options: SysWatchModuleAsyncOptions): DynamicModule {\n return {\n module: SysWatchModule,\n imports: options.imports || [],\n providers: [\n ...this.createAsyncProviders(options),\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n private static createAsyncProviders(options: SysWatchModuleAsyncOptions): Provider[] {\n if (options.useExisting || options.useFactory) {\n return [this.createAsyncOptionsProvider(options)];\n }\n return [\n this.createAsyncOptionsProvider(options),\n {\n provide: options.useClass!,\n useClass: options.useClass!,\n },\n ];\n }\n\n private static createAsyncOptionsProvider(options: SysWatchModuleAsyncOptions): Provider {\n if (options.useFactory) {\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject || [],\n };\n }\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: async (optionsFactory: SysWatchOptionsFactory) =>\n await optionsFactory.createSysWatchOptions(),\n inject: [options.useExisting || options.useClass!],\n };\n }\n}\n","import {\n CallHandler,\n ExecutionContext,\n Injectable,\n NestInterceptor,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { Observable, throwError } from \"rxjs\";\nimport { catchError, tap } from \"rxjs/operators\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class LoggerInterceptor implements NestInterceptor {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n if (!this.sysWatch || !this.sysWatch.log) {\n Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n\n return next.handle();\n }\n\n const start = Date.now();\n\n const request = context.switchToHttp().getRequest<\n Request & {\n user?: {\n id: string | undefined;\n sub: string | undefined;\n _id: string | undefined;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n return next.handle().pipe(\n tap((body) => {\n const response = context.switchToHttp().getResponse<Response>();\n const statusCode = response.statusCode;\n const duration = Date.now() - start;\n\n const statusCodeSuccess = statusCode.toString().startsWith(\"2\");\n const statusCodeFailure = statusCode.toString().startsWith(\"4\");\n const statusCodeError = statusCode.toString().startsWith(\"5\");\n\n const meta = {\n ...(requestId && { requestId }),\n method,\n statusCode,\n url,\n queryParams,\n duration,\n ...(body &&\n !statusCodeSuccess && {\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n }),\n };\n\n const isValidBody =\n typeof body === \"object\" &&\n !Array.isArray(body) &&\n \"message\" in body &&\n typeof body.message === \"string\";\n\n request[\"logged\"] = true;\n\n if (statusCodeSuccess) {\n return this.sysWatch.log.success(\"http_request\", {\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeFailure) {\n return this.sysWatch.log.failure(\"http_request\", {\n ...(isValidBody ? { message: body.message } : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeError) {\n return this.sysWatch.log.error(\"http_request\", {\n ...(isValidBody ? { message: body.message } : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n this.sysWatch.log.debug(\"http_request\", {\n ...(userId && { userId }),\n meta,\n });\n }),\n catchError((error) => {\n return throwError(() => error);\n }),\n );\n }\n}\n","import {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Catch()\nexport class LoggerException implements ExceptionFilter {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n async catch(exception: any, host: ArgumentsHost) {\n if (!this.sysWatch || !this.sysWatch.log) {\n return Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n }\n\n const ctx = host.switchToHttp();\n\n const request = ctx.getRequest<\n Request & {\n user?: {\n id?: string;\n sub?: string;\n _id?: string;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const response = ctx.getResponse<Response>();\n\n if (request[\"logged\"]) return;\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n const status = exception.getStatus ? exception.getStatus() : 500;\n const body =\n exception instanceof HttpException\n ? exception.getResponse()\n : { message: \"Internal server error\" };\n\n const statusCodeFailure = status.toString().startsWith(\"4\");\n const statusCodeError = status.toString().startsWith(\"5\");\n\n const meta = {\n ...(requestId && { requestId }),\n method,\n statusCode: status,\n url,\n queryParams,\n body: typeof body === \"string\" ? body.slice(0, 500) : body,\n ...(exception &&\n exception instanceof Error &&\n !(exception instanceof HttpException)\n ? { error: exception.message }\n : {}),\n };\n\n if (statusCodeFailure) {\n this.sysWatch.log.failure(\"http_request\", {\n ...(typeof body === \"object\" &&\n !Array.isArray(body) &&\n \"message\" in body &&\n typeof body.message === \"string\"\n ? { message: body.message }\n : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeError) {\n this.sysWatch.log.error(\"http_request\", {\n ...(exception && exception instanceof Error && exception.message\n ? { message: exception.message }\n : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n return response.status(status).json(body);\n }\n}\n"],"mappings":"okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,sBAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAP,GCAO,IAAMQ,EAAmB,mBCAhC,IAAAC,EAAyD,0BACzDC,EAAyB,0BAKlB,IAAMC,EAAN,cAA8B,UAAiC,CACpE,YAAsCC,EAAgC,CACpE,MAAMA,CAAO,CACf,CAEA,MAAM,cAAe,CACf,KAAK,oBAIT,MAAM,KAAK,KAAK,EAAE,MAAOC,GAAU,CACjC,SAAO,MAAMA,EAAM,QAAS,iBAAiB,CAC/C,CAAC,CACH,CACF,EAdaF,EAANG,EAAA,IADN,cAAW,EAEGC,EAAA,eAAOC,CAAgB,IADzBL,GCNb,IAAAM,EAAwD,0BAOjD,IAAMC,EAAN,KAAqB,CAC1B,OAAO,QAAQC,EAA+C,CAC5D,MAAO,CACL,OAAQD,EACR,UAAW,CACT,CACE,QAASE,EACT,SAAUD,CACZ,EACAE,CACF,EACA,QAAS,CAACA,CAAe,CAC3B,CACF,CAEA,OAAO,aAAaF,EAAoD,CACtE,MAAO,CACL,OAAQD,EACR,QAASC,EAAQ,SAAW,CAAC,EAC7B,UAAW,CACT,GAAG,KAAK,qBAAqBA,CAAO,EACpCE,CACF,EACA,QAAS,CAACA,CAAe,CAC3B,CACF,CAEA,OAAe,qBAAqBF,EAAiD,CACnF,OAAIA,EAAQ,aAAeA,EAAQ,WAC1B,CAAC,KAAK,2BAA2BA,CAAO,CAAC,EAE3C,CACL,KAAK,2BAA2BA,CAAO,EACvC,CACE,QAAS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AAC,EACL,GAAIQ,GAAU,CAAE,OAAAA,CAAO,EACvB,KAAAM,CACF,CAAC,EAGIV,EAAS,OAAOM,CAAM,EAAE,KAAKC,CAAI,CAC1C,CACF,EA5Fab,EAANiB,EAAA,IADN,SAAM,EAGFC,EAAA,eAAOC,CAAe,IAFdnB","names":["index_exports","__export","LoggerException","LoggerInterceptor","SYSWATCH_OPTIONS","SysWatchModule","SysWatchService","__toCommonJS","SYSWATCH_OPTIONS","import_common","import_core","SysWatchService","options","error","__decorateClass","__decorateParam","SYSWATCH_OPTIONS","import_common","SysWatchModule","options","SYSWATCH_OPTIONS","SysWatchService","optionsFactory","__decorateClass","import_common","import_rxjs","import_operators","LoggerInterceptor","sysWatch","context","next","start","request","method","url","queryParams","userId","requestId","body","statusCode","duration","statusCodeSuccess","statusCodeFailure","statusCodeError","meta","isValidBody","error","__decorateClass","__decorateParam","SysWatchService","import_common","LoggerException","sysWatch","exception","host","ctx","request","response","method","url","queryParams","userId","requestId","status","body","statusCodeFailure","statusCodeError","meta","__decorateClass","__decorateParam","SysWatchService"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/syswatch.service.ts","../src/syswatch.module.ts","../src/interceptors/logger.interceptor.ts","../src/exceptions/logger.exception.ts"],"sourcesContent":["export * from \"./interfaces\";\nexport * from \"./constants\";\nexport * from \"./syswatch.service\";\nexport * from \"./syswatch.module\";\n\nexport * from \"./interceptors\";\nexport * from \"./exceptions\";\n","export const SYSWATCH_OPTIONS = 'SYSWATCH_OPTIONS';\n","import { Inject, Injectable, Logger, OnModuleInit } from \"@nestjs/common\";\nimport { SysWatch } from \"@syswatch/core\";\nimport { SYSWATCH_OPTIONS } from \"./constants\";\nimport { SysWatchModuleOptions } from \"./interfaces\";\n\n@Injectable()\nexport class SysWatchService extends SysWatch implements OnModuleInit {\n constructor(@Inject(SYSWATCH_OPTIONS) options: SysWatchModuleOptions) {\n super(options);\n }\n\n async onModuleInit() {\n if (this.validateOnFirstUse) {\n return;\n }\n\n await this.init().catch((error) => {\n Logger.error(error.message, \"SysWatchService\");\n });\n }\n}\n","import { DynamicModule, Global, Module, Provider } from '@nestjs/common';\nimport { SysWatchService } from './syswatch.service';\nimport { SYSWATCH_OPTIONS } from './constants';\nimport { SysWatchModuleAsyncOptions, SysWatchModuleOptions, SysWatchOptionsFactory } from './interfaces';\n\n@Global()\n@Module({})\nexport class SysWatchModule {\n static forRoot(options: SysWatchModuleOptions): DynamicModule {\n return {\n module: SysWatchModule,\n providers: [\n {\n provide: SYSWATCH_OPTIONS,\n useValue: options,\n },\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n static forRootAsync(options: SysWatchModuleAsyncOptions): DynamicModule {\n return {\n module: SysWatchModule,\n imports: options.imports || [],\n providers: [\n ...this.createAsyncProviders(options),\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n private static createAsyncProviders(options: SysWatchModuleAsyncOptions): Provider[] {\n if (options.useExisting || options.useFactory) {\n return [this.createAsyncOptionsProvider(options)];\n }\n return [\n this.createAsyncOptionsProvider(options),\n {\n provide: options.useClass!,\n useClass: options.useClass!,\n },\n ];\n }\n\n private static createAsyncOptionsProvider(options: SysWatchModuleAsyncOptions): Provider {\n if (options.useFactory) {\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject || [],\n };\n }\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: async (optionsFactory: SysWatchOptionsFactory) =>\n await optionsFactory.createSysWatchOptions(),\n inject: [options.useExisting || options.useClass!],\n };\n }\n}\n","import {\n CallHandler,\n ExecutionContext,\n Injectable,\n NestInterceptor,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { Observable, throwError } from \"rxjs\";\nimport { catchError, tap } from \"rxjs/operators\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class LoggerInterceptor implements NestInterceptor {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n if (!this.sysWatch || !this.sysWatch.log) {\n Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n\n return next.handle();\n }\n\n const start = Date.now();\n\n const request = context.switchToHttp().getRequest<\n Request & {\n user?: {\n id: string | undefined;\n sub: string | undefined;\n _id: string | undefined;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n return next.handle().pipe(\n tap((body) => {\n const response = context.switchToHttp().getResponse<Response>();\n const statusCode = response.statusCode;\n const duration = Date.now() - start;\n const statusCodeSuccess = /^(2|3)/.test(statusCode.toString());\n\n const isValidBody =\n typeof body === \"object\" &&\n body !== null &&\n !Array.isArray(body) &&\n \"message\" in body &&\n typeof body.message === \"string\";\n\n request[\"logged\"] = true;\n\n this.sysWatch.log\n .httpRequest({\n method,\n url,\n statusCode,\n duration,\n queryParams,\n requestId: typeof requestId === \"string\" ? requestId : undefined,\n ...(userId && { userId }),\n ...(isValidBody && { message: body.message }),\n ...(body &&\n !statusCodeSuccess && {\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n }),\n })\n .catch((error) => {\n // tap() não espera nem observa Promises retornadas pelo seu\n // callback — sem este catch, uma rejeição aqui (ex: API key\n // inválida) vira unhandled rejection e derruba o processo\n // inteiro a cada request (Node 15+ trata isso como fatal).\n Logger.warn(\n `Falha ao reportar request ao SysWatch: ${error.message}`,\n );\n });\n }),\n catchError((error) => {\n return throwError(() => error);\n }),\n );\n }\n}\n","import {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Catch()\nexport class LoggerException implements ExceptionFilter {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n async catch(exception: any, host: ArgumentsHost) {\n if (!this.sysWatch || !this.sysWatch.log) {\n return Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n }\n\n const ctx = host.switchToHttp();\n\n const request = ctx.getRequest<\n Request & {\n user?: {\n id?: string;\n sub?: string;\n _id?: string;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const response = ctx.getResponse<Response>();\n\n if (request[\"logged\"]) return;\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n const status = exception.getStatus ? exception.getStatus() : 500;\n const body =\n exception instanceof HttpException\n ? exception.getResponse()\n : { message: \"Internal server error\" };\n\n const isGenericError =\n exception instanceof Error && !(exception instanceof HttpException);\n\n const bodyMessage: string | undefined =\n typeof body === \"object\" &&\n body !== null &&\n !Array.isArray(body) &&\n typeof (body as { message?: unknown }).message === \"string\"\n ? (body as { message: string }).message\n : undefined;\n\n // .catch aqui é essencial: `catch()` do ExceptionFilter não espera essa\n // chamada (não tem await), então uma rejeição (ex: API key inválida)\n // viraria unhandled rejection e derrubaria o processo a cada exceção.\n this.sysWatch.log\n .httpRequest({\n method,\n url,\n statusCode: status,\n queryParams,\n requestId: typeof requestId === \"string\" ? requestId : undefined,\n ...(userId && { userId }),\n message:\n bodyMessage ??\n (isGenericError && exception.message\n ? exception.message\n : undefined),\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n ...(isGenericError && { error: exception.message }),\n })\n .catch((error) => {\n Logger.warn(`Falha ao reportar exceção ao SysWatch: ${error.message}`);\n });\n\n return response.status(status).json(body);\n }\n}\n"],"mappings":"okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,sBAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAP,GCAO,IAAMQ,EAAmB,mBCAhC,IAAAC,EAAyD,0BACzDC,EAAyB,0BAKlB,IAAMC,EAAN,cAA8B,UAAiC,CACpE,YAAsCC,EAAgC,CACpE,MAAMA,CAAO,CACf,CAEA,MAAM,cAAe,CACf,KAAK,oBAIT,MAAM,KAAK,KAAK,EAAE,MAAOC,GAAU,CACjC,SAAO,MAAMA,EAAM,QAAS,iBAAiB,CAC/C,CAAC,CACH,CACF,EAdaF,EAANG,EAAA,IADN,cAAW,EAEGC,EAAA,eAAOC,CAAgB,IADzBL,GCNb,IAAAM,EAAwD,0BAOjD,IAAMC,EAAN,KAAqB,CAC1B,OAAO,QAAQC,EAA+C,CAC5D,MAAO,CACL,OAAQD,EACR,UAAW,CACT,CACE,QAASE,EACT,SAAUD,CACZ,EACAE,CACF,EACA,QAAS,CAACA,CAAe,CAC3B,CACF,CAEA,OAAO,aAAaF,EAAoD,CACtE,MAAO,CACL,OAAQD,EACR,QAASC,EAAQ,SAAW,CAAC,EAC7B,UAAW,CACT,GAAG,KAAK,qBAAqBA,CAAO,EACpCE,CACF,EACA,QAAS,CAACA,CAAe,CAC3B,CACF,CAEA,OAAe,qBAAqBF,EAAiD,CACnF,OAAIA,EAAQ,aAAeA,EAAQ,WAC1B,CAAC,KAAK,2BAA2BA,CAAO,CAAC,EAE3C,CACL,KAAK,2BAA2BA,CAAO,EACvC,CACE,QAASA,EAAQ,SACjB,SAAUA,EAAQ,QACpB,CACF,CACF,CAEA,OAAe,2BAA2BA,EAA+C,CACvF,OAAIA,EAAQ,WACH,CACL,QAASC,EACT,WAAYD,EAAQ,WACpB,OAAQA,EAAQ,QAAU,CAAC,CAC7B,EAE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AA6B,QAC9B,OAKN,YAAK,SAAS,IACX,YAAY,CACX,OAAAN,EACA,IAAAC,EACA,WAAYI,EACZ,YAAAH,EACA,UAAW,OAAOE,GAAc,SAAWA,EAAY,OACvD,GAAID,GAAU,CAAE,OAAAA,CAAO,EACvB,QACEK,IACCD,GAAkBZ,EAAU,QACzBA,EAAU,QACV,QACN,SAAU,OAAOW,GAAS,SAAWA,EAAK,MAAM,EAAG,GAAG,EAAIA,EAC1D,GAAIC,GAAkB,CAAE,MAAOZ,EAAU,OAAQ,CACnD,CAAC,EACA,MAAOc,GAAU,CAChB,SAAO,KAAK,gDAA0CA,EAAM,OAAO,EAAE,CACvE,CAAC,EAEIV,EAAS,OAAOM,CAAM,EAAE,KAAKC,CAAI,CAC1C,CACF,EAtFab,EAANiB,EAAA,IADN,SAAM,EAGFC,EAAA,eAAOC,CAAe,IAFdnB","names":["index_exports","__export","LoggerException","LoggerInterceptor","SYSWATCH_OPTIONS","SysWatchModule","SysWatchService","__toCommonJS","SYSWATCH_OPTIONS","import_common","import_core","SysWatchService","options","error","__decorateClass","__decorateParam","SYSWATCH_OPTIONS","import_common","SysWatchModule","options","SYSWATCH_OPTIONS","SysWatchService","optionsFactory","__decorateClass","import_common","import_rxjs","import_operators","LoggerInterceptor","sysWatch","context","next","start","request","method","url","queryParams","userId","requestId","body","statusCode","duration","statusCodeSuccess","isValidBody","error","__decorateClass","__decorateParam","SysWatchService","import_common","LoggerException","sysWatch","exception","host","ctx","request","response","method","url","queryParams","userId","requestId","status","body","isGenericError","bodyMessage","error","__decorateClass","__decorateParam","SysWatchService"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var R=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var c=(u,t,i,n)=>{for(var s=n>1?void 0:n?P(t,i):t,d=u.length-1,m;d>=0;d--)(m=u[d])&&(s=(n?m(t,i,s):m(s))||s);return n&&s&&R(t,i,s),s},h=(u,t)=>(i,n)=>t(i,n,u);var g="SYSWATCH_OPTIONS";import{Inject as j,Injectable as F,Logger as H}from"@nestjs/common";import{SysWatch as _}from"@syswatch/core";var o=class extends _{constructor(t){super(t)}async onModuleInit(){this.validateOnFirstUse||await this.init().catch(t=>{H.error(t.message,"SysWatchService")})}};o=c([F(),h(0,j(g))],o);import{Global as T,Module as w}from"@nestjs/common";var p=class{static forRoot(t){return{module:p,providers:[{provide:g,useValue:t},o],exports:[o]}}static forRootAsync(t){return{module:p,imports:t.imports||[],providers:[...this.createAsyncProviders(t),o],exports:[o]}}static createAsyncProviders(t){return t.useExisting||t.useFactory?[this.createAsyncOptionsProvider(t)]:[this.createAsyncOptionsProvider(t),{provide:t.useClass,useClass:t.useClass}]}static createAsyncOptionsProvider(t){return t.useFactory?{provide:g,useFactory:t.useFactory,inject:t.inject||[]}:{provide:g,useFactory:async i=>await i.createSysWatchOptions(),inject:[t.useExisting||t.useClass]}}};p=c([T(),w({})],p);import{Injectable as E,Inject as M,Logger as b}from"@nestjs/common";import{throwError as N}from"rxjs";import{catchError as D,tap as Y}from"rxjs/operators";var v=class{constructor(t){this.sysWatch=t}intercept(t,i){if(!this.sysWatch||!this.sysWatch.log)return b.error("SysWatchService not injected. LoggerInterceptor will not log requests."),i.handle();let n=Date.now(),s=t.switchToHttp().getRequest(),d=s.method,m=s.route&&"path"in s.route?s.route.path:s.url,q=s.query,a=s.user?.id||s.user?.sub||s.user?._id,l=s?.id||s.headers?.["x-request-id"]||s.headers?.["x-correlation-id"];return i.handle().pipe(Y(e=>{let r=t.switchToHttp().getResponse().statusCode,C=Date.now()-n,f=r.toString().startsWith("2"),S=r.toString().startsWith("4"),x=r.toString().startsWith("5"),W={...l&&{requestId:l},method:d,statusCode:r,url:m,queryParams:q,duration:C,...e&&!f&&{response:typeof e=="string"?e.slice(0,500):e}},A=typeof e=="object"&&!Array.isArray(e)&&"message"in e&&typeof e.message=="string";if(s.logged=!0,f)return this.sysWatch.log.success("http_request",{...a&&{userId:a},meta:W});if(S)return this.sysWatch.log.failure("http_request",{...A?{message:e.message}:{},...a&&{userId:a},meta:W});if(x)return this.sysWatch.log.error("http_request",{...A?{message:e.message}:{},...a&&{userId:a},meta:W});this.sysWatch.log.debug("http_request",{...a&&{userId:a},meta:W})}),D(e=>N(()=>e)))}};v=c([E(),h(0,M(o))],v);import{Catch as V,HttpException as I,Inject as B,Logger as G}from"@nestjs/common";var O=class{constructor(t){this.sysWatch=t}async catch(t,i){if(!this.sysWatch||!this.sysWatch.log)return G.error("SysWatchService not injected. LoggerInterceptor will not log requests.");let n=i.switchToHttp(),s=n.getRequest(),d=n.getResponse();if(s.logged)return;let m=s.method,q=s.route&&"path"in s.route?s.route.path:s.url,a=s.query,l=s.user?.id||s.user?.sub||s.user?._id,e=s?.id||s.headers?.["x-request-id"]||s.headers?.["x-correlation-id"],y=t.getStatus?t.getStatus():500,r=t instanceof I?t.getResponse():{message:"Internal server error"},C=y.toString().startsWith("4"),f=y.toString().startsWith("5"),S={...e&&{requestId:e},method:m,statusCode:y,url:q,queryParams:a,body:typeof r=="string"?r.slice(0,500):r,...t&&t instanceof Error&&!(t instanceof I)?{error:t.message}:{}};return C&&this.sysWatch.log.failure("http_request",{...typeof r=="object"&&!Array.isArray(r)&&"message"in r&&typeof r.message=="string"?{message:r.message}:{},...l&&{userId:l},meta:S}),f&&this.sysWatch.log.error("http_request",{...t&&t instanceof Error&&t.message?{message:t.message}:{},...l&&{userId:l},meta:S}),d.status(y).json(r)}};O=c([V(),h(0,B(o))],O);export{O as LoggerException,v as LoggerInterceptor,g as SYSWATCH_OPTIONS,p as SysWatchModule,o as SysWatchService};
1
+ var R=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var a=(c,e,o,i)=>{for(var t=i>1?void 0:i?P(e,o):e,u=c.length-1,d;u>=0;u--)(d=c[u])&&(t=(i?d(e,o,t):d(t))||t);return i&&t&&R(e,o,t),t},m=(c,e)=>(o,i)=>e(o,i,c);var l="SYSWATCH_OPTIONS";import{Inject as j,Injectable as w,Logger as F}from"@nestjs/common";import{SysWatch as H}from"@syswatch/core";var r=class extends H{constructor(e){super(e)}async onModuleInit(){this.validateOnFirstUse||await this.init().catch(e=>{F.error(e.message,"SysWatchService")})}};r=a([w(),m(0,j(l))],r);import{Global as M,Module as T}from"@nestjs/common";var p=class{static forRoot(e){return{module:p,providers:[{provide:l,useValue:e},r],exports:[r]}}static forRootAsync(e){return{module:p,imports:e.imports||[],providers:[...this.createAsyncProviders(e),r],exports:[r]}}static createAsyncProviders(e){return e.useExisting||e.useFactory?[this.createAsyncOptionsProvider(e)]:[this.createAsyncOptionsProvider(e),{provide:e.useClass,useClass:e.useClass}]}static createAsyncOptionsProvider(e){return e.useFactory?{provide:l,useFactory:e.useFactory,inject:e.inject||[]}:{provide:l,useFactory:async o=>await o.createSysWatchOptions(),inject:[e.useExisting||e.useClass]}}};p=a([M(),T({})],p);import{Injectable as b,Inject as E,Logger as A}from"@nestjs/common";import{throwError as N}from"rxjs";import{catchError as _,tap as D}from"rxjs/operators";var f=class{constructor(e){this.sysWatch=e}intercept(e,o){if(!this.sysWatch||!this.sysWatch.log)return A.error("SysWatchService not injected. LoggerInterceptor will not log requests."),o.handle();let i=Date.now(),t=e.switchToHttp().getRequest(),u=t.method,d=t.route&&"path"in t.route?t.route.path:t.url,v=t.query,g=t.user?.id||t.user?.sub||t.user?._id,h=t?.id||t.headers?.["x-request-id"]||t.headers?.["x-correlation-id"];return o.handle().pipe(D(s=>{let n=e.switchToHttp().getResponse().statusCode,y=Date.now()-i,W=/^(2|3)/.test(n.toString()),q=typeof s=="object"&&s!==null&&!Array.isArray(s)&&"message"in s&&typeof s.message=="string";t.logged=!0,this.sysWatch.log.httpRequest({method:u,url:d,statusCode:n,duration:y,queryParams:v,requestId:typeof h=="string"?h:void 0,...g&&{userId:g},...q&&{message:s.message},...s&&!W&&{response:typeof s=="string"?s.slice(0,500):s}}).catch(C=>{A.warn(`Falha ao reportar request ao SysWatch: ${C.message}`)})}),_(s=>N(()=>s)))}};f=a([b(),m(0,E(r))],f);import{Catch as Y,HttpException as I,Inject as G,Logger as x}from"@nestjs/common";var S=class{constructor(e){this.sysWatch=e}async catch(e,o){if(!this.sysWatch||!this.sysWatch.log)return x.error("SysWatchService not injected. LoggerInterceptor will not log requests.");let i=o.switchToHttp(),t=i.getRequest(),u=i.getResponse();if(t.logged)return;let d=t.method,v=t.route&&"path"in t.route?t.route.path:t.url,g=t.query,h=t.user?.id||t.user?.sub||t.user?._id,s=t?.id||t.headers?.["x-request-id"]||t.headers?.["x-correlation-id"],O=e.getStatus?e.getStatus():500,n=e instanceof I?e.getResponse():{message:"Internal server error"},y=e instanceof Error&&!(e instanceof I),W=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.message=="string"?n.message:void 0;return this.sysWatch.log.httpRequest({method:d,url:v,statusCode:O,queryParams:g,requestId:typeof s=="string"?s:void 0,...h&&{userId:h},message:W??(y&&e.message?e.message:void 0),response:typeof n=="string"?n.slice(0,500):n,...y&&{error:e.message}}).catch(q=>{x.warn(`Falha ao reportar exce\xE7\xE3o ao SysWatch: ${q.message}`)}),u.status(O).json(n)}};S=a([Y(),m(0,G(r))],S);export{S as LoggerException,f as LoggerInterceptor,l as SYSWATCH_OPTIONS,p as SysWatchModule,r as SysWatchService};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/syswatch.service.ts","../src/syswatch.module.ts","../src/interceptors/logger.interceptor.ts","../src/exceptions/logger.exception.ts"],"sourcesContent":["export const SYSWATCH_OPTIONS = 'SYSWATCH_OPTIONS';\n","import { Inject, Injectable, Logger, OnModuleInit } from \"@nestjs/common\";\nimport { SysWatch } from \"@syswatch/core\";\nimport { SYSWATCH_OPTIONS } from \"./constants\";\nimport { SysWatchModuleOptions } from \"./interfaces\";\n\n@Injectable()\nexport class SysWatchService extends SysWatch implements OnModuleInit {\n constructor(@Inject(SYSWATCH_OPTIONS) options: SysWatchModuleOptions) {\n super(options);\n }\n\n async onModuleInit() {\n if (this.validateOnFirstUse) {\n return;\n }\n\n await this.init().catch((error) => {\n Logger.error(error.message, \"SysWatchService\");\n });\n }\n}\n","import { DynamicModule, Global, Module, Provider } from '@nestjs/common';\nimport { SysWatchService } from './syswatch.service';\nimport { SYSWATCH_OPTIONS } from './constants';\nimport { SysWatchModuleAsyncOptions, SysWatchModuleOptions, SysWatchOptionsFactory } from './interfaces';\n\n@Global()\n@Module({})\nexport class SysWatchModule {\n static forRoot(options: SysWatchModuleOptions): DynamicModule {\n return {\n module: SysWatchModule,\n providers: [\n {\n provide: SYSWATCH_OPTIONS,\n useValue: options,\n },\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n static forRootAsync(options: SysWatchModuleAsyncOptions): DynamicModule {\n return {\n module: SysWatchModule,\n imports: options.imports || [],\n providers: [\n ...this.createAsyncProviders(options),\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n private static createAsyncProviders(options: SysWatchModuleAsyncOptions): Provider[] {\n if (options.useExisting || options.useFactory) {\n return [this.createAsyncOptionsProvider(options)];\n }\n return [\n this.createAsyncOptionsProvider(options),\n {\n provide: options.useClass!,\n useClass: options.useClass!,\n },\n ];\n }\n\n private static createAsyncOptionsProvider(options: SysWatchModuleAsyncOptions): Provider {\n if (options.useFactory) {\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject || [],\n };\n }\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: async (optionsFactory: SysWatchOptionsFactory) =>\n await optionsFactory.createSysWatchOptions(),\n inject: [options.useExisting || options.useClass!],\n };\n }\n}\n","import {\n CallHandler,\n ExecutionContext,\n Injectable,\n NestInterceptor,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { Observable, throwError } from \"rxjs\";\nimport { catchError, tap } from \"rxjs/operators\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class LoggerInterceptor implements NestInterceptor {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n if (!this.sysWatch || !this.sysWatch.log) {\n Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n\n return next.handle();\n }\n\n const start = Date.now();\n\n const request = context.switchToHttp().getRequest<\n Request & {\n user?: {\n id: string | undefined;\n sub: string | undefined;\n _id: string | undefined;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n return next.handle().pipe(\n tap((body) => {\n const response = context.switchToHttp().getResponse<Response>();\n const statusCode = response.statusCode;\n const duration = Date.now() - start;\n\n const statusCodeSuccess = statusCode.toString().startsWith(\"2\");\n const statusCodeFailure = statusCode.toString().startsWith(\"4\");\n const statusCodeError = statusCode.toString().startsWith(\"5\");\n\n const meta = {\n ...(requestId && { requestId }),\n method,\n statusCode,\n url,\n queryParams,\n duration,\n ...(body &&\n !statusCodeSuccess && {\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n }),\n };\n\n const isValidBody =\n typeof body === \"object\" &&\n !Array.isArray(body) &&\n \"message\" in body &&\n typeof body.message === \"string\";\n\n request[\"logged\"] = true;\n\n if (statusCodeSuccess) {\n return this.sysWatch.log.success(\"http_request\", {\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeFailure) {\n return this.sysWatch.log.failure(\"http_request\", {\n ...(isValidBody ? { message: body.message } : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeError) {\n return this.sysWatch.log.error(\"http_request\", {\n ...(isValidBody ? { message: body.message } : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n this.sysWatch.log.debug(\"http_request\", {\n ...(userId && { userId }),\n meta,\n });\n }),\n catchError((error) => {\n return throwError(() => error);\n }),\n );\n }\n}\n","import {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Catch()\nexport class LoggerException implements ExceptionFilter {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n async catch(exception: any, host: ArgumentsHost) {\n if (!this.sysWatch || !this.sysWatch.log) {\n return Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n }\n\n const ctx = host.switchToHttp();\n\n const request = ctx.getRequest<\n Request & {\n user?: {\n id?: string;\n sub?: string;\n _id?: string;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const response = ctx.getResponse<Response>();\n\n if (request[\"logged\"]) return;\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n const status = exception.getStatus ? exception.getStatus() : 500;\n const body =\n exception instanceof HttpException\n ? exception.getResponse()\n : { message: \"Internal server error\" };\n\n const statusCodeFailure = status.toString().startsWith(\"4\");\n const statusCodeError = status.toString().startsWith(\"5\");\n\n const meta = {\n ...(requestId && { requestId }),\n method,\n statusCode: status,\n url,\n queryParams,\n body: typeof body === \"string\" ? body.slice(0, 500) : body,\n ...(exception &&\n exception instanceof Error &&\n !(exception instanceof HttpException)\n ? { error: exception.message }\n : {}),\n };\n\n if (statusCodeFailure) {\n this.sysWatch.log.failure(\"http_request\", {\n ...(typeof body === \"object\" &&\n !Array.isArray(body) &&\n \"message\" in body &&\n typeof body.message === \"string\"\n ? { message: body.message }\n : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeError) {\n this.sysWatch.log.error(\"http_request\", {\n ...(exception && exception instanceof Error && exception.message\n ? { message: exception.message }\n : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n return response.status(status).json(body);\n }\n}\n"],"mappings":"iOAAO,IAAMA,EAAmB,mBCAhC,OAAS,UAAAC,EAAQ,cAAAC,EAAY,UAAAC,MAA4B,iBACzD,OAAS,YAAAC,MAAgB,iBAKlB,IAAMC,EAAN,cAA8BC,CAAiC,CACpE,YAAsCC,EAAgC,CACpE,MAAMA,CAAO,CACf,CAEA,MAAM,cAAe,CACf,KAAK,oBAIT,MAAM,KAAK,KAAK,EAAE,MAAOC,GAAU,CACjCC,EAAO,MAAMD,EAAM,QAAS,iBAAiB,CAC/C,CAAC,CACH,CACF,EAdaH,EAANK,EAAA,CADNC,EAAW,EAEGC,EAAA,EAAAC,EAAOC,CAAgB,IADzBT,GCNb,OAAwB,UAAAU,EAAQ,UAAAC,MAAwB,iBAOjD,IAAMC,EAAN,KAAqB,CAC1B,OAAO,QAAQC,EAA+C,CAC5D,MAAO,CACL,OAAQD,EACR,UAAW,CACT,CACE,QAASE,EACT,SAAUD,CACZ,EACAE,CACF,EACA,QAAS,CAACA,CAAe,CAC3B,CACF,CAEA,OAAO,aAAaF,EAAoD,CACtE,MAAO,CACL,OAAQD,EACR,QAASC,EAAQ,SAAW,CAAC,EAC7B,UAAW,CACT,GAAG,KAAK,qBAAqBA,CAAO,EACpCE,CACF,EACA,QAAS,CAACA,CAAe,CAC3B,CACF,CAEA,OAAe,qBAAqBF,EAAiD,CACnF,OAAIA,EAAQ,aAAeA,EAAQ,WAC1B,CAAC,KAAK,2BAA2BA,CAAO,CAAC,EAE3C,CACL,KAAK,2BAA2BA,CAAO,EACvC,CACE,QAASA,EAAQ,SACjB,SAAUA,EAAQ,QACpB,CACF,CACF,CAEA,OAAe,2BAA2BA,EAA+C,CACvF,OAAIA,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AAU,QACrD,CAAE,QAASA,EAAU,OAAQ,EAC7B,CAAC,EACL,GAAIS,GAAU,CAAE,OAAAA,CAAO,EACvB,KAAAO,CACF,CAAC,EAGIX,EAAS,OAAOM,CAAM,EAAE,KAAKC,CAAI,CAC1C,CACF,EA5Fad,EAANmB,EAAA,CADNC,EAAM,EAGFC,EAAA,EAAAC,EAAOC,CAAe,IAFdvB","names":["SYSWATCH_OPTIONS","Inject","Injectable","Logger","SysWatch","SysWatchService","SysWatch","options","error","Logger","__decorateClass","Injectable","__decorateParam","Inject","SYSWATCH_OPTIONS","Global","Module","SysWatchModule","options","SYSWATCH_OPTIONS","SysWatchService","optionsFactory","__decorateClass","Global","Module","Injectable","Inject","Logger","throwError","catchError","tap","LoggerInterceptor","sysWatch","context","next","Logger","start","request","method","url","queryParams","userId","requestId","tap","body","statusCode","duration","statusCodeSuccess","statusCodeFailure","statusCodeError","meta","isValidBody","catchError","error","throwError","__decorateClass","Injectable","__decorateParam","Inject","SysWatchService","Catch","HttpException","Inject","Logger","LoggerException","sysWatch","exception","host","Logger","ctx","request","response","method","url","queryParams","userId","requestId","status","body","HttpException","statusCodeFailure","statusCodeError","meta","__decorateClass","Catch","__decorateParam","Inject","SysWatchService"]}
1
+ {"version":3,"sources":["../src/constants.ts","../src/syswatch.service.ts","../src/syswatch.module.ts","../src/interceptors/logger.interceptor.ts","../src/exceptions/logger.exception.ts"],"sourcesContent":["export const SYSWATCH_OPTIONS = 'SYSWATCH_OPTIONS';\n","import { Inject, Injectable, Logger, OnModuleInit } from \"@nestjs/common\";\nimport { SysWatch } from \"@syswatch/core\";\nimport { SYSWATCH_OPTIONS } from \"./constants\";\nimport { SysWatchModuleOptions } from \"./interfaces\";\n\n@Injectable()\nexport class SysWatchService extends SysWatch implements OnModuleInit {\n constructor(@Inject(SYSWATCH_OPTIONS) options: SysWatchModuleOptions) {\n super(options);\n }\n\n async onModuleInit() {\n if (this.validateOnFirstUse) {\n return;\n }\n\n await this.init().catch((error) => {\n Logger.error(error.message, \"SysWatchService\");\n });\n }\n}\n","import { DynamicModule, Global, Module, Provider } from '@nestjs/common';\nimport { SysWatchService } from './syswatch.service';\nimport { SYSWATCH_OPTIONS } from './constants';\nimport { SysWatchModuleAsyncOptions, SysWatchModuleOptions, SysWatchOptionsFactory } from './interfaces';\n\n@Global()\n@Module({})\nexport class SysWatchModule {\n static forRoot(options: SysWatchModuleOptions): DynamicModule {\n return {\n module: SysWatchModule,\n providers: [\n {\n provide: SYSWATCH_OPTIONS,\n useValue: options,\n },\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n static forRootAsync(options: SysWatchModuleAsyncOptions): DynamicModule {\n return {\n module: SysWatchModule,\n imports: options.imports || [],\n providers: [\n ...this.createAsyncProviders(options),\n SysWatchService,\n ],\n exports: [SysWatchService],\n };\n }\n\n private static createAsyncProviders(options: SysWatchModuleAsyncOptions): Provider[] {\n if (options.useExisting || options.useFactory) {\n return [this.createAsyncOptionsProvider(options)];\n }\n return [\n this.createAsyncOptionsProvider(options),\n {\n provide: options.useClass!,\n useClass: options.useClass!,\n },\n ];\n }\n\n private static createAsyncOptionsProvider(options: SysWatchModuleAsyncOptions): Provider {\n if (options.useFactory) {\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject || [],\n };\n }\n return {\n provide: SYSWATCH_OPTIONS,\n useFactory: async (optionsFactory: SysWatchOptionsFactory) =>\n await optionsFactory.createSysWatchOptions(),\n inject: [options.useExisting || options.useClass!],\n };\n }\n}\n","import {\n CallHandler,\n ExecutionContext,\n Injectable,\n NestInterceptor,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { Observable, throwError } from \"rxjs\";\nimport { catchError, tap } from \"rxjs/operators\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class LoggerInterceptor implements NestInterceptor {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n if (!this.sysWatch || !this.sysWatch.log) {\n Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n\n return next.handle();\n }\n\n const start = Date.now();\n\n const request = context.switchToHttp().getRequest<\n Request & {\n user?: {\n id: string | undefined;\n sub: string | undefined;\n _id: string | undefined;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n return next.handle().pipe(\n tap((body) => {\n const response = context.switchToHttp().getResponse<Response>();\n const statusCode = response.statusCode;\n const duration = Date.now() - start;\n const statusCodeSuccess = /^(2|3)/.test(statusCode.toString());\n\n const isValidBody =\n typeof body === \"object\" &&\n body !== null &&\n !Array.isArray(body) &&\n \"message\" in body &&\n typeof body.message === \"string\";\n\n request[\"logged\"] = true;\n\n this.sysWatch.log\n .httpRequest({\n method,\n url,\n statusCode,\n duration,\n queryParams,\n requestId: typeof requestId === \"string\" ? requestId : undefined,\n ...(userId && { userId }),\n ...(isValidBody && { message: body.message }),\n ...(body &&\n !statusCodeSuccess && {\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n }),\n })\n .catch((error) => {\n // tap() não espera nem observa Promises retornadas pelo seu\n // callback — sem este catch, uma rejeição aqui (ex: API key\n // inválida) vira unhandled rejection e derruba o processo\n // inteiro a cada request (Node 15+ trata isso como fatal).\n Logger.warn(\n `Falha ao reportar request ao SysWatch: ${error.message}`,\n );\n });\n }),\n catchError((error) => {\n return throwError(() => error);\n }),\n );\n }\n}\n","import {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n Inject,\n Logger,\n} from \"@nestjs/common\";\nimport { SysWatchService } from \"../syswatch.service\";\nimport { Request, Response } from \"express\";\n\n@Catch()\nexport class LoggerException implements ExceptionFilter {\n constructor(\n @Inject(SysWatchService) private readonly sysWatch: SysWatchService,\n ) {}\n\n async catch(exception: any, host: ArgumentsHost) {\n if (!this.sysWatch || !this.sysWatch.log) {\n return Logger.error(\n \"SysWatchService not injected. LoggerInterceptor will not log requests.\",\n );\n }\n\n const ctx = host.switchToHttp();\n\n const request = ctx.getRequest<\n Request & {\n user?: {\n id?: string;\n sub?: string;\n _id?: string;\n };\n id?: string;\n logged?: boolean;\n }\n >();\n\n const response = ctx.getResponse<Response>();\n\n if (request[\"logged\"]) return;\n\n const method = request.method;\n const url =\n request.route && \"path\" in request.route\n ? request.route.path\n : request.url;\n const queryParams = request.query;\n\n const userId: string | undefined =\n request[\"user\"]?.id || request[\"user\"]?.sub || request[\"user\"]?._id;\n const requestId =\n request?.[\"id\"] ||\n request.headers?.[\"x-request-id\"] ||\n request.headers?.[\"x-correlation-id\"];\n\n const status = exception.getStatus ? exception.getStatus() : 500;\n const body =\n exception instanceof HttpException\n ? exception.getResponse()\n : { message: \"Internal server error\" };\n\n const isGenericError =\n exception instanceof Error && !(exception instanceof HttpException);\n\n const bodyMessage: string | undefined =\n typeof body === \"object\" &&\n body !== null &&\n !Array.isArray(body) &&\n typeof (body as { message?: unknown }).message === \"string\"\n ? (body as { message: string }).message\n : undefined;\n\n // .catch aqui é essencial: `catch()` do ExceptionFilter não espera essa\n // chamada (não tem await), então uma rejeição (ex: API key inválida)\n // viraria unhandled rejection e derrubaria o processo a cada exceção.\n this.sysWatch.log\n .httpRequest({\n method,\n url,\n statusCode: status,\n queryParams,\n requestId: typeof requestId === \"string\" ? requestId : undefined,\n ...(userId && { userId }),\n message:\n bodyMessage ??\n (isGenericError && exception.message\n ? exception.message\n : undefined),\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n ...(isGenericError && { error: exception.message }),\n })\n .catch((error) => {\n Logger.warn(`Falha ao reportar exceção ao SysWatch: ${error.message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CAAC,MAAM,QAAQA,CAAI,GACnB,OAAQA,EAA+B,SAAY,SAC9CA,EAA6B,QAC9B,OAKN,YAAK,SAAS,IACX,YAAY,CACX,OAAAN,EACA,IAAAC,EACA,WAAYI,EACZ,YAAAH,EACA,UAAW,OAAOE,GAAc,SAAWA,EAAY,OACvD,GAAID,GAAU,CAAE,OAAAA,CAAO,EACvB,QACEM,IACCD,GAAkBd,EAAU,QACzBA,EAAU,QACV,QACN,SAAU,OAAOY,GAAS,SAAWA,EAAK,MAAM,EAAG,GAAG,EAAIA,EAC1D,GAAIE,GAAkB,CAAE,MAAOd,EAAU,OAAQ,CACnD,CAAC,EACA,MAAOgB,GAAU,CAChBd,EAAO,KAAK,gDAA0Cc,EAAM,OAAO,EAAE,CACvE,CAAC,EAEIX,EAAS,OAAOM,CAAM,EAAE,KAAKC,CAAI,CAC1C,CACF,EAtFad,EAANmB,EAAA,CADNC,EAAM,EAGFC,EAAA,EAAAC,EAAOC,CAAe,IAFdvB","names":["SYSWATCH_OPTIONS","Inject","Injectable","Logger","SysWatch","SysWatchService","SysWatch","options","error","Logger","__decorateClass","Injectable","__decorateParam","Inject","SYSWATCH_OPTIONS","Global","Module","SysWatchModule","options","SYSWATCH_OPTIONS","SysWatchService","optionsFactory","__decorateClass","Global","Module","Injectable","Inject","Logger","throwError","catchError","tap","LoggerInterceptor","sysWatch","context","next","Logger","start","request","method","url","queryParams","userId","requestId","tap","body","statusCode","duration","statusCodeSuccess","isValidBody","error","catchError","throwError","__decorateClass","Injectable","__decorateParam","Inject","SysWatchService","Catch","HttpException","Inject","Logger","LoggerException","sysWatch","exception","host","Logger","ctx","request","response","method","url","queryParams","userId","requestId","status","body","HttpException","isGenericError","bodyMessage","error","__decorateClass","Catch","__decorateParam","Inject","SysWatchService"]}
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@syswatch/nestjs",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "NestJS module for SysWatch SDK",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/MINIFAK/sys-watch-sdk.git",
8
+ "directory": "packages/nestjs"
9
+ },
5
10
  "main": "dist/index.js",
6
11
  "module": "dist/index.mjs",
7
12
  "types": "dist/index.d.ts",
@@ -23,7 +28,7 @@
23
28
  "test": "jest"
24
29
  },
25
30
  "dependencies": {
26
- "@syswatch/core": "^1.1.0"
31
+ "@syswatch/core": "^1.3.0"
27
32
  },
28
33
  "peerDependencies": {
29
34
  "@nestjs/common": ">=8.0.0",