@koalarx/nest 3.0.2 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +504 -0
- package/core/backgroud-services/cron-service/cron-job.handler.base.d.ts +16 -0
- package/core/backgroud-services/cron-service/cron-job.handler.base.js +49 -0
- package/core/backgroud-services/event-service/event-class.d.ts +5 -0
- package/core/backgroud-services/event-service/event-class.js +11 -0
- package/core/backgroud-services/event-service/event-handler.base.d.ts +8 -0
- package/core/backgroud-services/event-service/event-handler.base.js +14 -0
- package/core/backgroud-services/event-service/event-is-trigger.d.ts +3 -0
- package/core/backgroud-services/event-service/event-is-trigger.js +7 -0
- package/core/backgroud-services/event-service/event-job.d.ts +13 -0
- package/core/backgroud-services/event-service/event-job.js +21 -0
- package/core/backgroud-services/event-service/event-queue.d.ts +17 -0
- package/core/backgroud-services/event-service/event-queue.js +62 -0
- package/core/constants/query-params.d.ts +6 -0
- package/core/constants/query-params.js +8 -0
- package/core/controllers/base.controller.d.ts +4 -0
- package/core/controllers/base.controller.js +6 -0
- package/core/controllers/controller.decorator.d.ts +2 -0
- package/core/controllers/controller.decorator.js +11 -0
- package/core/controllers/created-registre-response.base.d.ts +10 -0
- package/core/controllers/created-registre-response.base.js +35 -0
- package/core/controllers/list-response.base.d.ts +4 -0
- package/core/controllers/list-response.base.js +21 -0
- package/core/controllers/pagination.request.d.ts +10 -0
- package/core/controllers/pagination.request.js +56 -0
- package/core/controllers/router-config.base.d.ts +7 -0
- package/core/controllers/router-config.base.js +18 -0
- package/core/controllers/schemas/boolean.schema.d.ts +2 -0
- package/core/controllers/schemas/boolean.schema.js +12 -0
- package/core/controllers/schemas/document-number.schema.d.ts +1 -0
- package/core/controllers/schemas/document-number.schema.js +26 -0
- package/core/controllers/schemas/email.schema.d.ts +1 -0
- package/core/controllers/schemas/email.schema.js +13 -0
- package/core/controllers/schemas/list-query.schema.d.ts +17 -0
- package/core/controllers/schemas/list-query.schema.js +19 -0
- package/core/controllers/schemas/native-enum.schema.d.ts +7 -0
- package/core/controllers/schemas/native-enum.schema.js +28 -0
- package/core/controllers/schemas/set-mask-document-number.schema.d.ts +1 -0
- package/core/controllers/schemas/set-mask-document-number.schema.js +13 -0
- package/core/database/entity.base.d.ts +20 -0
- package/core/database/entity.base.js +71 -0
- package/core/database/entity.decorator.d.ts +13 -0
- package/core/database/entity.decorator.js +23 -0
- package/core/database/prisma-client-with-custom-transaction.interface.d.ts +8 -0
- package/core/database/prisma-client-with-custom-transaction.interface.js +2 -0
- package/core/database/prisma-resolver.d.ts +2 -0
- package/core/database/prisma-resolver.js +74 -0
- package/core/database/prisma-transactional-client.d.ts +11 -0
- package/core/database/prisma-transactional-client.js +25 -0
- package/core/database/prisma.service.d.ts +24 -0
- package/core/database/prisma.service.js +104 -0
- package/core/database/repository.base.d.ts +44 -0
- package/core/database/repository.base.js +360 -0
- package/core/dtos/pagination.dto.d.ts +9 -0
- package/core/dtos/pagination.dto.js +49 -0
- package/core/errors/bad-request.error.d.ts +5 -0
- package/core/errors/bad-request.error.js +10 -0
- package/core/errors/conflict.error.d.ts +4 -0
- package/core/errors/conflict.error.js +10 -0
- package/core/errors/error.base.d.ts +4 -0
- package/core/errors/error.base.js +11 -0
- package/core/errors/no-content.error.d.ts +5 -0
- package/core/errors/no-content.error.js +10 -0
- package/core/errors/not-allowed.error.d.ts +5 -0
- package/core/errors/not-allowed.error.js +10 -0
- package/core/errors/resource-not-found.error.d.ts +5 -0
- package/core/errors/resource-not-found.error.js +10 -0
- package/{src/core/errors/use-case-error.ts → core/errors/use-case-error.d.ts} +1 -1
- package/core/errors/use-case-error.js +2 -0
- package/core/errors/user-already-exist.error.d.ts +4 -0
- package/core/errors/user-already-exist.error.js +10 -0
- package/core/errors/wrong-credentials.error.d.ts +4 -0
- package/core/errors/wrong-credentials.error.js +10 -0
- package/core/health-check/health-check.controller.d.ts +5 -0
- package/core/health-check/health-check.controller.js +32 -0
- package/core/health-check/health-check.module.d.ts +2 -0
- package/core/health-check/health-check.module.js +19 -0
- package/core/index.d.ts +18 -0
- package/core/index.js +7 -0
- package/core/koala-app.d.ts +64 -0
- package/core/koala-app.js +252 -0
- package/core/koala-global-vars.d.ts +7 -0
- package/core/koala-global-vars.js +9 -0
- package/core/koala-nest-database.module.d.ts +16 -0
- package/core/koala-nest-database.module.js +52 -0
- package/core/koala-nest-http.module.d.ts +13 -0
- package/core/koala-nest-http.module.js +37 -0
- package/core/koala-nest.module.d.ts +17 -0
- package/core/koala-nest.module.js +66 -0
- package/core/mapping/auto-mapping-class-context.d.ts +16 -0
- package/core/mapping/auto-mapping-class-context.js +18 -0
- package/core/mapping/auto-mapping-context.d.ts +11 -0
- package/core/mapping/auto-mapping-context.js +24 -0
- package/core/mapping/auto-mapping-list.d.ts +27 -0
- package/core/mapping/auto-mapping-list.js +94 -0
- package/core/mapping/auto-mapping-profile.d.ts +3 -0
- package/core/mapping/auto-mapping-profile.js +6 -0
- package/core/mapping/auto-mapping.decorator.d.ts +9 -0
- package/core/mapping/auto-mapping.decorator.js +27 -0
- package/core/mapping/auto-mapping.module.d.ts +5 -0
- package/core/mapping/auto-mapping.module.js +29 -0
- package/core/mapping/auto-mapping.service.d.ts +14 -0
- package/core/mapping/auto-mapping.service.js +140 -0
- package/core/mapping/create-map.d.ts +3 -0
- package/core/mapping/create-map.js +7 -0
- package/core/mapping/for-member.d.ts +5 -0
- package/core/mapping/for-member.js +8 -0
- package/core/request-overflow/request-handler.base.d.ts +4 -0
- package/core/request-overflow/request-handler.base.js +6 -0
- package/core/request-overflow/request-result.d.ts +15 -0
- package/core/request-overflow/request-result.js +37 -0
- package/core/request-overflow/request-validator.base.d.ts +7 -0
- package/core/request-overflow/request-validator.base.js +26 -0
- package/core/security/strategies/api-key.strategy.d.ts +16 -0
- package/core/security/strategies/api-key.strategy.js +31 -0
- package/core/utils/assing-object.d.ts +5 -0
- package/core/utils/assing-object.js +6 -0
- package/core/utils/env.config.d.ts +6 -0
- package/core/utils/env.config.js +18 -0
- package/core/utils/filter-request-params.d.ts +13 -0
- package/core/utils/filter-request-params.js +22 -0
- package/core/utils/find-on-list.d.ts +2 -0
- package/core/utils/find-on-list.js +13 -0
- package/core/utils/get-type-by-prop.d.ts +2 -0
- package/core/utils/get-type-by-prop.js +11 -0
- package/core/utils/instanciate-class-with-dependencies-injection.d.ts +2 -0
- package/core/utils/instanciate-class-with-dependencies-injection.js +10 -0
- package/core/utils/interfaces/icomparable.d.ts +5 -0
- package/core/utils/interfaces/icomparable.js +6 -0
- package/core/utils/list.d.ts +39 -0
- package/core/utils/list.js +168 -0
- package/core/utils/promise-all.d.ts +7 -0
- package/core/utils/promise-all.js +19 -0
- package/core/utils/set-mask-document-number.d.ts +1 -0
- package/core/utils/set-mask-document-number.js +13 -0
- package/core/validators/file-validator.d.ts +27 -0
- package/core/validators/file-validator.js +94 -0
- package/decorators/api-exclude-endpoint-diff-develop.decorator.d.ts +1 -0
- package/decorators/api-exclude-endpoint-diff-develop.decorator.js +9 -0
- package/decorators/api-property-enum.decorator.d.ts +8 -0
- package/decorators/api-property-enum.decorator.js +21 -0
- package/decorators/api-property-only-develop.decorator.d.ts +2 -0
- package/decorators/api-property-only-develop.decorator.js +9 -0
- package/decorators/cookies.decorator.d.ts +1 -0
- package/decorators/cookies.decorator.js +8 -0
- package/decorators/is-public.decorator.d.ts +2 -0
- package/decorators/is-public.decorator.js +7 -0
- package/decorators/upload.decorator.d.ts +1 -0
- package/decorators/upload.decorator.js +18 -0
- package/env/env.d.ts +25 -0
- package/env/env.js +14 -0
- package/env/env.module.d.ts +2 -0
- package/env/env.module.js +20 -0
- package/env/env.service.d.ts +7 -0
- package/env/env.service.js +28 -0
- package/filters/domain-errors.filter.d.ts +18 -0
- package/filters/domain-errors.filter.js +92 -0
- package/filters/global-exception.filter.d.ts +8 -0
- package/filters/global-exception.filter.js +68 -0
- package/filters/prisma-validation-exception.filter.d.ts +10 -0
- package/filters/prisma-validation-exception.filter.js +82 -0
- package/filters/zod-errors.filter.d.ts +9 -0
- package/filters/zod-errors.filter.js +60 -0
- package/package.json +4 -1
- package/services/logging/ilogging.service.d.ts +16 -0
- package/services/logging/ilogging.service.js +6 -0
- package/services/logging/logging.service.d.ts +4 -0
- package/services/logging/logging.service.js +20 -0
- package/services/redis/iredis.service.d.ts +6 -0
- package/services/redis/iredis.service.js +6 -0
- package/services/redis/redis.service.d.ts +14 -0
- package/services/redis/redis.service.js +65 -0
- package/services/redlock/ired-lock.service.d.ts +4 -0
- package/services/redlock/ired-lock.service.js +6 -0
- package/services/redlock/red-lock.service.d.ts +9 -0
- package/services/redlock/red-lock.service.js +46 -0
- package/test/koala-app-test-dependencies.d.ts +10 -0
- package/test/koala-app-test-dependencies.js +13 -0
- package/test/koala-app-test.d.ts +22 -0
- package/test/koala-app-test.js +77 -0
- package/test/repositories/in-memory-base.repository.d.ts +17 -0
- package/test/repositories/in-memory-base.repository.js +65 -0
- package/test/services/fake-logging.service.d.ts +4 -0
- package/test/services/fake-logging.service.js +9 -0
- package/test/services/fake-red-lock.service.d.ts +5 -0
- package/test/services/fake-red-lock.service.js +11 -0
- package/test/utils/create-e2e-database.d.ts +2 -0
- package/test/utils/create-e2e-database.js +47 -0
- package/test/utils/drop-e2e-database.d.ts +2 -0
- package/test/utils/drop-e2e-database.js +33 -0
- package/test/utils/wait-for.d.ts +1 -0
- package/test/utils/wait-for.js +21 -0
- package/tsconfig.lib.tsbuildinfo +1 -0
- package/CHANGELOG.md +0 -21
- package/src/core/backgroud-services/cron-service/cron-job.handler.base.ts +0 -66
- package/src/core/backgroud-services/cron-service/cron-job.handler.spec.ts +0 -38
- package/src/core/backgroud-services/event-service/event-class.ts +0 -5
- package/src/core/backgroud-services/event-service/event-handler.base.ts +0 -17
- package/src/core/backgroud-services/event-service/event-is-trigger.ts +0 -3
- package/src/core/backgroud-services/event-service/event-job.ts +0 -28
- package/src/core/backgroud-services/event-service/event-queue.spec.ts +0 -47
- package/src/core/backgroud-services/event-service/event-queue.ts +0 -107
- package/src/core/constants/query-params.ts +0 -7
- package/src/core/controllers/base.controller.ts +0 -9
- package/src/core/controllers/controller.decorator.ts +0 -10
- package/src/core/controllers/created-registre-response.base.ts +0 -17
- package/src/core/controllers/list-response.base.ts +0 -8
- package/src/core/controllers/pagination.request.ts +0 -41
- package/src/core/controllers/router-config.base.ts +0 -14
- package/src/core/controllers/schemas/boolean.schema.ts +0 -10
- package/src/core/controllers/schemas/document-number.schema.ts +0 -23
- package/src/core/controllers/schemas/email.schema.ts +0 -13
- package/src/core/controllers/schemas/list-query.schema.ts +0 -17
- package/src/core/controllers/schemas/native-enum.schema.ts +0 -34
- package/src/core/controllers/schemas/set-mask-document-number.schema.ts +0 -13
- package/src/core/database/entity.base.ts +0 -95
- package/src/core/database/entity.decorator.spec.ts +0 -71
- package/src/core/database/entity.decorator.ts +0 -39
- package/src/core/database/prisma-client-with-custom-transaction.interface.ts +0 -13
- package/src/core/database/prisma-resolver.ts +0 -99
- package/src/core/database/prisma-transactional-client.ts +0 -43
- package/src/core/database/prisma.service.ts +0 -136
- package/src/core/database/repository.base.ts +0 -548
- package/src/core/dtos/pagination.dto.ts +0 -35
- package/src/core/errors/bad-request.error.ts +0 -8
- package/src/core/errors/conflict.error.ts +0 -7
- package/src/core/errors/error.base.ts +0 -5
- package/src/core/errors/no-content.error.ts +0 -8
- package/src/core/errors/not-allowed.error.ts +0 -8
- package/src/core/errors/resource-not-found.error.ts +0 -8
- package/src/core/errors/user-already-exist.error.ts +0 -7
- package/src/core/errors/wrong-credentials.error.ts +0 -7
- package/src/core/health-check/health-check.controller.ts +0 -13
- package/src/core/health-check/health-check.module.ts +0 -7
- package/src/core/index.ts +0 -56
- package/src/core/koala-app.ts +0 -379
- package/src/core/koala-global-vars.ts +0 -8
- package/src/core/koala-nest-database.module.ts +0 -65
- package/src/core/koala-nest-http.module.ts +0 -44
- package/src/core/koala-nest.module.ts +0 -67
- package/src/core/mapping/auto-mapping-class-context.ts +0 -28
- package/src/core/mapping/auto-mapping-context.ts +0 -26
- package/src/core/mapping/auto-mapping-list.ts +0 -154
- package/src/core/mapping/auto-mapping-profile.ts +0 -3
- package/src/core/mapping/auto-mapping.decorator.ts +0 -54
- package/src/core/mapping/auto-mapping.module.ts +0 -17
- package/src/core/mapping/auto-mapping.service.ts +0 -187
- package/src/core/mapping/create-map.ts +0 -11
- package/src/core/mapping/for-member.ts +0 -16
- package/src/core/request-overflow/request-handler.base.ts +0 -8
- package/src/core/request-overflow/request-result.spec.ts +0 -23
- package/src/core/request-overflow/request-result.ts +0 -41
- package/src/core/request-overflow/request-validator.base.ts +0 -33
- package/src/core/security/strategies/api-key.strategy.ts +0 -45
- package/src/core/utils/assing-object.ts +0 -9
- package/src/core/utils/env.config.ts +0 -17
- package/src/core/utils/filter-request-params.ts +0 -23
- package/src/core/utils/find-on-list.ts +0 -18
- package/src/core/utils/get-type-by-prop.ts +0 -9
- package/src/core/utils/instanciate-class-with-dependencies-injection.ts +0 -12
- package/src/core/utils/interfaces/icomparable.ts +0 -6
- package/src/core/utils/list.spec.ts +0 -81
- package/src/core/utils/list.ts +0 -223
- package/src/core/utils/promise-all.ts +0 -24
- package/src/core/utils/set-mask-document-number.ts +0 -13
- package/src/core/validators/file-validator.ts +0 -113
- package/src/decorators/api-exclude-endpoint-diff-develop.decorator.ts +0 -15
- package/src/decorators/api-property-enum.decorator.ts +0 -58
- package/src/decorators/api-property-only-develop.decorator.ts +0 -6
- package/src/decorators/cookies.decorator.ts +0 -8
- package/src/decorators/is-public.decorator.ts +0 -5
- package/src/decorators/upload.decorator.ts +0 -31
- package/src/env/env.module.ts +0 -8
- package/src/env/env.service.ts +0 -12
- package/src/env/env.ts +0 -14
- package/src/filters/domain-errors.filter.ts +0 -97
- package/src/filters/global-exception.filter.ts +0 -60
- package/src/filters/prisma-validation-exception.filter.ts +0 -73
- package/src/filters/zod-errors.filter.ts +0 -48
- package/src/services/logging/ilogging.service.ts +0 -17
- package/src/services/logging/logging.service.ts +0 -10
- package/src/services/redis/iredis.service.ts +0 -11
- package/src/services/redis/redis.service.ts +0 -70
- package/src/services/redlock/ired-lock.service.ts +0 -4
- package/src/services/redlock/red-lock.service.ts +0 -36
- package/src/test/koala-app-test-dependencies.ts +0 -15
- package/src/test/koala-app-test.ts +0 -103
- package/src/test/repositories/in-memory-base.repository.ts +0 -90
- package/src/test/services/fake-logging.service.ts +0 -7
- package/src/test/services/fake-red-lock.service.ts +0 -11
- package/src/test/utils/create-e2e-database.ts +0 -55
- package/src/test/utils/drop-e2e-database.ts +0 -36
- package/src/test/utils/wait-for.ts +0 -31
- package/tsconfig.lib.json +0 -11
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.setPrismaClient = setPrismaClient;
|
|
4
|
+
exports.getPrismaClientClass = getPrismaClientClass;
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const fs = require("fs");
|
|
7
|
+
let cachedPrismaClient = null;
|
|
8
|
+
function findPrismaClient() {
|
|
9
|
+
const possiblePaths = [
|
|
10
|
+
path.join(process.cwd(), 'prisma/generated/client.js'),
|
|
11
|
+
path.join(__dirname, '../../../../../prisma/generated/client.js'),
|
|
12
|
+
path.join(process.cwd(), 'prisma/generated/client.ts'),
|
|
13
|
+
path.join(__dirname, '../../../../../prisma/generated/client.ts'),
|
|
14
|
+
...(require.main?.filename
|
|
15
|
+
? [
|
|
16
|
+
path.join(path.dirname(require.main.filename), '../prisma/generated/client.js'),
|
|
17
|
+
path.join(path.dirname(require.main.filename), '../prisma/generated/client.ts'),
|
|
18
|
+
]
|
|
19
|
+
: []),
|
|
20
|
+
];
|
|
21
|
+
for (const prismaPath of possiblePaths) {
|
|
22
|
+
if (fs.existsSync(prismaPath)) {
|
|
23
|
+
return prismaPath;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
async function resolvePrismaClient() {
|
|
29
|
+
if (cachedPrismaClient) {
|
|
30
|
+
return cachedPrismaClient;
|
|
31
|
+
}
|
|
32
|
+
const prismaPath = findPrismaClient();
|
|
33
|
+
if (!prismaPath) {
|
|
34
|
+
throw new Error(`
|
|
35
|
+
Não foi possível carregar o Prisma Client automaticamente.
|
|
36
|
+
|
|
37
|
+
Certifique-se de que você:
|
|
38
|
+
1. Executou 'bunx prisma generate' no seu projeto
|
|
39
|
+
2. Tem a pasta 'prisma/generated/client' no seu projeto
|
|
40
|
+
3. A lib @koalarx/nest está instalada como dependência
|
|
41
|
+
|
|
42
|
+
Se o problema persistir, você pode registrar manualmente o Prisma Client:
|
|
43
|
+
|
|
44
|
+
import { setPrismaClient } from '@koalarx/nest'
|
|
45
|
+
import { PrismaClient } from './prisma/generated/client'
|
|
46
|
+
|
|
47
|
+
setPrismaClient(PrismaClient)
|
|
48
|
+
`.trim());
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
const module = await Promise.resolve(`${prismaPath}`).then(s => require(s));
|
|
52
|
+
cachedPrismaClient = module.PrismaClient || module.default || module;
|
|
53
|
+
return cachedPrismaClient;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
throw new Error(`
|
|
57
|
+
Erro ao carregar o Prisma Client de ${prismaPath}:
|
|
58
|
+
${error instanceof Error ? error.message : String(error)}
|
|
59
|
+
|
|
60
|
+
Certifique-se de que 'bunx prisma generate' foi executado com sucesso.
|
|
61
|
+
`.trim());
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
let manualPrismaClient = null;
|
|
65
|
+
function setPrismaClient(prismaClientClass) {
|
|
66
|
+
manualPrismaClient = prismaClientClass;
|
|
67
|
+
cachedPrismaClient = null;
|
|
68
|
+
}
|
|
69
|
+
function getPrismaClientClass() {
|
|
70
|
+
if (manualPrismaClient) {
|
|
71
|
+
return manualPrismaClient;
|
|
72
|
+
}
|
|
73
|
+
return resolvePrismaClient();
|
|
74
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Prisma } from 'prisma/generated/client';
|
|
2
|
+
export declare abstract class PrismaTransactionalClient {
|
|
3
|
+
protected readonly transactionalClient: Prisma.TransactionClient;
|
|
4
|
+
[key: symbol]: any;
|
|
5
|
+
constructor(transactionalClient: Prisma.TransactionClient);
|
|
6
|
+
withTransaction<F>(fn: (prisma: Prisma.TransactionClient) => Promise<F>): Promise<F>;
|
|
7
|
+
$executeRaw(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): Prisma.PrismaPromise<number>;
|
|
8
|
+
$executeRawUnsafe(query: string, ...values: any[]): Prisma.PrismaPromise<number>;
|
|
9
|
+
$queryRaw<T = unknown>(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): Prisma.PrismaPromise<T>;
|
|
10
|
+
$queryRawUnsafe<T = unknown>(query: string, ...values: any[]): Prisma.PrismaPromise<T>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrismaTransactionalClient = void 0;
|
|
4
|
+
class PrismaTransactionalClient {
|
|
5
|
+
transactionalClient;
|
|
6
|
+
constructor(transactionalClient) {
|
|
7
|
+
this.transactionalClient = transactionalClient;
|
|
8
|
+
}
|
|
9
|
+
async withTransaction(fn) {
|
|
10
|
+
return await fn(this.transactionalClient);
|
|
11
|
+
}
|
|
12
|
+
$executeRaw(query, ...values) {
|
|
13
|
+
return this.transactionalClient.$executeRaw(query, ...values);
|
|
14
|
+
}
|
|
15
|
+
$executeRawUnsafe(query, ...values) {
|
|
16
|
+
return this.transactionalClient.$executeRawUnsafe(query, ...values);
|
|
17
|
+
}
|
|
18
|
+
$queryRaw(query, ...values) {
|
|
19
|
+
return this.transactionalClient.$queryRaw(query, ...values);
|
|
20
|
+
}
|
|
21
|
+
$queryRawUnsafe(query, ...values) {
|
|
22
|
+
return this.transactionalClient.$queryRawUnsafe(query, ...values);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.PrismaTransactionalClient = PrismaTransactionalClient;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { EnvService } from '@koalarx/nest/env/env.service';
|
|
2
|
+
import { OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
|
3
|
+
import { PrismaClientWithCustomTransaction } from './prisma-client-with-custom-transaction.interface';
|
|
4
|
+
import type { Prisma } from 'prisma/generated/client';
|
|
5
|
+
export declare function setPrismaClientOptions(options: Prisma.PrismaClientOptions): void;
|
|
6
|
+
export declare class PrismaService implements OnModuleInit, OnModuleDestroy, PrismaClientWithCustomTransaction {
|
|
7
|
+
private readonly env;
|
|
8
|
+
private prismaInstance;
|
|
9
|
+
constructor(env: EnvService);
|
|
10
|
+
initialize(): Promise<void>;
|
|
11
|
+
onModuleInit(): Promise<any>;
|
|
12
|
+
onModuleDestroy(): any;
|
|
13
|
+
withTransaction<F>(fn: (prisma: Prisma.TransactionClient) => Promise<F>, options?: {
|
|
14
|
+
maxWait?: number;
|
|
15
|
+
timeout?: number;
|
|
16
|
+
isolationLevel?: Prisma.TransactionIsolationLevel;
|
|
17
|
+
}): Promise<F>;
|
|
18
|
+
[Symbol.toPrimitive](): any;
|
|
19
|
+
toString(): string;
|
|
20
|
+
get $connect(): any;
|
|
21
|
+
get $disconnect(): any;
|
|
22
|
+
get $transaction(): any;
|
|
23
|
+
get $on(): any;
|
|
24
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
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.PrismaService = void 0;
|
|
13
|
+
exports.setPrismaClientOptions = setPrismaClientOptions;
|
|
14
|
+
const env_service_1 = require("../../env/env.service");
|
|
15
|
+
const common_1 = require("@nestjs/common");
|
|
16
|
+
const prisma_resolver_1 = require("./prisma-resolver");
|
|
17
|
+
let globalPrismaOptions = {};
|
|
18
|
+
function setPrismaClientOptions(options) {
|
|
19
|
+
globalPrismaOptions = options;
|
|
20
|
+
}
|
|
21
|
+
let PrismaClientClass = null;
|
|
22
|
+
async function loadPrismaClient() {
|
|
23
|
+
if (!PrismaClientClass) {
|
|
24
|
+
PrismaClientClass = await (0, prisma_resolver_1.getPrismaClientClass)();
|
|
25
|
+
}
|
|
26
|
+
return PrismaClientClass;
|
|
27
|
+
}
|
|
28
|
+
let PrismaService = class PrismaService {
|
|
29
|
+
env;
|
|
30
|
+
prismaInstance;
|
|
31
|
+
constructor(env) {
|
|
32
|
+
this.env = env;
|
|
33
|
+
return new Proxy(this, {
|
|
34
|
+
get: (target, prop, receiver) => {
|
|
35
|
+
if (prop in target) {
|
|
36
|
+
const value = Reflect.get(target, prop, receiver);
|
|
37
|
+
if (typeof value === 'function') {
|
|
38
|
+
return value.bind(target);
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
if (target.prismaInstance && typeof prop === 'string') {
|
|
43
|
+
const value = target.prismaInstance[prop];
|
|
44
|
+
if (typeof value === 'function') {
|
|
45
|
+
return value.bind(target.prismaInstance);
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
return Reflect.get(target, prop, receiver);
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async initialize() {
|
|
54
|
+
const PrismaClientType = await loadPrismaClient();
|
|
55
|
+
this.prismaInstance = new PrismaClientType({
|
|
56
|
+
log: [{ emit: 'event', level: 'query' }],
|
|
57
|
+
...globalPrismaOptions,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async onModuleInit() {
|
|
61
|
+
await this.initialize();
|
|
62
|
+
if (this.env.get('PRISMA_QUERY_LOG')) {
|
|
63
|
+
this.prismaInstance?.$on?.('query', async (e) => {
|
|
64
|
+
console.log(`${e.query} ${e.params}`);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return this.prismaInstance?.$connect?.();
|
|
68
|
+
}
|
|
69
|
+
onModuleDestroy() {
|
|
70
|
+
return this.prismaInstance?.$disconnect?.();
|
|
71
|
+
}
|
|
72
|
+
async withTransaction(fn, options) {
|
|
73
|
+
return this.prismaInstance?.$transaction?.(fn, options ?? {
|
|
74
|
+
maxWait: 20000,
|
|
75
|
+
timeout: 20000,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
[Symbol.toPrimitive]() {
|
|
79
|
+
return this.prismaInstance;
|
|
80
|
+
}
|
|
81
|
+
toString() {
|
|
82
|
+
return '[PrismaService]';
|
|
83
|
+
}
|
|
84
|
+
get $connect() {
|
|
85
|
+
return this.prismaInstance?.$connect?.bind(this.prismaInstance);
|
|
86
|
+
}
|
|
87
|
+
get $disconnect() {
|
|
88
|
+
return this.prismaInstance?.$disconnect?.bind(this.prismaInstance);
|
|
89
|
+
}
|
|
90
|
+
get $transaction() {
|
|
91
|
+
return this.prismaInstance?.$transaction?.bind(this.prismaInstance);
|
|
92
|
+
}
|
|
93
|
+
get $on() {
|
|
94
|
+
return this.prismaInstance?.$on?.bind(this.prismaInstance);
|
|
95
|
+
}
|
|
96
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
97
|
+
return this.prismaInstance;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
exports.PrismaService = PrismaService;
|
|
101
|
+
exports.PrismaService = PrismaService = __decorate([
|
|
102
|
+
(0, common_1.Injectable)(),
|
|
103
|
+
__metadata("design:paramtypes", [env_service_1.EnvService])
|
|
104
|
+
], PrismaService);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Type } from '@nestjs/common';
|
|
2
|
+
import { ListResponse } from '..';
|
|
3
|
+
import { PaginationDto } from '../dtos/pagination.dto';
|
|
4
|
+
import { IComparableId } from '../utils/interfaces/icomparable';
|
|
5
|
+
import { List } from '../utils/list';
|
|
6
|
+
import { EntityBase } from './entity.base';
|
|
7
|
+
import { PrismaTransactionalClient } from './prisma-transactional-client';
|
|
8
|
+
type RepositoryInclude<TEntity> = Omit<{
|
|
9
|
+
[K in keyof TEntity as TEntity[K] extends Function ? never : K]?: boolean | (TEntity[K] extends List<infer U> ? RepositoryInclude<U> : RepositoryInclude<TEntity[K]>);
|
|
10
|
+
}, '_id' | '_action'>;
|
|
11
|
+
interface RepositoryInitProps<TEntity extends EntityBase<TEntity>, TContext extends PrismaTransactionalClient> {
|
|
12
|
+
context: TContext;
|
|
13
|
+
modelName: Type<TEntity>;
|
|
14
|
+
transactionContext?: Type<TContext>;
|
|
15
|
+
include?: RepositoryInclude<TEntity>;
|
|
16
|
+
}
|
|
17
|
+
export declare abstract class RepositoryBase<TEntity extends EntityBase<TEntity>, TContext extends PrismaTransactionalClient = PrismaTransactionalClient, TModelKey extends keyof TContext = keyof TContext> {
|
|
18
|
+
protected _context: TContext;
|
|
19
|
+
private readonly _modelName;
|
|
20
|
+
private readonly _include?;
|
|
21
|
+
constructor({ context, modelName, include, }: RepositoryInitProps<TEntity, TContext>);
|
|
22
|
+
private listRelationEntities;
|
|
23
|
+
private listToRelationActionList;
|
|
24
|
+
private entityToPrisma;
|
|
25
|
+
private findManySchema;
|
|
26
|
+
private createEntity;
|
|
27
|
+
private orphanRemoval;
|
|
28
|
+
private getIdPropName;
|
|
29
|
+
private getInclude;
|
|
30
|
+
private getPropNameFromEntitySource;
|
|
31
|
+
private persistRelations;
|
|
32
|
+
protected context(transactionalClient?: TContext): TContext[TModelKey];
|
|
33
|
+
protected findById(id: IComparableId): Promise<TEntity | null>;
|
|
34
|
+
protected findFirst<T>(where: T): Promise<TEntity | null>;
|
|
35
|
+
protected findUnique<T>(where: T): Promise<TEntity | null>;
|
|
36
|
+
protected findMany<T>(where: T, pagination?: PaginationDto): Promise<TEntity[]>;
|
|
37
|
+
protected findManyAndCount<T>(where: T, pagination?: PaginationDto): Promise<ListResponse<TEntity>>;
|
|
38
|
+
protected saveChanges<TWhere = any>(entity: TEntity, updateWhere?: TWhere): Promise<TEntity>;
|
|
39
|
+
protected saveMany<TWhere = any>(entities: TEntity[], updateWhere?: TWhere): Promise<void>;
|
|
40
|
+
protected remove<TWhere = any>(where: TWhere, notCascadeEntityProps?: Array<keyof TEntity>, externalServices?: Promise<any>): Promise<any>;
|
|
41
|
+
protected removeMany<TWhere = any>(where: TWhere, notCascadeEntityProps?: Array<keyof TEntity>, externalServices?: Promise<any>): Promise<void>;
|
|
42
|
+
withTransaction(fn: (prisma: TContext) => Promise<any>): Promise<any>;
|
|
43
|
+
}
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RepositoryBase = void 0;
|
|
4
|
+
const KlString_1 = require("@koalarx/utils/KlString");
|
|
5
|
+
const pagination_dto_1 = require("../dtos/pagination.dto");
|
|
6
|
+
const koala_global_vars_1 = require("../koala-global-vars");
|
|
7
|
+
const list_1 = require("../utils/list");
|
|
8
|
+
const entity_base_1 = require("./entity.base");
|
|
9
|
+
const auto_mapping_list_1 = require("../mapping/auto-mapping-list");
|
|
10
|
+
class RepositoryBase {
|
|
11
|
+
_context;
|
|
12
|
+
_modelName;
|
|
13
|
+
_include;
|
|
14
|
+
constructor({ context, modelName, include, }) {
|
|
15
|
+
this._context = context;
|
|
16
|
+
this._modelName = modelName;
|
|
17
|
+
this._include = include;
|
|
18
|
+
}
|
|
19
|
+
listRelationEntities(entity) {
|
|
20
|
+
const relationEntities = [];
|
|
21
|
+
Object.keys(entity).forEach((key) => {
|
|
22
|
+
if (entity[key] instanceof list_1.List) {
|
|
23
|
+
const list = entity[key];
|
|
24
|
+
list.toArray('added').forEach((item) => {
|
|
25
|
+
relationEntities.push(item);
|
|
26
|
+
relationEntities.push(...this.listRelationEntities(item));
|
|
27
|
+
});
|
|
28
|
+
list.toArray('updated').forEach((item) => {
|
|
29
|
+
relationEntities.push(item);
|
|
30
|
+
relationEntities.push(...this.listRelationEntities(item));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
else if (entity[key] instanceof entity_base_1.EntityBase) {
|
|
34
|
+
relationEntities.push(entity[key]);
|
|
35
|
+
relationEntities.push(...this.listRelationEntities(entity[key]));
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
return relationEntities;
|
|
39
|
+
}
|
|
40
|
+
listToRelationActionList(entity) {
|
|
41
|
+
const relationCreates = [];
|
|
42
|
+
const relationUpdates = [];
|
|
43
|
+
const relationDeletes = [];
|
|
44
|
+
Object.keys(entity).forEach((key) => {
|
|
45
|
+
if (entity[key] instanceof list_1.List) {
|
|
46
|
+
const list = entity[key];
|
|
47
|
+
const entityInstance = list.entityType;
|
|
48
|
+
const modelName = entityInstance.name;
|
|
49
|
+
const parentModelName = entity.constructor.name;
|
|
50
|
+
if (modelName) {
|
|
51
|
+
list.toArray('removed').forEach((item) => {
|
|
52
|
+
relationDeletes.push({
|
|
53
|
+
modelName: (0, KlString_1.toCamelCase)(modelName),
|
|
54
|
+
entityInstance,
|
|
55
|
+
schema: { where: { id: item._id } },
|
|
56
|
+
relations: [],
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
list.toArray('added').forEach((item) => {
|
|
60
|
+
relationCreates.push({
|
|
61
|
+
modelName: (0, KlString_1.toCamelCase)(modelName),
|
|
62
|
+
entityInstance,
|
|
63
|
+
schema: {
|
|
64
|
+
data: {
|
|
65
|
+
...this.entityToPrisma(item),
|
|
66
|
+
[(0, KlString_1.toCamelCase)(parentModelName)]: {
|
|
67
|
+
connect: {
|
|
68
|
+
[this.getIdPropName(entity)]: entity[this.getIdPropName(entity)],
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
relations: this.listRelationEntities(item),
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
list.toArray('updated').forEach((item) => {
|
|
77
|
+
relationUpdates.push({
|
|
78
|
+
modelName: (0, KlString_1.toCamelCase)(modelName),
|
|
79
|
+
entityInstance,
|
|
80
|
+
schema: {
|
|
81
|
+
where: { id: item._id },
|
|
82
|
+
data: this.entityToPrisma(item),
|
|
83
|
+
},
|
|
84
|
+
relations: this.listRelationEntities(item),
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
return { relationCreates, relationUpdates, relationDeletes };
|
|
91
|
+
}
|
|
92
|
+
entityToPrisma(entity) {
|
|
93
|
+
const prismaSchema = {};
|
|
94
|
+
Object.keys(entity)
|
|
95
|
+
.filter((key) => !['id', '_id', '_action'].includes(key))
|
|
96
|
+
.filter((key) => !(entity[key] instanceof Function || entity[key] instanceof list_1.List))
|
|
97
|
+
.forEach((key) => {
|
|
98
|
+
if (entity[key] instanceof entity_base_1.EntityBase) {
|
|
99
|
+
if (entity[key]._action === entity_base_1.EntityActionType.create) {
|
|
100
|
+
if (entity[key][this.getIdPropName(entity)]) {
|
|
101
|
+
prismaSchema[key] = {
|
|
102
|
+
connectOrCreate: {
|
|
103
|
+
where: {
|
|
104
|
+
[this.getIdPropName(entity)]: entity[key][this.getIdPropName(entity)],
|
|
105
|
+
},
|
|
106
|
+
create: this.entityToPrisma(entity[key]),
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
prismaSchema[key] = {
|
|
112
|
+
create: this.entityToPrisma(entity[key]),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
prismaSchema[key] = {
|
|
118
|
+
update: this.entityToPrisma(entity[key]),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
prismaSchema[key] = entity[key];
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
return prismaSchema;
|
|
127
|
+
}
|
|
128
|
+
findManySchema(where, pagination) {
|
|
129
|
+
return {
|
|
130
|
+
include: this.getInclude(),
|
|
131
|
+
where,
|
|
132
|
+
orderBy: pagination?.generateOrderBy(),
|
|
133
|
+
skip: pagination?.skip(),
|
|
134
|
+
take: (pagination?.limit ?? 0) > 0 ? pagination?.limit : undefined,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
createEntity(data, entityClass) {
|
|
138
|
+
const entity = new (entityClass || this._modelName)();
|
|
139
|
+
entity._action = entity_base_1.EntityActionType.update;
|
|
140
|
+
entity.automap(data);
|
|
141
|
+
return entity;
|
|
142
|
+
}
|
|
143
|
+
orphanRemoval(client, entity) {
|
|
144
|
+
const where = {};
|
|
145
|
+
Object.keys(entity)
|
|
146
|
+
.filter((key) => key === 'id' || key.includes('Id'))
|
|
147
|
+
.forEach((key) => (where[key] = entity[key]));
|
|
148
|
+
return client[(0, KlString_1.toCamelCase)(entity.constructor.name)].delete({ where });
|
|
149
|
+
}
|
|
150
|
+
getIdPropName(entity) {
|
|
151
|
+
return (Reflect.getMetadata('entity:id', entity ? entity.constructor.prototype : this._modelName.prototype) ?? 'id');
|
|
152
|
+
}
|
|
153
|
+
getInclude(include) {
|
|
154
|
+
include = include ?? this._include ?? {};
|
|
155
|
+
const result = {};
|
|
156
|
+
Object.keys(include).forEach((key) => {
|
|
157
|
+
if (typeof include[key] === 'boolean') {
|
|
158
|
+
result[key] = include[key];
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
result[key] = {
|
|
162
|
+
include: this.getInclude(include[key]),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
getPropNameFromEntitySource(source, entity) {
|
|
169
|
+
return Object.keys(source).find((key) => {
|
|
170
|
+
const propDefinitions = auto_mapping_list_1.AutoMappingList.getPropDefinitions(source.constructor, key);
|
|
171
|
+
if (propDefinitions) {
|
|
172
|
+
if (propDefinitions.type === entity.name) {
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
else if (source[key] instanceof list_1.List) {
|
|
176
|
+
const list = source[key];
|
|
177
|
+
return list.entityType?.name === entity.name;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return false;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
persistRelations(transaction, entity) {
|
|
184
|
+
const { relationCreates, relationUpdates, relationDeletes } = this.listToRelationActionList(entity);
|
|
185
|
+
return Promise.all([
|
|
186
|
+
...relationCreates.map((relationCreate) => transaction[relationCreate.modelName]
|
|
187
|
+
.create(relationCreate.schema)
|
|
188
|
+
.then((response) => {
|
|
189
|
+
return Promise.all(relationCreate.relations.map((relation) => {
|
|
190
|
+
const relationPropName = this.getPropNameFromEntitySource(relation, relationCreate.entityInstance);
|
|
191
|
+
if (!relationPropName) {
|
|
192
|
+
throw new Error(`Propname not found for relation entity ${relation.constructor.name} on entity ${relationCreate.entityInstance.constructor.name}`);
|
|
193
|
+
}
|
|
194
|
+
const relationEntity = this.createEntity(response, relationCreate.entityInstance);
|
|
195
|
+
relationEntity._action = entity_base_1.EntityActionType.create;
|
|
196
|
+
relation[relationPropName] = relationEntity;
|
|
197
|
+
return transaction[(0, KlString_1.toCamelCase)(relation.constructor.name)]
|
|
198
|
+
.create({
|
|
199
|
+
data: this.entityToPrisma(relation),
|
|
200
|
+
})
|
|
201
|
+
.then((response) => {
|
|
202
|
+
entity[this.getIdPropName(relation)] =
|
|
203
|
+
response[this.getIdPropName(relation)];
|
|
204
|
+
return this.persistRelations(transaction, relation);
|
|
205
|
+
});
|
|
206
|
+
}));
|
|
207
|
+
})),
|
|
208
|
+
...relationUpdates.map((relation) => transaction[relation.modelName].update(relation.schema)),
|
|
209
|
+
...relationDeletes.map((relation) => this.removeMany(relation.schema)),
|
|
210
|
+
]);
|
|
211
|
+
}
|
|
212
|
+
context(transactionalClient) {
|
|
213
|
+
const modelName = this._modelName.name;
|
|
214
|
+
if (!modelName)
|
|
215
|
+
throw new Error('modelName não informado no contrutor do repositorio');
|
|
216
|
+
const contextKey = (0, KlString_1.toCamelCase)(modelName);
|
|
217
|
+
if (transactionalClient) {
|
|
218
|
+
return transactionalClient[contextKey];
|
|
219
|
+
}
|
|
220
|
+
return this._context[contextKey];
|
|
221
|
+
}
|
|
222
|
+
async findById(id) {
|
|
223
|
+
return this.context()
|
|
224
|
+
.findFirst({
|
|
225
|
+
include: this.getInclude(),
|
|
226
|
+
where: { [this.getIdPropName()]: id },
|
|
227
|
+
})
|
|
228
|
+
.then((response) => {
|
|
229
|
+
if (response) {
|
|
230
|
+
return this.createEntity(response);
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
async findFirst(where) {
|
|
236
|
+
return this.context()
|
|
237
|
+
.findFirst({
|
|
238
|
+
include: this.getInclude(),
|
|
239
|
+
where,
|
|
240
|
+
})
|
|
241
|
+
.then((response) => {
|
|
242
|
+
if (response) {
|
|
243
|
+
return this.createEntity(response);
|
|
244
|
+
}
|
|
245
|
+
return null;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
async findUnique(where) {
|
|
249
|
+
return this.context()
|
|
250
|
+
.findUnique({
|
|
251
|
+
include: this.getInclude(),
|
|
252
|
+
where,
|
|
253
|
+
})
|
|
254
|
+
.then((response) => {
|
|
255
|
+
if (response) {
|
|
256
|
+
return this.createEntity(response);
|
|
257
|
+
}
|
|
258
|
+
return null;
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
async findMany(where, pagination) {
|
|
262
|
+
return this.context()
|
|
263
|
+
.findMany(this.findManySchema(where, pagination))
|
|
264
|
+
.then((result) => result.map((response) => this.createEntity(response)));
|
|
265
|
+
}
|
|
266
|
+
async findManyAndCount(where, pagination) {
|
|
267
|
+
const count = await this.context().count({ where });
|
|
268
|
+
if (count > 0) {
|
|
269
|
+
const items = await this.findMany(where, Object.assign(new pagination_dto_1.PaginationDto(), pagination));
|
|
270
|
+
return { items, count };
|
|
271
|
+
}
|
|
272
|
+
return { items: [], count };
|
|
273
|
+
}
|
|
274
|
+
async saveChanges(entity, updateWhere) {
|
|
275
|
+
const prismaEntity = this.entityToPrisma(entity);
|
|
276
|
+
if (entity._action === entity_base_1.EntityActionType.create) {
|
|
277
|
+
return this.withTransaction((client) => this.context(client)
|
|
278
|
+
.create({
|
|
279
|
+
data: prismaEntity,
|
|
280
|
+
include: this.getInclude(),
|
|
281
|
+
})
|
|
282
|
+
.then((response) => {
|
|
283
|
+
entity[this.getIdPropName()] = response[this.getIdPropName()];
|
|
284
|
+
return this.persistRelations(client, entity).then(() => entity);
|
|
285
|
+
}));
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
const where = updateWhere ?? { id: entity._id };
|
|
289
|
+
return this.withTransaction((client) => this.context(client)
|
|
290
|
+
.update({
|
|
291
|
+
where,
|
|
292
|
+
data: prismaEntity,
|
|
293
|
+
})
|
|
294
|
+
.then(() => this.persistRelations(client, entity))).then(() => this.findUnique(where));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
async saveMany(entities, updateWhere) {
|
|
298
|
+
await this.withTransaction(async (client) => {
|
|
299
|
+
const prismaEntities = entities.map((entity) => this.entityToPrisma(entity));
|
|
300
|
+
return Promise.all([
|
|
301
|
+
this.context(client).createMany({
|
|
302
|
+
data: prismaEntities,
|
|
303
|
+
skipDuplicates: true,
|
|
304
|
+
}),
|
|
305
|
+
...entities
|
|
306
|
+
.filter((entity) => !!entity._id)
|
|
307
|
+
.map((entity) => this.context(client).update({
|
|
308
|
+
data: entity,
|
|
309
|
+
where: updateWhere ?? { id: entity._id },
|
|
310
|
+
})),
|
|
311
|
+
]);
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
async remove(where, notCascadeEntityProps, externalServices) {
|
|
315
|
+
const entity = await this.findUnique(where);
|
|
316
|
+
if (!entity) {
|
|
317
|
+
throw new Error(`Entity not found for where: ${JSON.stringify(where)}`);
|
|
318
|
+
}
|
|
319
|
+
const relationEntity = [];
|
|
320
|
+
Object.keys(entity).forEach((key) => {
|
|
321
|
+
if (entity[key] instanceof entity_base_1.EntityBase &&
|
|
322
|
+
!notCascadeEntityProps?.includes(key)) {
|
|
323
|
+
relationEntity.push(entity[key]);
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
return this.withTransaction((client) => (externalServices
|
|
327
|
+
? externalServices.then(() => client)
|
|
328
|
+
: Promise.resolve(client)).then((client) => this.context(client)
|
|
329
|
+
.delete({ where })
|
|
330
|
+
.then((response) => Promise.all(relationEntity.map((entity) => this.orphanRemoval(client, entity))).then(() => response))));
|
|
331
|
+
}
|
|
332
|
+
async removeMany(where, notCascadeEntityProps, externalServices) {
|
|
333
|
+
const entities = await this.findMany(where);
|
|
334
|
+
if (entities.length === 0) {
|
|
335
|
+
throw new Error(`Entities not found for where: ${JSON.stringify(where)}`);
|
|
336
|
+
}
|
|
337
|
+
return this.withTransaction((client) => (externalServices
|
|
338
|
+
? externalServices.then(() => client)
|
|
339
|
+
: Promise.resolve(client)).then(async (client) => {
|
|
340
|
+
const relationEntity = [];
|
|
341
|
+
for (const entity of entities) {
|
|
342
|
+
Object.keys(entity).forEach((key) => {
|
|
343
|
+
if (entity[key] instanceof entity_base_1.EntityBase &&
|
|
344
|
+
!notCascadeEntityProps?.includes(key)) {
|
|
345
|
+
relationEntity.push(entity[key]);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
return this.context(client)
|
|
350
|
+
.deleteMany({ where })
|
|
351
|
+
.then((response) => Promise.all(relationEntity.map((entity) => this.orphanRemoval(client, entity))).then(() => response));
|
|
352
|
+
}));
|
|
353
|
+
}
|
|
354
|
+
withTransaction(fn) {
|
|
355
|
+
return this._context.withTransaction(async (client) => {
|
|
356
|
+
return fn(new koala_global_vars_1.KoalaGlobalVars.dbTransactionContext(client));
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
exports.RepositoryBase = RepositoryBase;
|