@koalarx/nest 1.0.1 → 1.1.0

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.
@@ -0,0 +1,6 @@
1
+ import { QueryDirectionType } from "..";
2
+ export declare const QUERY_FILTER_PARAMS: {
3
+ direction: QueryDirectionType;
4
+ page: number;
5
+ limit: number;
6
+ };
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QUERY_FILTER_PARAMS = void 0;
4
+ exports.QUERY_FILTER_PARAMS = {
5
+ direction: 'asc',
6
+ page: 0,
7
+ limit: 30,
8
+ };
@@ -0,0 +1,10 @@
1
+ import { QueryDirectionType } from '..';
2
+ export type PaginatedRequestProps<T extends PaginationRequest> = Omit<{
3
+ [K in keyof T as T[K] extends Function ? never : K]: T[K];
4
+ }, '_id'>;
5
+ export declare class PaginationRequest {
6
+ page?: number;
7
+ limit?: number;
8
+ orderBy?: string;
9
+ direction?: QueryDirectionType;
10
+ }
@@ -9,59 +9,48 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.PaginationParams = exports.QueryFilterParams = void 0;
12
+ exports.PaginationRequest = void 0;
13
13
  const swagger_1 = require("@nestjs/swagger");
14
- exports.QueryFilterParams = {
15
- direction: 'asc',
16
- page: 0,
17
- limit: 30,
18
- };
19
- class PaginationParams {
20
- page = exports.QueryFilterParams.page;
21
- limit = exports.QueryFilterParams.limit;
14
+ const auto_mapping_decorator_1 = require("../mapping/auto-mapping.decorator");
15
+ const query_params_1 = require("../constants/query-params");
16
+ class PaginationRequest {
17
+ page = query_params_1.QUERY_FILTER_PARAMS.page;
18
+ limit = query_params_1.QUERY_FILTER_PARAMS.limit;
22
19
  orderBy;
23
- direction = exports.QueryFilterParams.direction;
24
- skip() {
25
- return (this.limit ?? 0) * (this.page ?? exports.QueryFilterParams.page);
26
- }
27
- generateOrderBy() {
28
- if (this.orderBy) {
29
- const orderByField = this.orderBy.split('.');
30
- return orderByField.reduceRight((acc, item, index) => ({
31
- [item]: index === orderByField.length - 1 ? this.direction : acc,
32
- }), {});
33
- }
34
- return undefined;
35
- }
20
+ direction = query_params_1.QUERY_FILTER_PARAMS.direction;
36
21
  }
37
- exports.PaginationParams = PaginationParams;
22
+ exports.PaginationRequest = PaginationRequest;
38
23
  __decorate([
39
24
  (0, swagger_1.ApiProperty)({
40
25
  required: false,
41
26
  format: 'int32',
42
- default: exports.QueryFilterParams.page,
27
+ default: query_params_1.QUERY_FILTER_PARAMS.page,
43
28
  }),
29
+ (0, auto_mapping_decorator_1.AutoMap)(),
44
30
  __metadata("design:type", Number)
45
- ], PaginationParams.prototype, "page", void 0);
31
+ ], PaginationRequest.prototype, "page", void 0);
46
32
  __decorate([
47
33
  (0, swagger_1.ApiProperty)({
48
34
  required: false,
49
35
  format: 'int32',
50
- default: exports.QueryFilterParams.limit,
36
+ default: query_params_1.QUERY_FILTER_PARAMS.limit,
51
37
  }),
38
+ (0, auto_mapping_decorator_1.AutoMap)(),
52
39
  __metadata("design:type", Number)
53
- ], PaginationParams.prototype, "limit", void 0);
40
+ ], PaginationRequest.prototype, "limit", void 0);
54
41
  __decorate([
55
42
  (0, swagger_1.ApiProperty)({
56
43
  required: false,
57
44
  }),
45
+ (0, auto_mapping_decorator_1.AutoMap)(),
58
46
  __metadata("design:type", String)
59
- ], PaginationParams.prototype, "orderBy", void 0);
47
+ ], PaginationRequest.prototype, "orderBy", void 0);
60
48
  __decorate([
61
49
  (0, swagger_1.ApiProperty)({
62
50
  required: false,
63
51
  enum: ['asc', 'desc'],
64
- default: exports.QueryFilterParams.direction,
52
+ default: query_params_1.QUERY_FILTER_PARAMS.direction,
65
53
  }),
54
+ (0, auto_mapping_decorator_1.AutoMap)(),
66
55
  __metadata("design:type", String)
67
- ], PaginationParams.prototype, "direction", void 0);
56
+ ], PaginationRequest.prototype, "direction", void 0);
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LIST_QUERY_SCHEMA = void 0;
4
4
  const zod_1 = require("zod");
5
- const pagination_params_1 = require("../../models/pagination-params");
5
+ const query_params_1 = require("../../constants/query-params");
6
6
  exports.LIST_QUERY_SCHEMA = zod_1.z.object({
7
7
  page: zod_1.z.coerce
8
8
  .number()
@@ -10,10 +10,10 @@ exports.LIST_QUERY_SCHEMA = zod_1.z.object({
10
10
  if (value) {
11
11
  return value - 1;
12
12
  }
13
- return pagination_params_1.QueryFilterParams.page;
13
+ return query_params_1.QUERY_FILTER_PARAMS.page;
14
14
  })
15
15
  .optional(),
16
- limit: zod_1.z.coerce.number().default(pagination_params_1.QueryFilterParams.limit).optional(),
16
+ limit: zod_1.z.coerce.number().default(query_params_1.QUERY_FILTER_PARAMS.limit).optional(),
17
17
  orderBy: zod_1.z.string().optional(),
18
18
  direction: zod_1.z.enum(['asc', 'desc']).default('asc').optional(),
19
19
  });
@@ -1,6 +1,6 @@
1
1
  import { Type } from '@nestjs/common';
2
- import { ListResponse } from '../@types';
3
- import { PaginationParams } from '../models/pagination-params';
2
+ import { ListResponse } from '..';
3
+ import { PaginationDto } from '../dtos/pagination.dto';
4
4
  import { IComparableId } from '../utils/interfaces/icomparable';
5
5
  import { EntityBase } from './entity.base';
6
6
  import { PrismaTransactionalClient } from './prisma-transactional-client';
@@ -20,10 +20,12 @@ export declare abstract class RepositoryBase<TEntity extends EntityBase<TEntity>
20
20
  constructor({ context, modelName, include, }: RepositoryInitProps<TEntity>);
21
21
  withTransaction(fn: (prisma: PrismaTransactionalClient) => Promise<any>): Promise<any>;
22
22
  protected findById(id: IComparableId): Promise<TEntity | null>;
23
- protected findMany<T>(where: T, pagination?: PaginationParams): Promise<any>;
24
- protected findManyAndCount<T>(where: T, pagination?: PaginationParams): Promise<ListResponse<TEntity>>;
25
- protected saveChanges(entity: TEntity): any;
26
- protected delete(id: IComparableId): any;
23
+ protected findFirst<T>(where: T): Promise<any>;
24
+ protected findMany<T>(where: T, pagination?: PaginationDto): Promise<any>;
25
+ protected findManyAndCount<T>(where: T, pagination?: PaginationDto): Promise<ListResponse<TEntity>>;
26
+ protected insert(entity: TEntity): any;
27
+ protected edit<TWhere = any>(entity: TEntity, updateWhere?: TWhere): Promise<any>;
28
+ protected remove<TWhere = any>(where: TWhere): any;
27
29
  private listToRelationActionList;
28
30
  private entityToPrisma;
29
31
  private context;
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RepositoryBase = void 0;
4
4
  const string_1 = require("@koalarx/utils/operators/string");
5
+ const pagination_dto_1 = require("../dtos/pagination.dto");
5
6
  const koala_global_vars_1 = require("../koala-global-vars");
6
- const pagination_params_1 = require("../models/pagination-params");
7
7
  const list_1 = require("../utils/list");
8
8
  const entity_base_1 = require("./entity.base");
9
9
  class RepositoryBase {
@@ -33,6 +33,19 @@ class RepositoryBase {
33
33
  return null;
34
34
  });
35
35
  }
36
+ async findFirst(where) {
37
+ return this.context()
38
+ .findFirst({
39
+ include: this._include,
40
+ where,
41
+ })
42
+ .then((response) => {
43
+ if (response) {
44
+ return this.createEntity(response);
45
+ }
46
+ return null;
47
+ });
48
+ }
36
49
  async findMany(where, pagination) {
37
50
  return this.context()
38
51
  .findMany(this.findManySchema(where, pagination))
@@ -41,39 +54,35 @@ class RepositoryBase {
41
54
  async findManyAndCount(where, pagination) {
42
55
  const count = await this.context().count({ where });
43
56
  if (count > 0) {
44
- const items = await this.findMany(where, Object.assign(new pagination_params_1.PaginationParams(), pagination));
57
+ const items = await this.findMany(where, Object.assign(new pagination_dto_1.PaginationDto(), pagination));
45
58
  return { items, count };
46
59
  }
47
60
  return { items: [], count };
48
61
  }
49
- saveChanges(entity) {
62
+ insert(entity) {
50
63
  const prismaEntity = this.entityToPrisma(entity);
51
- const isCreate = !entity._id;
52
- if (isCreate) {
53
- return this.context().create({
54
- data: prismaEntity,
55
- });
56
- }
57
- else {
58
- return this.withTransaction((client) => this.context(client)
59
- .update({
60
- where: { id: entity._id },
61
- data: prismaEntity,
62
- })
63
- .then(() => {
64
- const { relationUpdates, relationDeletes } = this.listToRelationActionList(entity);
65
- return Promise.all([
66
- ...relationUpdates.map((relation) => client[relation.modelName].updateMany(relation.schema)),
67
- ...relationDeletes.map((relation) => client[relation.modelName].deleteMany(relation.schema)),
68
- ]);
69
- }));
70
- }
71
- }
72
- delete(id) {
73
- return this.context().delete({
74
- where: { id },
64
+ return this.context().create({
65
+ data: prismaEntity,
75
66
  });
76
67
  }
68
+ edit(entity, updateWhere) {
69
+ const prismaEntity = this.entityToPrisma(entity);
70
+ return this.withTransaction((client) => this.context(client)
71
+ .update({
72
+ where: updateWhere ?? { id: entity._id },
73
+ data: prismaEntity,
74
+ })
75
+ .then(() => {
76
+ const { relationUpdates, relationDeletes } = this.listToRelationActionList(entity);
77
+ return Promise.all([
78
+ ...relationUpdates.map((relation) => client[relation.modelName].updateMany(relation.schema)),
79
+ ...relationDeletes.map((relation) => client[relation.modelName].deleteMany(relation.schema)),
80
+ ]);
81
+ }));
82
+ }
83
+ remove(where) {
84
+ return this.context().delete({ where });
85
+ }
77
86
  listToRelationActionList(entity) {
78
87
  const relationUpdates = [];
79
88
  const relationDeletes = [];
@@ -0,0 +1,9 @@
1
+ import { QueryDirectionType } from '..';
2
+ export declare class PaginationDto {
3
+ page?: number;
4
+ limit?: number;
5
+ orderBy?: string;
6
+ direction?: QueryDirectionType;
7
+ skip(): number;
8
+ generateOrderBy(): {} | undefined;
9
+ }
@@ -0,0 +1,49 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PaginationDto = void 0;
13
+ const query_params_1 = require("../constants/query-params");
14
+ const auto_mapping_decorator_1 = require("../mapping/auto-mapping.decorator");
15
+ class PaginationDto {
16
+ page = 0;
17
+ limit = query_params_1.QUERY_FILTER_PARAMS.limit;
18
+ orderBy = '';
19
+ direction = 'asc';
20
+ skip() {
21
+ return (this.limit ?? 0) * (this.page ?? query_params_1.QUERY_FILTER_PARAMS.page);
22
+ }
23
+ generateOrderBy() {
24
+ if (this.orderBy) {
25
+ const orderByField = this.orderBy.split('.');
26
+ return orderByField.reduceRight((acc, item, index) => ({
27
+ [item]: index === orderByField.length - 1 ? this.direction : acc,
28
+ }), {});
29
+ }
30
+ return undefined;
31
+ }
32
+ }
33
+ exports.PaginationDto = PaginationDto;
34
+ __decorate([
35
+ (0, auto_mapping_decorator_1.AutoMap)(),
36
+ __metadata("design:type", Number)
37
+ ], PaginationDto.prototype, "page", void 0);
38
+ __decorate([
39
+ (0, auto_mapping_decorator_1.AutoMap)(),
40
+ __metadata("design:type", Number)
41
+ ], PaginationDto.prototype, "limit", void 0);
42
+ __decorate([
43
+ (0, auto_mapping_decorator_1.AutoMap)(),
44
+ __metadata("design:type", String)
45
+ ], PaginationDto.prototype, "orderBy", void 0);
46
+ __decorate([
47
+ (0, auto_mapping_decorator_1.AutoMap)(),
48
+ __metadata("design:type", String)
49
+ ], PaginationDto.prototype, "direction", void 0);
@@ -0,0 +1,15 @@
1
+ export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
2
+ export type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
3
+ export type CreatedRegister<TypeId = string> = {
4
+ id: TypeId;
5
+ };
6
+ export type ListResponse<TItem = any> = {
7
+ items: Array<TItem>;
8
+ count: number;
9
+ };
10
+ export type FileResponse = {
11
+ filename: string;
12
+ type: string;
13
+ base64: string;
14
+ };
15
+ export type QueryDirectionType = 'asc' | 'desc';
package/core/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -29,7 +29,7 @@ let AutoMappingService = exports.AutoMappingService = class AutoMappingService {
29
29
  const value = data[propSource.name];
30
30
  const compositionType = propSource.compositionType;
31
31
  const compositionAction = propSource.compositionAction;
32
- if (value) {
32
+ if (value !== undefined) {
33
33
  const targetProp = propTargetContext?.props.find((tp) => tp.name === propSource.name);
34
34
  if (targetProp) {
35
35
  const listToArray = propSource.type === list_1.List.name &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalarx/nest",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,16 +1,17 @@
1
+ import { PaginationDto } from '@koalarx/nest/core/dtos/pagination.dto';
1
2
  import { CreatedRegistreResponseBase } from '../../core/controllers/created-registre-response.base';
2
3
  import { ListResponseBase } from '../../core/controllers/list-response.base';
3
4
  import { EntityBase } from '../../core/database/entity.base';
4
- import { PaginationParams } from '../../core/models/pagination-params';
5
5
  import { IComparableId } from '../../core/utils/interfaces/icomparable';
6
6
  export declare abstract class InMemoryBaseRepository<TClass extends EntityBase<any>> {
7
7
  private readonly typeId;
8
8
  protected items: TClass[];
9
9
  constructor(typeId?: 'number' | 'string');
10
10
  protected findById(id: IComparableId): Promise<TClass | null>;
11
- protected findMany<T extends PaginationParams>(query: T, predicate?: (value: TClass, index: number, array: TClass[]) => unknown): Promise<TClass[]>;
12
- protected findManyAndCount<T extends PaginationParams>(query: T, predicate?: (value: TClass, index: number, array: TClass[]) => unknown): Promise<ListResponseBase<TClass>>;
13
- protected saveChanges(item: TClass): Promise<CreatedRegistreResponseBase<any>>;
11
+ protected findMany<T extends PaginationDto>(query: T, predicate?: (value: TClass, index: number, array: TClass[]) => unknown): Promise<TClass[]>;
12
+ protected findManyAndCount<T extends PaginationDto>(query: T, predicate?: (value: TClass, index: number, array: TClass[]) => unknown): Promise<ListResponseBase<TClass>>;
13
+ protected insert(item: TClass): Promise<CreatedRegistreResponseBase<any>>;
14
+ protected edit(item: TClass, updateWhere?: (item: TClass) => boolean): Promise<void>;
14
15
  protected remove(predicate: (value: TClass, index: number, obj: TClass[]) => unknown): Promise<void>;
15
16
  private getNewId;
16
17
  }
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InMemoryBaseRepository = void 0;
4
+ const query_params_1 = require("../../core/constants/query-params");
4
5
  const array_1 = require("@koalarx/utils/operators/array");
5
- const pagination_params_1 = require("../../core/models/pagination-params");
6
6
  const node_crypto_1 = require("node:crypto");
7
7
  class InMemoryBaseRepository {
8
8
  typeId;
@@ -14,8 +14,8 @@ class InMemoryBaseRepository {
14
14
  return this.items.find((item) => item._id === id) ?? null;
15
15
  }
16
16
  async findMany(query, predicate) {
17
- const page = query.page ?? pagination_params_1.QueryFilterParams.page;
18
- const limit = query.limit ?? pagination_params_1.QueryFilterParams.limit;
17
+ const page = query.page ?? query_params_1.QUERY_FILTER_PARAMS.page;
18
+ const limit = query.limit ?? query_params_1.QUERY_FILTER_PARAMS.limit;
19
19
  return (0, array_1.klArray)(predicate ? this.items.filter(predicate) : this.items)
20
20
  .orderBy(query.orderBy ?? '', query.direction === 'desc')
21
21
  .getValue()
@@ -28,11 +28,7 @@ class InMemoryBaseRepository {
28
28
  count: items.length,
29
29
  };
30
30
  }
31
- async saveChanges(item) {
32
- const itemIndex = this.items.findIndex((itemDB) => itemDB.equals(item));
33
- if (itemIndex > -1) {
34
- this.items[itemIndex] = item;
35
- }
31
+ async insert(item) {
36
32
  const id = this.typeId === 'number'
37
33
  ? this.getNewId()
38
34
  : (0, node_crypto_1.randomUUID)();
@@ -40,6 +36,13 @@ class InMemoryBaseRepository {
40
36
  this.items.push(item);
41
37
  return { id: item._id };
42
38
  }
39
+ async edit(item, updateWhere) {
40
+ const predicate = updateWhere ?? ((itemDB) => itemDB.equals(item));
41
+ const itemIndex = this.items.findIndex(predicate);
42
+ if (itemIndex > -1) {
43
+ this.items[itemIndex] = item;
44
+ }
45
+ }
43
46
  async remove(predicate) {
44
47
  const itemIndex = this.items.findIndex(predicate);
45
48
  if (itemIndex > -1) {