@syswatch/nestjs 1.0.1 → 1.0.3

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,p=r.length-1,l;p>=0;p--)(l=r[p])&&(s=(i?l(t,e,s):l(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:()=>n});module.exports=D(Y);var g="SYSWATCH_OPTIONS";var f=require("@nestjs/common"),_=require("@syswatch/core");var n=class extends _.SysWatch{constructor(t){super(t)}async onModuleInit(){await this.init().catch(t=>{f.Logger.error(t.message,"SysWatchService")})}};n=d([(0,f.Injectable)(),y(0,(0,f.Inject)(g))],n);var x=require("@nestjs/common");var m=class{static forRoot(t){return{module:m,providers:[{provide:g,useValue:t},n],exports:[n]}}static forRootAsync(t){return{module:m,imports:t.imports||[],providers:[...this.createAsyncProviders(t),n],exports:[n]}}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"),F=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(),p=s.method,l=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 a=t.switchToHttp().getResponse().statusCode,j=Date.now()-i,q=a.toString().startsWith("2"),C=a.toString().startsWith("4"),T=a.toString().startsWith("5"),A={...h&&{requestId:h},method:p,statusCode:a,url:l,queryParams:P,duration:j,...o&&!q&&{response:typeof o=="string"?o.slice(0,500):o}},w=typeof o=="object"&&!Array.isArray(o)&&"message"in o&&typeof o.message=="string";if(q)return this.sysWatch.log.success("http_request",{...c&&{userId:c},meta:A});C&&this.sysWatch.log.failure("http_request",{...w?{message:o.message}:{},...c&&{userId:c},meta:A}),T&&this.sysWatch.log.error("http_request",{...w?{message:o.message}:{},...c&&{userId:c},meta:A}),this.sysWatch.log.debug("http_request",{...c&&{userId:c},meta:A}),s.logged=!0}),(0,R.catchError)(o=>(0,F.throwError)(()=>o)))}};v=d([(0,S.Injectable)(),y(0,(0,S.Inject)(n))],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(),p=i.getResponse();if(s.logged)return;let l=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,a=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:l,statusCode:W,url:P,queryParams:c,body:typeof a=="string"?a.slice(0,500):a,...t&&t instanceof Error&&!(t instanceof u.HttpException)?{error:t.message}:{}};return j&&await this.sysWatch.log.failure("http_request",{...typeof a=="object"&&!Array.isArray(a)&&"message"in a&&typeof a.message=="string"?{message:a.message}:{},...h&&{userId:h},meta:C}),q&&await this.sysWatch.log.error("http_request",{...t&&t instanceof Error&&t.message?{message:t.message}:{},...h&&{userId:h},meta:C}),p.status(W).json(a)}};O=d([(0,u.Catch)(),y(0,(0,u.Inject)(n))],O);0&&(module.exports={LoggerException,LoggerInterceptor,SYSWATCH_OPTIONS,SysWatchModule,SysWatchService});
1
+ "use strict";var q=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var F=(r,e)=>{for(var s in e)q(r,s,{get:e[s],enumerable:!0})},b=(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=P(e,t))||n.enumerable});return r};var E=r=>b(q({},"__esModule",{value:!0}),r),u=(r,e,s,n)=>{for(var t=n>1?void 0:n?P(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 N={};F(N,{LoggerException:()=>v,LoggerInterceptor:()=>S,SYSWATCH_OPTIONS:()=>l,SysWatchModule:()=>d,SysWatchService:()=>i});module.exports=E(N);var l="SYSWATCH_OPTIONS";var y=require("@nestjs/common"),j=require("@syswatch/core");var i=class extends j.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"),H=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()),w=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},...w&&{message:o.message},...o&&!R&&{response:typeof o=="string"?o.slice(0,500):o}})}),(0,I.catchError)(o=>(0,H.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}}),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 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 if (statusCodeSuccess) {\n return this.sysWatch.log.success(\"http_request\", {\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeFailure) {\n this.sysWatch.log.failure(\"http_request\", {\n ...(isValidBody ? { message: body.message } : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeError) {\n 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 request[\"logged\"] = true;\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 await 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 await 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,CACnB,MAAM,KAAK,KAAK,EAAE,MAAOC,GAAU,CACjC,SAAO,MAAMA,EAAM,QAAS,iBAAiB,CAC/C,CAAC,CACH,CACF,EAVaF,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,EAEK,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AFdnB","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.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 }),\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 this.sysWatch.log.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 ? exception.message : undefined),\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n ...(isGenericError && { error: exception.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,IAAA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E,EAAUD,EAAI,WAUlB,EAEIE,EAAWF,EAAI,YAAsB,EAE3C,GAAIC,EAAQ,OAAW,OAEvB,IAAME,EAASF,EAAQ,OACjBG,EACJH,EAAQ,OAAS,SAAUA,EAAQ,MAC/BA,EAAQ,MAAM,KACdA,EAAQ,IACRI,EAAcJ,EAAQ,MAEtBK,EACJL,EAAQ,MAAS,IAAMA,EAAQ,MAAS,KAAOA,EAAQ,MAAS,IAC5DM,EACJN,GAAU,IACVA,EAAQ,UAAU,cAAc,GAChCA,EAAQ,UAAU,kBAAkB,EAEhCO,EAASV,EAAU,UAAYA,EAAU,UAAU,EAAI,IACvDW,EACJX,aAAqB,gBACjBA,EAAU,YAAY,EACtB,CAAE,QAAS,uBAAwB,EAEnCY,EACJZ,aAAqB,OAAS,EAAEA,aAAqB,iBAEjDa,EACJ,OAAOF,GAAS,UAChBA,IAAS,MACT,CAAC,MAAM,QAAQA,CAAI,GACnB,OAAQA,EAA+B,SAAY,SAC9CA,EAA6B,QAC9B,OAEN,YAAK,SAAS,IAAI,YAAY,CAC5B,OAAAN,EACA,IAAAC,EACA,WAAYI,EACZ,YAAAH,EACA,UAAW,OAAOE,GAAc,SAAWA,EAAY,OACvD,GAAID,GAAU,CAAE,OAAAA,CAAO,EACvB,QACEK,IACCD,GAAkBZ,EAAU,QAAUA,EAAU,QAAU,QAC7D,SAAU,OAAOW,GAAS,SAAWA,EAAK,MAAM,EAAG,GAAG,EAAIA,EAC1D,GAAIC,GAAkB,CAAE,MAAOZ,EAAU,OAAQ,CACnD,CAAC,EAEMI,EAAS,OAAOM,CAAM,EAAE,KAAKC,CAAI,CAC1C,CACF,EA7Eab,EAANgB,EAAA,IADN,SAAM,EAGFC,EAAA,eAAOC,CAAe,IAFdlB","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","__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,a)=>{for(var s=a>1?void 0:a?P(t,i):t,d=u.length-1,m;d>=0;d--)(m=u[d])&&(s=(a?m(t,i,s):m(s))||s);return a&&s&&R(t,i,s),s},h=(u,t)=>(i,a)=>t(i,a,u);var g="SYSWATCH_OPTIONS";import{Inject as j,Injectable as w,Logger as H}from"@nestjs/common";import{SysWatch as _}from"@syswatch/core";var o=class extends _{constructor(t){super(t)}async onModuleInit(){await this.init().catch(t=>{H.error(t.message,"SysWatchService")})}};o=c([w(),h(0,j(g))],o);import{Global as F,Module as T}from"@nestjs/common";var l=class{static forRoot(t){return{module:l,providers:[{provide:g,useValue:t},o],exports:[o]}}static forRootAsync(t){return{module:l,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]}}};l=c([F(),T({})],l);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 a=Date.now(),s=t.switchToHttp().getRequest(),d=s.method,m=s.route&&"path"in s.route?s.route.path:s.url,q=s.query,n=s.user?.id||s.user?.sub||s.user?._id,p=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()-a,f=r.toString().startsWith("2"),S=r.toString().startsWith("4"),x=r.toString().startsWith("5"),W={...p&&{requestId:p},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(f)return this.sysWatch.log.success("http_request",{...n&&{userId:n},meta:W});S&&this.sysWatch.log.failure("http_request",{...A?{message:e.message}:{},...n&&{userId:n},meta:W}),x&&this.sysWatch.log.error("http_request",{...A?{message:e.message}:{},...n&&{userId:n},meta:W}),this.sysWatch.log.debug("http_request",{...n&&{userId:n},meta:W}),s.logged=!0}),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 a=i.switchToHttp(),s=a.getRequest(),d=a.getResponse();if(s.logged)return;let m=s.method,q=s.route&&"path"in s.route?s.route.path:s.url,n=s.query,p=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:n,body:typeof r=="string"?r.slice(0,500):r,...t&&t instanceof Error&&!(t instanceof I)?{error:t.message}:{}};return C&&await this.sysWatch.log.failure("http_request",{...typeof r=="object"&&!Array.isArray(r)&&"message"in r&&typeof r.message=="string"?{message:r.message}:{},...p&&{userId:p},meta:S}),f&&await this.sysWatch.log.error("http_request",{...t&&t instanceof Error&&t.message?{message:t.message}:{},...p&&{userId:p},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,l as SysWatchModule,o as SysWatchService};
1
+ var I=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var a=(c,e,o,i)=>{for(var t=i>1?void 0:i?x(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&&I(e,o,t),t},m=(c,e)=>(o,i)=>e(o,i,c);var l="SYSWATCH_OPTIONS";import{Inject as C,Injectable as R,Logger as P}from"@nestjs/common";import{SysWatch as j}from"@syswatch/core";var r=class extends j{constructor(e){super(e)}async onModuleInit(){this.validateOnFirstUse||await this.init().catch(e=>{P.error(e.message,"SysWatchService")})}};r=a([R(),m(0,C(l))],r);import{Global as H,Module as w}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([H(),w({})],p);import{Injectable as M,Inject as T,Logger as F}from"@nestjs/common";import{throwError as b}from"rxjs";import{catchError as E,tap as N}from"rxjs/operators";var f=class{constructor(e){this.sysWatch=e}intercept(e,o){if(!this.sysWatch||!this.sysWatch.log)return F.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,y=t.user?.id||t.user?.sub||t.user?._id,g=t?.id||t.headers?.["x-request-id"]||t.headers?.["x-correlation-id"];return o.handle().pipe(N(s=>{let n=e.switchToHttp().getResponse().statusCode,h=Date.now()-i,W=/^(2|3)/.test(n.toString()),A=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:h,queryParams:v,requestId:typeof g=="string"?g:void 0,...y&&{userId:y},...A&&{message:s.message},...s&&!W&&{response:typeof s=="string"?s.slice(0,500):s}})}),E(s=>b(()=>s)))}};f=a([M(),m(0,T(r))],f);import{Catch as _,HttpException as q,Inject as D,Logger as Y}from"@nestjs/common";var S=class{constructor(e){this.sysWatch=e}async catch(e,o){if(!this.sysWatch||!this.sysWatch.log)return Y.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,y=t.query,g=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 q?e.getResponse():{message:"Internal server error"},h=e instanceof Error&&!(e instanceof q),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:y,requestId:typeof s=="string"?s:void 0,...g&&{userId:g},message:W??(h&&e.message?e.message:void 0),response:typeof n=="string"?n.slice(0,500):n,...h&&{error:e.message}}),u.status(O).json(n)}};S=a([_(),m(0,D(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 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 if (statusCodeSuccess) {\n return this.sysWatch.log.success(\"http_request\", {\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeFailure) {\n this.sysWatch.log.failure(\"http_request\", {\n ...(isValidBody ? { message: body.message } : {}),\n ...(userId && { userId }),\n meta,\n });\n }\n\n if (statusCodeError) {\n 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 request[\"logged\"] = true;\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 await 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 await 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,CACnB,MAAM,KAAK,KAAK,EAAE,MAAOC,GAAU,CACjCC,EAAO,MAAMD,EAAM,QAAS,iBAAiB,CAC/C,CAAC,CACH,CACF,EAVaH,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,C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Q,EAC3B,CAAC,CACP,EAEA,OAAIc,GACF,MAAM,KAAK,SAAS,IAAI,QAAQ,eAAgB,CAC9C,GAAI,OAAOF,GAAS,UACpB,CAAC,MAAM,QAAQA,CAAI,GACnB,YAAaA,GACb,OAAOA,EAAK,SAAY,SACpB,CAAE,QAASA,EAAK,OAAQ,EACxB,CAAC,EACL,GAAIH,GAAU,CAAE,OAAAA,CAAO,EACvB,KAAAO,CACF,CAAC,EAGCD,GACF,MAAM,KAAK,SAAS,IAAI,MAAM,eAAgB,CAC5C,GAAIf,GAAaA,aAAqB,OAASA,EAAU,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.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 }),\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 this.sysWatch.log.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 ? exception.message : undefined),\n response: typeof body === \"string\" ? body.slice(0, 500) : body,\n ...(isGenericError && { error: exception.message }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AEN,YAAK,SAAS,IAAI,YAAY,CAC5B,OAAAN,EACA,IAAAC,EACA,WAAYI,EACZ,YAAAH,EACA,UAAW,OAAOE,GAAc,SAAWA,EAAY,OACvD,GAAID,GAAU,CAAE,OAAAA,CAAO,EACvB,QACEM,IACCD,GAAkBd,EAAU,QAAUA,EAAU,QAAU,QAC7D,SAAU,OAAOY,GAAS,SAAWA,EAAK,MAAM,EAAG,GAAG,EAAIA,EAC1D,GAAIE,GAAkB,CAAE,MAAOd,EAAU,OAAQ,CACnD,CAAC,EAEMK,EAAS,OAAOM,CAAM,EAAE,KAAKC,CAAI,CAC1C,CACF,EA7Ead,EAANkB,EAAA,CADNC,EAAM,EAGFC,EAAA,EAAAC,EAAOC,CAAe,IAFdtB","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","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","isGenericError","bodyMessage","__decorateClass","Catch","__decorateParam","Inject","SysWatchService"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syswatch/nestjs",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "NestJS module for SysWatch SDK",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -19,22 +19,28 @@
19
19
  "access": "public"
20
20
  },
21
21
  "scripts": {
22
- "build": "tsup"
22
+ "build": "tsup",
23
+ "test": "jest"
24
+ },
25
+ "dependencies": {
26
+ "@syswatch/core": "^1.2.0"
23
27
  },
24
28
  "peerDependencies": {
25
29
  "@nestjs/common": ">=8.0.0",
26
30
  "@nestjs/core": ">=8.0.0",
27
- "@syswatch/core": "^1.x",
28
31
  "rxjs": "^7.0.0"
29
32
  },
30
33
  "devDependencies": {
31
34
  "@nestjs/common": "^10.0.0",
32
35
  "@nestjs/core": "^10.0.0",
33
36
  "@nestjs/platform-express": "^10.0.0",
34
- "@syswatch/core": "^1.0.5",
37
+ "@types/express": "^5.0.6",
38
+ "@types/jest": "^30.0.0",
35
39
  "@types/node": "^20.0.0",
40
+ "jest": "^30.2.0",
36
41
  "reflect-metadata": "^0.2.0",
37
42
  "rxjs": "^7.8.1",
43
+ "ts-jest": "^29.4.6",
38
44
  "tsup": "^8.5.1",
39
45
  "typescript": "^5.0.0"
40
46
  }