@mondart/nestjs-common-module 1.1.22 → 1.1.24

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.
@@ -1,4 +1,4 @@
1
- import { BaseErrorResponse } from "./error-response.dto";
1
+ import { BaseErrorResponse } from './error-response.dto';
2
2
  export declare class BaseKafkaErrorResponseDto {
3
3
  topic?: string;
4
4
  event_source: string;
@@ -1,5 +1,5 @@
1
1
  import { KafkaSuccessResponseInterface } from '../../interface/kafka-success-response.interface';
2
- import { BaseKafkaEventDto } from "./base-kafka-response.dto";
2
+ import { BaseKafkaEventDto } from './base-kafka-response.dto';
3
3
  export declare class KafkaSuccessResponse<type> extends BaseKafkaEventDto<type> {
4
4
  constructor({ data, event_source, topic, model, event_key, partition, status, }: KafkaSuccessResponseInterface<type>);
5
5
  stringify(): string;
@@ -1,4 +1,4 @@
1
- import { BaseModelWithDatesEntity } from "./base-model-with-dates.entity";
1
+ import { BaseModelWithDatesEntity } from './base-model-with-dates.entity';
2
2
  export declare class BaseModelWithAdminActionsEntity extends BaseModelWithDatesEntity {
3
3
  createdByAdmin?: string;
4
4
  updatedByAdmin?: string;
@@ -1,4 +1,4 @@
1
- import { BaseModelWithDatesEntity } from "./base-model-with-dates.entity";
1
+ import { BaseModelWithDatesEntity } from './base-model-with-dates.entity';
2
2
  export declare class BaseModelWithAdminAndUserActionsEntity extends BaseModelWithDatesEntity {
3
3
  createdByAdmin?: string;
4
4
  updatedByAdmin?: string;
@@ -1,4 +1,4 @@
1
- import { BaseModelEntity } from "./base-model.entity";
1
+ import { BaseModelEntity } from './base-model.entity';
2
2
  export declare class BaseModelWithDatesEntity extends BaseModelEntity {
3
3
  createdAt: Date;
4
4
  updatedAt: Date;
@@ -1,4 +1,4 @@
1
- import { BaseModelWithDatesEntity } from "./base-model-with-dates.entity";
1
+ import { BaseModelWithDatesEntity } from './base-model-with-dates.entity';
2
2
  export declare class BaseModelWithUserActionsEntity extends BaseModelWithDatesEntity {
3
3
  createdByUser?: string;
4
4
  updatedByUser?: string;
@@ -1,6 +1,6 @@
1
1
  import { EntityManager } from 'typeorm';
2
2
  import { FindOptionsRelations } from 'typeorm/find-options/FindOptionsRelations';
3
- export declare class CoreCrudServiceOption<T> {
3
+ export declare class CrudServiceOption<T> {
4
4
  entityManager?: EntityManager;
5
5
  relations?: FindOptionsRelations<T>;
6
6
  existsCheck?: boolean;
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CoreCrudServiceOption = void 0;
4
- class CoreCrudServiceOption {
3
+ exports.CrudServiceOption = void 0;
4
+ class CrudServiceOption {
5
5
  constructor() {
6
6
  this.existsCheck = true;
7
7
  }
8
8
  }
9
- exports.CoreCrudServiceOption = CoreCrudServiceOption;
9
+ exports.CrudServiceOption = CrudServiceOption;
@@ -1,2 +1,2 @@
1
- export * from './core-crud-service.option';
2
- export * from './core-crud-service.option';
1
+ export * from './crud-service.option';
2
+ export * from './crud-service.option';
@@ -14,5 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./core-crud-service.option"), exports);
18
- __exportStar(require("./core-crud-service.option"), exports);
17
+ __exportStar(require("./crud-service.option"), exports);
18
+ __exportStar(require("./crud-service.option"), exports);
@@ -1,4 +1,4 @@
1
- import { BaseErrorResponse } from "../dto";
1
+ import { BaseErrorResponse } from '../dto';
2
2
  export interface KafkaFailedResponseInterface {
3
3
  data?: BaseErrorResponse;
4
4
  event_source: string;
@@ -3,29 +3,31 @@ import { BaseModelEntity } from '../entities';
3
3
  import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
4
4
  import { Paginated } from 'nestjs-paginate';
5
5
  import { PaginateConfig } from 'nestjs-paginate/lib/paginate';
6
- import { ObjectId } from 'typeorm/driver/mongodb/typings';
7
6
  import { PaginationQueryCustom } from '../interface/pagination-query';
8
7
  import { InsertResult } from 'typeorm/query-builder/result/InsertResult';
9
- import { CoreCrudServiceOption } from '../interface';
8
+ import { CrudServiceOption } from '../interface';
10
9
  import { UpsertOptions } from 'typeorm/repository/UpsertOptions';
11
10
  export declare abstract class CoreCrudService<T extends BaseModelEntity, CreateDto, UpdateDto> {
12
11
  protected readonly repository: Repository<T>;
13
12
  private readonly relationsPath;
14
13
  protected constructor(repository: Repository<T>);
15
- create(createDto: CreateDto, options?: CoreCrudServiceOption<T>): Promise<T>;
16
- findAllWithPagination(query: PaginationQueryCustom, paginateConfig: PaginateConfig<T>, options?: CoreCrudServiceOption<T>): Promise<Paginated<T>>;
17
- findAll(query: FindManyOptions<T>, options?: CoreCrudServiceOption<T>): Promise<T[]>;
18
- findOneById(id: number, options?: CoreCrudServiceOption<T>): Promise<T>;
19
- findOne(query: FindManyOptions<T>, options?: CoreCrudServiceOption<T>): Promise<T>;
20
- isExists(query: FindManyOptions<T>, options?: CoreCrudServiceOption<T>): Promise<boolean>;
21
- count(query: FindManyOptions<T>, options?: CoreCrudServiceOption<T>): Promise<number>;
22
- upsert(upsertDto: QueryDeepPartialEntity<T>, upsertOptions: UpsertOptions<T>, options?: CoreCrudServiceOption<T>): Promise<InsertResult>;
23
- update(id: number, updateDto: Partial<UpdateDto> | DeepPartial<T> | QueryDeepPartialEntity<T>, options?: CoreCrudServiceOption<T>): Promise<UpdateResult>;
24
- softDelete(criteria: string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<T>, options?: CoreCrudServiceOption<T>): Promise<UpdateResult>;
25
- softDeleteById(id: number, options?: CoreCrudServiceOption<T>): Promise<UpdateResult>;
26
- delete(criteria: string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<T>, options?: CoreCrudServiceOption<T>): Promise<DeleteResult>;
27
- deleteById(id: number, options?: CoreCrudServiceOption<T>): Promise<DeleteResult>;
28
- private validateWhereQuery;
14
+ create(createDto: CreateDto, options?: CrudServiceOption<T>): Promise<T>;
15
+ findAllWithPagination(query: PaginationQueryCustom, paginateConfig: PaginateConfig<T>, options?: CrudServiceOption<T>): Promise<Paginated<T>>;
16
+ findAll(query: FindManyOptions<T>, options?: CrudServiceOption<T>): Promise<T[]>;
17
+ findOneById(id: number, options?: CrudServiceOption<T>): Promise<T>;
18
+ findOne(query: FindManyOptions<T>, options?: CrudServiceOption<T>): Promise<T>;
19
+ isExists(query: FindManyOptions<T>, options?: CrudServiceOption<T>): Promise<boolean>;
20
+ count(query: FindManyOptions<T>, options?: CrudServiceOption<T>): Promise<number>;
21
+ upsert(upsertDto: QueryDeepPartialEntity<T>, upsertOptions: UpsertOptions<T>, options?: CrudServiceOption<T>): Promise<InsertResult>;
22
+ update(id: number, updateDto: Partial<UpdateDto> | DeepPartial<T> | QueryDeepPartialEntity<T>, options?: CrudServiceOption<T>): Promise<UpdateResult>;
23
+ softDelete(query: FindOptionsWhere<T>, options?: CrudServiceOption<T>): Promise<UpdateResult>;
24
+ softDeleteById(id: string | string[] | number | number[], options?: CrudServiceOption<T>): Promise<UpdateResult>;
25
+ delete(query: FindOptionsWhere<T>, options?: CrudServiceOption<T>): Promise<DeleteResult>;
26
+ deleteById(id: string | string[] | number | number[], options?: CrudServiceOption<T>): Promise<DeleteResult>;
27
+ private relatedPropertyTransformer;
28
+ private whereQueryTransformer;
29
29
  private isObject;
30
30
  private isArray;
31
+ private isArrayOfObjectId;
32
+ private isArrayOfNumbers;
31
33
  }
@@ -1,33 +1,18 @@
1
1
  "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.CoreCrudService = void 0;
13
- const typeorm_1 = require("typeorm");
14
4
  const common_1 = require("@nestjs/common");
15
5
  const nestjs_paginate_1 = require("nestjs-paginate");
16
6
  const enums_1 = require("../enums");
17
7
  const helpers_1 = require("../helpers");
18
- let CoreCrudService = class CoreCrudService {
8
+ class CoreCrudService {
19
9
  constructor(repository) {
20
10
  this.repository = repository;
21
11
  const metadata = this.repository.metadata;
22
12
  this.relationsPath = metadata.relations.map((relation) => relation.propertyPath);
23
13
  }
24
14
  async create(createDto, options) {
25
- const relationEntityName = Object.keys(createDto).filter((item) => this.relationsPath.includes(item) && createDto[item]);
26
- relationEntityName.map((item) => {
27
- createDto[item] = createDto[item].map((id) => {
28
- return { id };
29
- });
30
- });
15
+ createDto = this.relatedPropertyTransformer(createDto);
31
16
  const entity = this.repository.create(createDto);
32
17
  if (options?.entityManager) {
33
18
  return await options.entityManager.save(entity);
@@ -44,18 +29,19 @@ let CoreCrudService = class CoreCrudService {
44
29
  }
45
30
  async findAll(query, options) {
46
31
  let result;
32
+ query.where = this.whereQueryTransformer(query.where) ?? undefined;
47
33
  if (!options?.entityManager)
48
34
  result = await this.repository.find({
49
- relations: this.relationsPath,
35
+ relations: options?.relations ? options?.relations : this.relationsPath,
50
36
  ...query,
51
37
  });
52
38
  else
53
39
  result = await options.entityManager.find(this.repository.target, {
54
- relations: this.relationsPath,
40
+ relations: options?.relations ? options?.relations : this.relationsPath,
55
41
  ...query,
56
42
  });
57
43
  if (options?.existsCheck && !result) {
58
- throw new common_1.NotFoundException(enums_1.SharedMessages.RESOURCE_NOT_FOUND);
44
+ throw new common_1.NotFoundException(helpers_1.MessageFormatter.replace(enums_1.SharedMessages.RESOURCE_NOT_FOUND, `${helpers_1.ConvertStringCaseHelper.snakeToKebab(this.repository.metadata?.tableName)}`));
59
45
  }
60
46
  return result;
61
47
  }
@@ -83,15 +69,11 @@ let CoreCrudService = class CoreCrudService {
83
69
  return result;
84
70
  }
85
71
  async findOne(query, options) {
86
- const whereQuery = this.validateWhereQuery(query.where);
87
- if (!whereQuery) {
88
- return undefined;
89
- }
90
- query.where = whereQuery;
91
72
  let result;
73
+ query.where = this.whereQueryTransformer(query.where) ?? undefined;
92
74
  if (options?.entityManager) {
93
75
  result = await options?.entityManager.findOne(this.repository.target, {
94
- relations: this.relationsPath,
76
+ relations: options?.relations ? options?.relations : this.relationsPath,
95
77
  ...query,
96
78
  });
97
79
  }
@@ -102,12 +84,13 @@ let CoreCrudService = class CoreCrudService {
102
84
  });
103
85
  }
104
86
  if (options?.existsCheck && !result) {
105
- throw new common_1.NotFoundException(enums_1.SharedMessages.RESOURCE_NOT_FOUND);
87
+ throw new common_1.NotFoundException(helpers_1.MessageFormatter.replace(enums_1.SharedMessages.RESOURCE_NOT_FOUND, `${helpers_1.ConvertStringCaseHelper.snakeToKebab(this.repository.metadata?.tableName)}`));
106
88
  }
107
89
  return result;
108
90
  }
109
91
  async isExists(query, options) {
110
92
  let result;
93
+ query.where = this.whereQueryTransformer(query.where) ?? undefined;
111
94
  if (options?.entityManager) {
112
95
  result = await options?.entityManager.exists(this.repository.target, {
113
96
  relations: query?.relations ? query?.relations : this.relationsPath,
@@ -123,12 +106,8 @@ let CoreCrudService = class CoreCrudService {
123
106
  return result;
124
107
  }
125
108
  async count(query, options) {
126
- const whereQuery = this.validateWhereQuery(query.where);
127
- if (!whereQuery) {
128
- return undefined;
129
- }
130
- query.where = whereQuery;
131
109
  let result;
110
+ query.where = this.whereQueryTransformer(query.where) ?? undefined;
132
111
  if (options?.entityManager) {
133
112
  result = await options?.entityManager.count(this.repository.target, {
134
113
  relations: query?.relations ? query?.relations : this.relationsPath,
@@ -145,6 +124,7 @@ let CoreCrudService = class CoreCrudService {
145
124
  }
146
125
  async upsert(upsertDto, upsertOptions, options) {
147
126
  try {
127
+ upsertDto = this.relatedPropertyTransformer(upsertDto);
148
128
  let conflictPaths = [];
149
129
  let findWhereQuery = {};
150
130
  if (this.isArray(upsertOptions.conflictPaths)) {
@@ -159,16 +139,17 @@ let CoreCrudService = class CoreCrudService {
159
139
  [path]: upsertDto[path],
160
140
  };
161
141
  });
142
+ const formatedQuery = this.whereQueryTransformer(findWhereQuery) ?? undefined;
162
143
  if (!options?.entityManager) {
163
144
  const existEntity = await this.repository.findOne({
164
- where: findWhereQuery,
145
+ where: formatedQuery,
165
146
  select: ['id'],
166
147
  });
167
148
  return await this.repository.upsert({ id: existEntity.id, ...upsertDto }, upsertOptions);
168
149
  }
169
150
  else {
170
151
  const existEntity = await options?.entityManager.findOne(this.repository.target, {
171
- where: findWhereQuery,
152
+ where: formatedQuery,
172
153
  select: ['id'],
173
154
  });
174
155
  return await options?.entityManager.upsert(this.repository.target, { id: existEntity.id, ...upsertDto }, upsertOptions);
@@ -179,20 +160,14 @@ let CoreCrudService = class CoreCrudService {
179
160
  }
180
161
  }
181
162
  async update(id, updateDto, options) {
163
+ updateDto = this.relatedPropertyTransformer(updateDto);
182
164
  if (!options?.entityManager) {
183
165
  const fetchedItem = await this.repository.findOne({
184
166
  where: { id },
185
- relations: this.relationsPath,
167
+ relations: options?.relations ? options?.relations : this.relationsPath,
186
168
  });
187
169
  if (!fetchedItem)
188
- throw new common_1.NotFoundException(enums_1.SharedMessages.RESOURCE_NOT_FOUND);
189
- const relationEntityName = Object.keys(updateDto).filter((item) => this.relationsPath.includes(item) && updateDto[item]);
190
- relationEntityName.map((item) => {
191
- delete fetchedItem[item];
192
- updateDto[item] = updateDto[item].map((id) => {
193
- return { id };
194
- });
195
- });
170
+ throw new common_1.NotFoundException(helpers_1.MessageFormatter.replace(enums_1.SharedMessages.RESOURCE_NOT_FOUND, `${helpers_1.ConvertStringCaseHelper.snakeToKebab(this.repository.metadata?.tableName)}`));
196
171
  const merged = this.repository.merge(fetchedItem, updateDto);
197
172
  await this.repository.save(merged);
198
173
  return {
@@ -207,14 +182,7 @@ let CoreCrudService = class CoreCrudService {
207
182
  relations: this.relationsPath,
208
183
  });
209
184
  if (!fetchedItem)
210
- throw new common_1.NotFoundException(enums_1.SharedMessages.RESOURCE_NOT_FOUND);
211
- const relationEntityName = Object.keys(updateDto).filter((item) => this.relationsPath.includes(item) && updateDto[item]);
212
- relationEntityName.map((item) => {
213
- delete fetchedItem[item];
214
- updateDto[item] = updateDto[item].map((id) => {
215
- return { id };
216
- });
217
- });
185
+ throw new common_1.NotFoundException(helpers_1.MessageFormatter.replace(enums_1.SharedMessages.RESOURCE_NOT_FOUND, `${helpers_1.ConvertStringCaseHelper.snakeToKebab(this.repository.metadata?.tableName)}`));
218
186
  const merged = options?.entityManager.merge(this.repository.target, fetchedItem, updateDto);
219
187
  await options?.entityManager.save(merged);
220
188
  return {
@@ -224,12 +192,13 @@ let CoreCrudService = class CoreCrudService {
224
192
  };
225
193
  }
226
194
  }
227
- async softDelete(criteria, options) {
195
+ async softDelete(query, options) {
196
+ const formatedQuery = this.whereQueryTransformer(query) ?? undefined;
228
197
  if (options?.entityManager) {
229
- return await options?.entityManager.softDelete(this.repository.target, criteria);
198
+ return await options?.entityManager.softDelete(this.repository.target, formatedQuery);
230
199
  }
231
200
  else {
232
- return await this.repository.softDelete(criteria);
201
+ return await this.repository.softDelete(formatedQuery);
233
202
  }
234
203
  }
235
204
  async softDeleteById(id, options) {
@@ -240,12 +209,13 @@ let CoreCrudService = class CoreCrudService {
240
209
  return await this.repository.softDelete(id);
241
210
  }
242
211
  }
243
- async delete(criteria, options) {
212
+ async delete(query, options) {
213
+ const formatedQuery = this.whereQueryTransformer(query) ?? undefined;
244
214
  if (options?.entityManager) {
245
- return await options?.entityManager.delete(this.repository.target, criteria);
215
+ return await options?.entityManager.delete(this.repository.target, formatedQuery);
246
216
  }
247
217
  else {
248
- return await this.repository.delete(criteria);
218
+ return await this.repository.delete(formatedQuery);
249
219
  }
250
220
  }
251
221
  async deleteById(id, options) {
@@ -256,52 +226,58 @@ let CoreCrudService = class CoreCrudService {
256
226
  return await this.repository.delete(id);
257
227
  }
258
228
  }
259
- validateWhereQuery(query) {
260
- if (this.isArray(query)) {
261
- const newArrayQuery = [];
262
- query = query;
263
- if (query.length !== 0) {
264
- query.map((key, index) => {
265
- if (this.isArray(query[index])) {
266
- return query[index].map((item) => this.validateWhereQuery(item));
267
- }
268
- if (this.isObject(query[index])) {
269
- this.validateWhereQuery(query[index]);
270
- }
271
- if (query[index] !== undefined) {
272
- newArrayQuery.push({
273
- [index]: query[index],
274
- });
275
- }
229
+ relatedPropertyTransformer(dtoObject) {
230
+ const relationEntityName = Object.keys(dtoObject).filter((item) => this.relationsPath.includes(item) && dtoObject[item]);
231
+ relationEntityName.map((item) => {
232
+ let relatedItem;
233
+ if (this.isArrayOfNumbers(dtoObject[item])) {
234
+ relatedItem = dtoObject[item].map((id) => {
235
+ return { id };
276
236
  });
277
237
  }
278
- if (Object.keys(newArrayQuery).length === 0)
279
- return undefined;
280
- return newArrayQuery;
238
+ else {
239
+ relatedItem = dtoObject[item];
240
+ }
241
+ dtoObject[item] = relatedItem;
242
+ });
243
+ return dtoObject;
244
+ }
245
+ whereQueryTransformer(query) {
246
+ if (typeof query === 'object' && Array.isArray(query)) {
247
+ const newArrayQuery = query
248
+ .map((item) => this.whereQueryTransformer(item))
249
+ .filter((item) => item !== undefined);
250
+ return newArrayQuery.length > 0 ? newArrayQuery : undefined;
281
251
  }
282
- else {
283
- let newQuery = {};
284
- const queryKeys = Object.keys(query);
285
- if (queryKeys.length !== 0) {
286
- queryKeys.map((key) => {
287
- if (this.isArray(query[key])) {
288
- return query[key].map((item) => this.validateWhereQuery(item));
252
+ else if (this.isObject(query)) {
253
+ const newQuery = {};
254
+ for (const key in query) {
255
+ if (query.hasOwnProperty(key)) {
256
+ const value = query[key];
257
+ if (typeof value === 'object' && Array.isArray(value)) {
258
+ const validatedArray = value
259
+ .map((item) => this.whereQueryTransformer(item))
260
+ .filter((item) => item !== undefined);
261
+ if (validatedArray.length > 0) {
262
+ newQuery[key] = validatedArray;
263
+ }
289
264
  }
290
- if (this.isObject(query[key])) {
291
- this.validateWhereQuery(query[key]);
265
+ else if (value !== null &&
266
+ typeof value === 'object' &&
267
+ !Array.isArray(value)) {
268
+ const validatedObject = this.whereQueryTransformer(value);
269
+ if (validatedObject !== undefined) {
270
+ newQuery[key] = validatedObject;
271
+ }
292
272
  }
293
- if (query[key] !== undefined) {
294
- newQuery = {
295
- ...newQuery,
296
- [key]: query[key],
297
- };
273
+ else if (value !== undefined) {
274
+ newQuery[key] = value;
298
275
  }
299
- });
276
+ }
300
277
  }
301
- if (Object.keys(newQuery).length === 0)
302
- return undefined;
303
- return newQuery;
278
+ return Object.keys(newQuery).length > 0 ? newQuery : undefined;
304
279
  }
280
+ return undefined;
305
281
  }
306
282
  isObject(value) {
307
283
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -309,9 +285,12 @@ let CoreCrudService = class CoreCrudService {
309
285
  isArray(value) {
310
286
  return value !== null && typeof value === 'object' && Array.isArray(value);
311
287
  }
312
- };
288
+ isArrayOfObjectId(value) {
289
+ return (this.isArray(value) &&
290
+ value.every((item) => this.isObject(item) && item?.id));
291
+ }
292
+ isArrayOfNumbers(value) {
293
+ return (this.isArray(value) && value.every((item) => typeof item === 'number'));
294
+ }
295
+ }
313
296
  exports.CoreCrudService = CoreCrudService;
314
- exports.CoreCrudService = CoreCrudService = __decorate([
315
- (0, common_1.Injectable)(),
316
- __metadata("design:paramtypes", [typeorm_1.Repository])
317
- ], CoreCrudService);