@viplance/nestjs-logger 0.1.2 → 0.1.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/README.md CHANGED
@@ -1,34 +1,39 @@
1
1
  ## @viplance/nestjs-logger
2
2
  # NestJS internal logging system
3
3
 
4
- 1. Install the package npm i @viplance/nestjs-logger
5
- 2. Import the module in app.module.ts
6
- import { LogModule } from '@viplance/nestjs-logger';
7
-
8
- @Module({
9
- imports: [
10
- ...,
11
- LogModule,
12
- ]
13
- })
14
- 3. Use the LogService in case of custom logs.
15
- 3. If you want to catch all errors automatically, put the code in main.ts
16
- import { LogModule } from '@viplance/nestjs-logger';
17
-
18
- await LogModule.connect(app, {
19
- path: '/logs',
20
- database: {
21
- type: 'mongodb',
22
- host: 'localhost',
23
- port: 27017,
24
- collection: 'logs'
25
- }
26
- });
27
-
28
- `path` and `database` options are optional
29
- The logs could be available at your_application_url/<path>
30
- By default the logs will be stored in memory and deleted when the application stops.
31
-
4
+ 1. Install the package npm i @viplance/nestjs-logger<br />
5
+ 2. Import the module in app.module.ts<br />
6
+ &ensp;import { LogModule } from '@viplance/nestjs-logger';<br />
7
+ <br />
8
+ &ensp;@Module({<br />
9
+ &ensp;&ensp;imports: [<br />
10
+ &ensp;&ensp;&ensp;...,<br />
11
+ &ensp;&ensp;&ensp;LogModule,<br />
12
+ &ensp;&ensp;]<br />
13
+ &ensp;})<br />
14
+ &ensp;import { LogModule } from '@viplance/nestjs-logger';<br />
15
+ <br />
16
+ &ensp;// use the memory to store logs
17
+ &ensp;await LogModule.connect(app, {<br />
18
+ &ensp;&ensp;path: '/logs',<br />
19
+ &ensp;&ensp;});<br /><br />
20
+ &ensp;// use the database to store logs
21
+ &ensp;await LogModule.connect(app, {<br />
22
+ &ensp;&ensp;path: '/logs',<br />
23
+ &ensp;&ensp;&ensp;database: {<br />
24
+ &ensp;&ensp;&ensp;&ensp;type: 'mongodb',<br />
25
+ &ensp;&ensp;&ensp;&ensp;host: 'localhost',<br />
26
+ &ensp;&ensp;&ensp;&ensp;port: 27017,<br />
27
+ &ensp;&ensp;&ensp;&ensp;collection: 'logs'<br />
28
+ &ensp;&ensp;&ensp;}<br />
29
+ &ensp;&ensp;});<br />
30
+ 3. Use the LogService in case of custom logs to debug the application.
31
+ <br />
32
+ <br />
33
+ `path` and `database` options are optional<br />
34
+ The logs could be available at your_application_url/<path><br />
35
+ By default the logs will be stored in memory and deleted when the application stops.<br />
36
+ <br />
32
37
  Available service methods:
33
38
  - log()
34
39
  - error()
@@ -3,4 +3,7 @@ export declare function createLogEntity(name: string): EntitySchema<{
3
3
  _id: unknown;
4
4
  type: unknown;
5
5
  message: unknown;
6
+ count: unknown;
7
+ createdAt: unknown;
8
+ updatedAt: unknown;
6
9
  }>;
@@ -13,6 +13,9 @@ function createLogEntity(name) {
13
13
  },
14
14
  type: { type: String },
15
15
  message: { type: String },
16
+ count: { type: Number, default: 1 },
17
+ createdAt: { type: Date },
18
+ updatedAt: { type: Date },
16
19
  },
17
20
  });
18
21
  }
@@ -1 +1 @@
1
- {"version":3,"file":"log.entity.js","sourceRoot":"","sources":["../../src/entities/log.entity.ts"],"names":[],"mappings":";;AAEA,0CAaC;AAfD,qCAAuC;AAEvC,SAAgB,eAAe,CAAC,IAAY;IAC1C,OAAO,IAAI,sBAAY,CAAC;QACtB,IAAI;QACJ,OAAO,EAAE;YACP,GAAG,EAAE;gBACH,IAAI,EAAE,MAAM;gBACZ,QAAQ,EAAE,IAAI;gBACd,OAAO,EAAE,IAAI;aACd;YACD,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;YACtB,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;SAC1B;KACF,CAAC,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"log.entity.js","sourceRoot":"","sources":["../../src/entities/log.entity.ts"],"names":[],"mappings":";;AAEA,0CAgBC;AAlBD,qCAAuC;AAEvC,SAAgB,eAAe,CAAC,IAAY;IAC1C,OAAO,IAAI,sBAAY,CAAC;QACtB,IAAI;QACJ,OAAO,EAAE;YACP,GAAG,EAAE;gBACH,IAAI,EAAE,MAAM;gBACZ,QAAQ,EAAE,IAAI;gBACd,OAAO,EAAE,IAAI;aACd;YACD,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;YACtB,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;YACzB,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE;YACnC,SAAS,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;YACzB,SAAS,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;SAC1B;KACF,CAAC,CAAC;AACL,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./log.interceptor";
2
2
  export * from "./log.module";
3
+ export * from "./types/index";
3
4
  export * from "./services/log.service";
package/dist/index.js CHANGED
@@ -16,5 +16,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./log.interceptor"), exports);
18
18
  __exportStar(require("./log.module"), exports);
19
+ __exportStar(require("./types/index"), exports);
19
20
  __exportStar(require("./services/log.service"), exports);
20
21
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,+CAA6B;AAC7B,yDAAuC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,+CAA6B;AAC7B,gDAA8B;AAC9B,yDAAuC"}
@@ -20,7 +20,7 @@ let LogModule = class LogModule {
20
20
  if (options === null || options === void 0 ? void 0 : options.path) {
21
21
  const httpAdapter = app.getHttpAdapter();
22
22
  httpAdapter.get(options.path, async (req, res) => {
23
- res.json(logService.getAll());
23
+ res.json(await logService.getAll());
24
24
  });
25
25
  }
26
26
  if (options) {
@@ -1 +1 @@
1
- {"version":3,"file":"log.module.js","sourceRoot":"","sources":["../src/log.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAgD;AAChD,wDAAoD;AACpD,oEAA+D;AAC/D,uDAAmD;AAEnD,6CAAgD;AAQzC,IAAM,SAAS,GAAf,MAAM,SAAS;IACb,MAAM,CAAC,KAAK,CAAC,OAAO,CACzB,GAAQ,EACR,OAA0B;QAE1B,GAAG,CAAC,OAAO,CAAC,wBAAU,CAAC,CAAC;QAExB,MAAM,UAAU,GAAe,MAAM,GAAG,CAAC,OAAO,CAAC,wBAAU,CAAC,CAAC;QAE7D,GAAG,CAAC,qBAAqB,CAAC,IAAI,gCAAc,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,uBAAuB;QAElF,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,EAAE,CAAC;YAClB,MAAM,WAAW,GAAG,GAAG,CAAC,cAAc,EAAE,CAAC;YACzC,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAQ,EAAE,GAAQ,EAAE,EAAE;gBACzD,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC;QAED,IAAI,OAAO,EAAE,CAAC;YACZ,MAAM,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;CACF,CAAA;AAtBY,8BAAS;oBAAT,SAAS;IANrB,IAAA,eAAM,GAAE;IACR,IAAA,eAAM,EAAC;QACN,OAAO,EAAE,CAAC,uBAAa,CAAC;QACxB,SAAS,EAAE,CAAC,wBAAU,EAAE,mCAAe,CAAC;QACxC,OAAO,EAAE,CAAC,uBAAa,EAAE,wBAAU,EAAE,mCAAe,CAAC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} from "./memory-db.service";
3
3
  import { LogModuleOptions } from "../types";
4
4
  import { DataSource, EntitySchema } from "typeorm";
5
5
  export declare class LogService implements LoggerService {
6
- private readonly MemoryDbService;
6
+ private readonly memoryDbService;
7
7
  static connection: DataSource;
8
8
  static Log: EntitySchema;
9
- constructor(MemoryDbService: MemoryDbService);
9
+ constructor(memoryDbService: MemoryDbService);
10
10
  connectDb(options: LogModuleOptions): Promise<DataSource>;
11
11
  log(message: string, context?: string): void;
12
12
  error(message: string, trace?: string, context?: ExecutionContext): void;
13
13
  warn(message: string, context?: string): void;
14
14
  debug(message: string, context?: string): void;
15
15
  verbose(message: string, context?: string): void;
16
- getAll(): any[];
16
+ getAll(): Promise<any[]>;
17
17
  private smartInsert;
18
+ private getConnection;
18
19
  }
@@ -18,14 +18,12 @@ const types_1 = require("../types");
18
18
  const typeorm_1 = require("typeorm");
19
19
  const log_entity_1 = require("../entities/log.entity");
20
20
  let LogService = LogService_1 = class LogService {
21
- constructor(MemoryDbService // @InjectRepository(Log) // private readonly userRepository: Repository<Log>
22
- ) {
23
- this.MemoryDbService = MemoryDbService;
21
+ constructor(memoryDbService) {
22
+ this.memoryDbService = memoryDbService;
24
23
  }
25
24
  async connectDb(options) {
26
25
  var _a, _b, _c, _d, _e, _f;
27
- const tableName = ((_a = options.database) === null || _a === void 0 ? void 0 : _a.collection) || ((_b = options.database) === null || _b === void 0 ? void 0 : _b.table) || "logs";
28
- LogService_1.Log = (0, log_entity_1.createLogEntity)(tableName);
26
+ LogService_1.Log = (0, log_entity_1.createLogEntity)(((_a = options.database) === null || _a === void 0 ? void 0 : _a.collection) || ((_b = options.database) === null || _b === void 0 ? void 0 : _b.table) || defaults_1.defaultTable);
29
27
  const dataSourceOptions = {
30
28
  type: (_c = options.database) === null || _c === void 0 ? void 0 : _c.type,
31
29
  database: (_d = options.database) === null || _d === void 0 ? void 0 : _d.database,
@@ -38,14 +36,14 @@ let LogService = LogService_1 = class LogService {
38
36
  return LogService_1.connection;
39
37
  }
40
38
  log(message, context) {
41
- this.smartInsert(defaults_1.defaultTable, {
39
+ this.smartInsert({
42
40
  type: types_1.LogType.LOG,
43
41
  message,
44
42
  context,
45
43
  });
46
44
  }
47
45
  error(message, trace, context) {
48
- this.smartInsert(defaults_1.defaultTable, {
46
+ this.smartInsert({
49
47
  type: types_1.LogType.ERROR,
50
48
  message,
51
49
  trace,
@@ -53,47 +51,61 @@ let LogService = LogService_1 = class LogService {
53
51
  });
54
52
  }
55
53
  warn(message, context) {
56
- this.smartInsert(defaults_1.defaultTable, {
54
+ this.smartInsert({
57
55
  type: types_1.LogType.WARN,
58
56
  message,
59
57
  context,
60
58
  });
61
59
  }
62
60
  debug(message, context) {
63
- this.smartInsert(defaults_1.defaultTable, {
61
+ this.smartInsert({
64
62
  type: types_1.LogType.DEBUG,
65
63
  message,
66
64
  context,
67
65
  });
68
66
  }
69
67
  verbose(message, context) {
70
- this.smartInsert(defaults_1.defaultTable, {
68
+ this.smartInsert({
71
69
  type: types_1.LogType.VERBOSE,
72
70
  message,
73
71
  context,
74
72
  });
75
73
  }
76
- getAll() {
77
- return this.MemoryDbService.getMany(defaults_1.defaultTable);
74
+ async getAll() {
75
+ return this.getConnection().find(LogService_1.Log);
78
76
  }
79
- async smartInsert(table, data) {
80
- return await LogService_1.connection.manager.insert(LogService_1.Log, {
77
+ async smartInsert(data) {
78
+ const currentDate = new Date();
79
+ const connection = this.getConnection();
80
+ // find the same log in DB
81
+ const log = await connection.findOne(LogService_1.Log, {
82
+ where: {
83
+ type: data.type,
84
+ message: data.message,
85
+ },
86
+ });
87
+ if (log) {
88
+ return await connection.update(LogService_1.Log, log._id, {
89
+ count: log.count + 1,
90
+ updatedAt: currentDate,
91
+ });
92
+ }
93
+ return await connection.insert(LogService_1.Log, {
81
94
  type: data.type,
82
95
  message: data.message,
83
96
  count: 1,
97
+ createdAt: currentDate,
98
+ updatedAt: currentDate,
84
99
  });
85
- // return this.MemoryDbService.insert(table, {
86
- // ...data,
87
- // count: 1,
88
- // createdAt: new Date(),
89
- // updatedAt: new Date(),
90
- // });
100
+ }
101
+ getConnection() {
102
+ return LogService_1.connection.manager || this.memoryDbService;
91
103
  }
92
104
  };
93
105
  exports.LogService = LogService;
106
+ LogService.Log = (0, log_entity_1.createLogEntity)(defaults_1.defaultTable);
94
107
  exports.LogService = LogService = LogService_1 = __decorate([
95
108
  (0, common_1.Injectable)({ scope: common_1.Scope.TRANSIENT }),
96
- __metadata("design:paramtypes", [memory_db_service_1.MemoryDbService // @InjectRepository(Log) // private readonly userRepository: Repository<Log>
97
- ])
109
+ __metadata("design:paramtypes", [memory_db_service_1.MemoryDbService])
98
110
  ], LogService);
99
111
  //# sourceMappingURL=log.service.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"log.service.js","sourceRoot":"","sources":["../../src/services/log.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,2CAKwB;AACxB,2DAAsD;AACtD,0CAA2C;AAC3C,oCAAqD;AACrD,qCAAsE;AACtE,uDAAyD;AAGlD,IAAM,UAAU,kBAAhB,MAAM,UAAU;IAIrB,YACmB,eAAgC,CAAC,6EAA6E;;QAA9G,oBAAe,GAAf,eAAe,CAAiB;IAChD,CAAC;IAEJ,KAAK,CAAC,SAAS,CAAC,OAAyB;;QACvC,MAAM,SAAS,GACb,CAAA,MAAA,OAAO,CAAC,QAAQ,0CAAE,UAAU,MAAI,MAAA,OAAO,CAAC,QAAQ,0CAAE,KAAK,CAAA,IAAI,MAAM,CAAC;QAEpE,YAAU,CAAC,GAAG,GAAG,IAAA,4BAAe,EAAC,SAAS,CAAC,CAAC;QAE5C,MAAM,iBAAiB,GAAG;YACxB,IAAI,EAAE,MAAA,OAAO,CAAC,QAAQ,0CAAE,IAAI;YAC5B,QAAQ,EAAE,MAAA,OAAO,CAAC,QAAQ,0CAAE,QAAQ;YACpC,IAAI,EAAE,MAAA,OAAO,CAAC,QAAQ,0CAAE,IAAI;YAC5B,IAAI,EAAE,MAAA,OAAO,CAAC,Q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UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAExC,0BAA0B;QAC1B,MAAM,GAAG,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,YAAU,CAAC,GAAG,EAAE;YACnD,KAAK,EAAE;gBACL,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,OAAO,EAAE,IAAI,CAAC,OAAO;aACtB;SACF,CAAC,CAAC;QAEH,IAAI,GAAG,EAAE,CAAC;YACR,OAAO,MAAM,UAAU,CAAC,MAAM,CAAC,YAAU,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE;gBACtD,KAAK,EAAE,GAAG,CAAC,KAAK,GAAG,CAAC;gBACpB,SAAS,EAAE,WAAW;aACvB,CAAC,CAAC;QACL,CAAC;QAED,OAAO,MAAM,UAAU,CAAC,MAAM,CAAC,YAAU,CAAC,GAAG,EAAE;YAC7C,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,KAAK,EAAE,CAAC;YACR,SAAS,EAAE,WAAW;YACtB,SAAS,EAAE,WAAW;SACvB,CAAC,CAAC;IACL,CAAC;IAEO,aAAa;QACnB,OAAO,YAAU,CAAC,UAAU,CAAC,OAAO,IAAI,IAAI,CAAC,eAAe,CAAC;IAC/D,CAAC;;AAtGU,gCAAU;AAEd,cAAG,GAAiB,IAAA,4BAAe,EAAC,uBAAY,CAAC,AAA9C,CAA+C;qBAF9C,UAAU;IADtB,IAAA,mBAAU,EAAC,EAAE,KAAK,EAAE,cAAK,CAAC,SAAS,EAAE,CAAC;qCAKS,mCAAe;GAJlD,UAAU,CAuGtB"}
@@ -1,9 +1,16 @@
1
+ import { EntitySchema } from "typeorm";
1
2
  export declare class MemoryDbService {
2
3
  private db;
3
4
  constructor();
4
- insert(table: string, data: any): string;
5
- update(table: string, condition: any, data: any): string;
6
- getMany(table: string): any[];
7
- getOneById(table: string, id: string): any;
8
- getManyByProperty(table: string, field: string, value: string): any[];
5
+ insert(entity: EntitySchema, data: any): string;
6
+ update(entity: EntitySchema, condition: any, data: any): Promise<string>;
7
+ find(entity: EntitySchema): Promise<any[]>;
8
+ getOneById(entity: EntitySchema, _id: string): Promise<any>;
9
+ findByProperty(entity: EntitySchema, field: string, value: string): any[];
10
+ findOne(entity: EntitySchema, condition: {
11
+ where: any;
12
+ }): Promise<any>;
13
+ private findIndex;
14
+ private partialEqual;
15
+ private getTableName;
9
16
  }
@@ -18,42 +18,89 @@ const tables = [defaults_1.defaultTable];
18
18
  let MemoryDbService = class MemoryDbService {
19
19
  constructor() {
20
20
  this.db = {};
21
+ this.getTableName = (entity) => entity.options.name;
21
22
  for (const table of tables) {
22
23
  this.db[table] = [];
23
24
  }
24
25
  }
25
- insert(table, data) {
26
- // generate new random ID
27
- const randomData = (0, crypto_1.randomBytes)(32).toString("hex");
28
- const id = (0, crypto_1.createHash)("sha256").update(randomData).digest("hex");
26
+ insert(entity, data) {
27
+ const table = this.getTableName(entity);
28
+ // generate new random _id
29
+ const randomData = (0, crypto_1.randomBytes)(24).toString("hex");
30
+ const _id = (0, crypto_1.createHash)("sha256").update(randomData).digest("hex");
29
31
  this.db[table].push({
30
32
  ...data,
31
- id, // creader unique index
33
+ _id, // unique index
32
34
  });
33
- return id;
35
+ return _id;
34
36
  }
35
- update(table, condition, data) {
36
- // generate new random ID
37
- const randomData = (0, crypto_1.randomBytes)(32).toString("hex");
38
- const id = (0, crypto_1.createHash)("sha256").update(randomData).digest("hex");
39
- this.db[table].push({
40
- ...data,
41
- id, // creader unique index
42
- });
43
- return id;
37
+ async update(entity, condition, data) {
38
+ const table = this.getTableName(entity);
39
+ let index = null;
40
+ if (typeof condition === "string") {
41
+ index = this.findIndex(entity, { where: { _id: condition } });
42
+ }
43
+ if (condition === null || condition === void 0 ? void 0 : condition.where) {
44
+ index = this.findIndex(entity, condition);
45
+ }
46
+ if (index !== null) {
47
+ this.db[table][index] = {
48
+ ...this.db[table][index],
49
+ ...data,
50
+ };
51
+ return Promise.resolve(this.db[table][index]._id);
52
+ }
53
+ return Promise.reject();
44
54
  }
45
- getMany(table) {
46
- return this.db[table].map((log) => ({
55
+ async find(entity) {
56
+ const table = this.getTableName(entity);
57
+ return Promise.resolve(this.db[table].map((log) => ({
47
58
  type: log.type,
48
59
  message: log.message,
49
- }));
60
+ count: log.count,
61
+ createdAt: log.createdAt,
62
+ updatedAt: log.updatedAt,
63
+ })));
50
64
  }
51
- getOneById(table, id) {
52
- return this.db[table].find((item) => item.id === id);
65
+ async getOneById(entity, _id) {
66
+ const table = this.getTableName(entity);
67
+ return Promise.resolve(this.db[table].find((item) => item._id === _id));
53
68
  }
54
- getManyByProperty(table, field, value) {
69
+ findByProperty(entity, field, value) {
70
+ const table = this.getTableName(entity);
55
71
  return this.db[table].filter((item) => item[field] === value);
56
72
  }
73
+ findOne(entity, condition) {
74
+ const table = this.getTableName(entity);
75
+ return Promise.resolve(this.db[table].find((item) => this.partialEqual(condition.where, item)));
76
+ }
77
+ findIndex(entity, condition) {
78
+ const table = this.getTableName(entity);
79
+ return this.db[table].findIndex((item) => this.partialEqual(condition.where, item));
80
+ }
81
+ partialEqual(obj1, obj2) {
82
+ // compare primitive type values
83
+ if (obj1 === obj2)
84
+ return true;
85
+ // handle null or non-object values
86
+ if (obj1 == null ||
87
+ obj2 == null ||
88
+ typeof obj1 !== "object" ||
89
+ typeof obj2 !== "object") {
90
+ return false;
91
+ }
92
+ // compare keys length
93
+ const keys1 = Object.keys(obj1);
94
+ const keys2 = Object.keys(obj2);
95
+ // compare values recursively
96
+ for (const key of keys1) {
97
+ if (!keys2.includes(key))
98
+ return false;
99
+ if (!this.partialEqual(obj1[key], obj2[key]))
100
+ return false;
101
+ }
102
+ return true;
103
+ }
57
104
  };
58
105
  exports.MemoryDbService = MemoryDbService;
59
106
  exports.MemoryDbService = MemoryDbService = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"memory-db.service.js","sourceRoot":"","sources":["../../src/services/memory-db.service.ts"],"names":[],"mappings":";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,CAAA;AAlIY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,mBAAU,GAAE;;GACA,eAAe,CAkI3B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@viplance/nestjs-logger",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "NestJS internal logging system",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -11,6 +11,9 @@ export function createLogEntity(name: string) {
11
11
  },
12
12
  type: { type: String },
13
13
  message: { type: String },
14
+ count: { type: Number, default: 1 },
15
+ createdAt: { type: Date },
16
+ updatedAt: { type: Date },
14
17
  },
15
18
  });
16
19
  }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./log.interceptor";
2
2
  export * from "./log.module";
3
+ export * from "./types/index";
3
4
  export * from "./services/log.service";
package/src/log.module.ts CHANGED
@@ -25,7 +25,7 @@ export class LogModule {
25
25
  if (options?.path) {
26
26
  const httpAdapter = app.getHttpAdapter();
27
27
  httpAdapter.get(options.path, async (req: any, res: any) => {
28
- res.json(logService.getAll());
28
+ res.json(await logService.getAll());
29
29
  });
30
30
  }
31
31
 
@@ -7,23 +7,25 @@ import {
7
7
  import { MemoryDbService } from "./memory-db.service";
8
8
  import { defaultTable } from "../defaults";
9
9
  import { LogModuleOptions, LogType } from "../types";
10
- import { DataSource, DataSourceOptions, EntitySchema } from "typeorm";
10
+ import {
11
+ DataSource,
12
+ DataSourceOptions,
13
+ EntityManager,
14
+ EntitySchema,
15
+ } from "typeorm";
11
16
  import { createLogEntity } from "../entities/log.entity";
12
17
 
13
18
  @Injectable({ scope: Scope.TRANSIENT })
14
19
  export class LogService implements LoggerService {
15
20
  static connection: DataSource;
16
- static Log: EntitySchema;
21
+ static Log: EntitySchema = createLogEntity(defaultTable);
17
22
 
18
- constructor(
19
- private readonly MemoryDbService: MemoryDbService // @InjectRepository(Log) // private readonly userRepository: Repository<Log>
20
- ) {}
23
+ constructor(private readonly memoryDbService: MemoryDbService) {}
21
24
 
22
25
  async connectDb(options: LogModuleOptions): Promise<DataSource> {
23
- const tableName =
24
- options.database?.collection || options.database?.table || "logs";
25
-
26
- LogService.Log = createLogEntity(tableName);
26
+ LogService.Log = createLogEntity(
27
+ options.database?.collection || options.database?.table || defaultTable
28
+ );
27
29
 
28
30
  const dataSourceOptions = {
29
31
  type: options.database?.type,
@@ -41,7 +43,7 @@ export class LogService implements LoggerService {
41
43
  }
42
44
 
43
45
  log(message: string, context?: string) {
44
- this.smartInsert(defaultTable, {
46
+ this.smartInsert({
45
47
  type: LogType.LOG,
46
48
  message,
47
49
  context,
@@ -49,7 +51,7 @@ export class LogService implements LoggerService {
49
51
  }
50
52
 
51
53
  error(message: string, trace?: string, context?: ExecutionContext) {
52
- this.smartInsert(defaultTable, {
54
+ this.smartInsert({
53
55
  type: LogType.ERROR,
54
56
  message,
55
57
  trace,
@@ -58,7 +60,7 @@ export class LogService implements LoggerService {
58
60
  }
59
61
 
60
62
  warn(message: string, context?: string) {
61
- this.smartInsert(defaultTable, {
63
+ this.smartInsert({
62
64
  type: LogType.WARN,
63
65
  message,
64
66
  context,
@@ -66,7 +68,7 @@ export class LogService implements LoggerService {
66
68
  }
67
69
 
68
70
  debug(message: string, context?: string) {
69
- this.smartInsert(defaultTable, {
71
+ this.smartInsert({
70
72
  type: LogType.DEBUG,
71
73
  message,
72
74
  context,
@@ -74,28 +76,47 @@ export class LogService implements LoggerService {
74
76
  }
75
77
 
76
78
  verbose(message: string, context?: string) {
77
- this.smartInsert(defaultTable, {
79
+ this.smartInsert({
78
80
  type: LogType.VERBOSE,
79
81
  message,
80
82
  context,
81
83
  });
82
84
  }
83
85
 
84
- getAll(): any[] {
85
- return this.MemoryDbService.getMany(defaultTable);
86
+ async getAll(): Promise<any[]> {
87
+ return this.getConnection().find(LogService.Log);
86
88
  }
87
89
 
88
- private async smartInsert(table: string, data: any): Promise<any> {
89
- return await LogService.connection.manager.insert(LogService.Log, {
90
+ private async smartInsert(data: any): Promise<any> {
91
+ const currentDate = new Date();
92
+
93
+ const connection = this.getConnection();
94
+
95
+ // find the same log in DB
96
+ const log = await connection.findOne(LogService.Log, {
97
+ where: {
98
+ type: data.type,
99
+ message: data.message,
100
+ },
101
+ });
102
+
103
+ if (log) {
104
+ return await connection.update(LogService.Log, log._id, {
105
+ count: log.count + 1,
106
+ updatedAt: currentDate,
107
+ });
108
+ }
109
+
110
+ return await connection.insert(LogService.Log, {
90
111
  type: data.type,
91
112
  message: data.message,
92
113
  count: 1,
114
+ createdAt: currentDate,
115
+ updatedAt: currentDate,
93
116
  });
94
- // return this.MemoryDbService.insert(table, {
95
- // ...data,
96
- // count: 1,
97
- // createdAt: new Date(),
98
- // updatedAt: new Date(),
99
- // });
117
+ }
118
+
119
+ private getConnection(): EntityManager {
120
+ return LogService.connection.manager || this.memoryDbService;
100
121
  }
101
122
  }
@@ -2,6 +2,7 @@
2
2
  import { Injectable } from "@nestjs/common";
3
3
  import { createHash, randomBytes } from "crypto";
4
4
  import { defaultTable } from "../defaults";
5
+ import { EntitySchema } from "typeorm";
5
6
 
6
7
  const tables = [defaultTable];
7
8
 
@@ -15,44 +16,125 @@ export class MemoryDbService {
15
16
  }
16
17
  }
17
18
 
18
- public insert(table: string, data: any): string {
19
- // generate new random ID
19
+ public insert(entity: EntitySchema, data: any): string {
20
+ const table = this.getTableName(entity);
21
+
22
+ // generate new random _id
20
23
  const randomData = randomBytes(24).toString("hex");
21
- const id = createHash("sha256").update(randomData).digest("hex");
24
+ const _id = createHash("sha256").update(randomData).digest("hex");
22
25
 
23
26
  this.db[table].push({
24
27
  ...data,
25
- id, // unique index
28
+ _id, // unique index
26
29
  });
27
30
 
28
- return id;
31
+ return _id;
29
32
  }
30
33
 
31
- public update(table: string, condition: any, data: any): string {
32
- // generate new random ID
33
- const randomData = randomBytes(24).toString("hex");
34
- const id = createHash("sha256").update(randomData).digest("hex");
34
+ public async update(
35
+ entity: EntitySchema,
36
+ condition: any,
37
+ data: any
38
+ ): Promise<string> {
39
+ const table = this.getTableName(entity);
40
+ let index: number | null = null;
35
41
 
36
- this.db[table].push({
37
- ...data,
38
- id, // unique index
39
- });
42
+ if (typeof condition === "string") {
43
+ index = this.findIndex(entity, { where: { _id: condition } });
44
+ }
45
+
46
+ if (condition?.where) {
47
+ index = this.findIndex(entity, condition);
48
+ }
40
49
 
41
- return id;
50
+ if (index !== null) {
51
+ this.db[table][index] = {
52
+ ...this.db[table][index],
53
+ ...data,
54
+ };
55
+
56
+ return Promise.resolve(this.db[table][index]._id);
57
+ }
58
+
59
+ return Promise.reject();
42
60
  }
43
61
 
44
- public getMany(table: string): any[] {
45
- return this.db[table].map((log) => ({
46
- type: log.type,
47
- message: log.message,
48
- }));
62
+ public async find(entity: EntitySchema): Promise<any[]> {
63
+ const table = this.getTableName(entity);
64
+
65
+ return Promise.resolve(
66
+ this.db[table].map((log) => ({
67
+ type: log.type,
68
+ message: log.message,
69
+ count: log.count,
70
+ createdAt: log.createdAt,
71
+ updatedAt: log.updatedAt,
72
+ }))
73
+ );
49
74
  }
50
75
 
51
- public getOneById(table: string, id: string): any {
52
- return this.db[table].find((item) => item.id === id);
76
+ public async getOneById(entity: EntitySchema, _id: string): Promise<any> {
77
+ const table = this.getTableName(entity);
78
+
79
+ return Promise.resolve(this.db[table].find((item) => item._id === _id));
53
80
  }
54
81
 
55
- public getManyByProperty(table: string, field: string, value: string): any[] {
82
+ public findByProperty(
83
+ entity: EntitySchema,
84
+ field: string,
85
+ value: string
86
+ ): any[] {
87
+ const table = this.getTableName(entity);
88
+
56
89
  return this.db[table].filter((item) => item[field] === value);
57
90
  }
91
+
92
+ public findOne(
93
+ entity: EntitySchema,
94
+ condition: { where: any }
95
+ ): Promise<any> {
96
+ const table = this.getTableName(entity);
97
+
98
+ return Promise.resolve(
99
+ this.db[table].find((item) => this.partialEqual(condition.where, item))
100
+ );
101
+ }
102
+
103
+ private findIndex(entity: EntitySchema, condition: { where: any }): number {
104
+ const table = this.getTableName(entity);
105
+
106
+ return this.db[table].findIndex((item) =>
107
+ this.partialEqual(condition.where, item)
108
+ );
109
+ }
110
+
111
+ private partialEqual(obj1: any, obj2: any) {
112
+ // compare primitive type values
113
+ if (obj1 === obj2) return true;
114
+
115
+ // handle null or non-object values
116
+ if (
117
+ obj1 == null ||
118
+ obj2 == null ||
119
+ typeof obj1 !== "object" ||
120
+ typeof obj2 !== "object"
121
+ ) {
122
+ return false;
123
+ }
124
+
125
+ // compare keys length
126
+ const keys1 = Object.keys(obj1);
127
+ const keys2 = Object.keys(obj2);
128
+
129
+ // compare values recursively
130
+ for (const key of keys1) {
131
+ if (!keys2.includes(key)) return false;
132
+
133
+ if (!this.partialEqual(obj1[key], obj2[key])) return false;
134
+ }
135
+
136
+ return true;
137
+ }
138
+
139
+ private getTableName = (entity: EntitySchema) => entity.options.name;
58
140
  }