@koalarx/nest 1.18.3 → 1.18.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.
@@ -0,0 +1,2 @@
1
+ export declare function setPrismaClient(prismaClientClass: any): void;
2
+ export declare function getPrismaClientClass(): any;
@@ -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
+ }
@@ -1,17 +1,25 @@
1
1
  import { EnvService } from '@koalarx/nest/env/env.service';
2
2
  import { OnModuleDestroy, OnModuleInit } from '@nestjs/common';
3
3
  import { PrismaClientWithCustomTransaction } from './prisma-client-with-custom-transaction.interface';
4
- import { Prisma, PrismaClient } from 'prisma/generated/client';
5
- import { PrismaClientOptions } from 'prisma/generated/internal/prismaNamespace';
4
+ import type { Prisma } from 'prisma/generated/client';
5
+ import type { PrismaClientOptions } from 'prisma/generated/internal/prismaNamespace';
6
6
  export declare function setPrismaClientOptions(options: PrismaClientOptions): void;
7
- export declare class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy, PrismaClientWithCustomTransaction {
7
+ export declare class PrismaService implements OnModuleInit, OnModuleDestroy, PrismaClientWithCustomTransaction {
8
8
  private readonly env;
9
+ private prismaInstance;
9
10
  constructor(env: EnvService);
10
- onModuleInit(): Promise<void>;
11
- onModuleDestroy(): Promise<void>;
11
+ initialize(): Promise<void>;
12
+ onModuleInit(): Promise<any>;
13
+ onModuleDestroy(): any;
12
14
  withTransaction<F>(fn: (prisma: Prisma.TransactionClient) => Promise<F>, options?: {
13
15
  maxWait?: number;
14
16
  timeout?: number;
15
17
  isolationLevel?: Prisma.TransactionIsolationLevel;
16
18
  }): Promise<F>;
19
+ [Symbol.toPrimitive](): any;
20
+ toString(): string;
21
+ get $connect(): any;
22
+ get $disconnect(): any;
23
+ get $transaction(): any;
24
+ get $on(): any;
17
25
  }
@@ -13,37 +13,89 @@ exports.PrismaService = void 0;
13
13
  exports.setPrismaClientOptions = setPrismaClientOptions;
14
14
  const env_service_1 = require("../../env/env.service");
15
15
  const common_1 = require("@nestjs/common");
16
- const client_1 = require("../../../../../prisma/generated/client");
16
+ const prisma_resolver_1 = require("./prisma-resolver");
17
17
  let globalPrismaOptions = {};
18
18
  function setPrismaClientOptions(options) {
19
19
  globalPrismaOptions = options;
20
20
  }
21
- let PrismaService = class PrismaService extends client_1.PrismaClient {
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 {
22
29
  env;
30
+ prismaInstance;
23
31
  constructor(env) {
24
- super({
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({
25
56
  log: [{ emit: 'event', level: 'query' }],
26
57
  ...globalPrismaOptions,
27
58
  });
28
- this.env = env;
29
59
  }
30
60
  async onModuleInit() {
61
+ await this.initialize();
31
62
  if (this.env.get('PRISMA_QUERY_LOG')) {
32
- this.$on('query', async (e) => {
63
+ this.prismaInstance?.$on?.('query', async (e) => {
33
64
  console.log(`${e.query} ${e.params}`);
34
65
  });
35
66
  }
36
- return this.$connect();
67
+ return this.prismaInstance?.$connect?.();
37
68
  }
38
69
  onModuleDestroy() {
39
- return this.$disconnect();
70
+ return this.prismaInstance?.$disconnect?.();
40
71
  }
41
- withTransaction(fn, options) {
42
- return this.$transaction(fn, options ?? {
72
+ async withTransaction(fn, options) {
73
+ return this.prismaInstance?.$transaction?.(fn, options ?? {
43
74
  maxWait: 20000,
44
75
  timeout: 20000,
45
76
  });
46
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
+ }
47
99
  };
48
100
  exports.PrismaService = PrismaService;
49
101
  exports.PrismaService = PrismaService = __decorate([
package/core/index.d.ts CHANGED
@@ -14,3 +14,5 @@ export type FileResponse = {
14
14
  base64: string;
15
15
  };
16
16
  export type QueryDirectionType = 'asc' | 'desc';
17
+ export { setPrismaClient } from './database/prisma-resolver';
18
+ export { setPrismaClientOptions } from './database/prisma.service';
package/core/index.js CHANGED
@@ -1,2 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setPrismaClientOptions = exports.setPrismaClient = void 0;
4
+ var prisma_resolver_1 = require("./database/prisma-resolver");
5
+ Object.defineProperty(exports, "setPrismaClient", { enumerable: true, get: function () { return prisma_resolver_1.setPrismaClient; } });
6
+ var prisma_service_1 = require("./database/prisma.service");
7
+ Object.defineProperty(exports, "setPrismaClientOptions", { enumerable: true, get: function () { return prisma_service_1.setPrismaClientOptions; } });
@@ -42,6 +42,8 @@ export declare class KoalaApp {
42
42
  private _ngrokKey;
43
43
  private _ngrokUrl;
44
44
  constructor(app: INestApplication<any>);
45
+ private showListeningMessage;
46
+ private startJobs;
45
47
  addGlobalGuard(Guard: Type<CanActivate>): this;
46
48
  addCronJob(job: CronJobClass): this;
47
49
  addEventJob(eventJob: EventJobClass): this;
@@ -58,6 +60,5 @@ export declare class KoalaApp {
58
60
  build(): Promise<INestApplication<any>>;
59
61
  serve(host?: string): Promise<void>;
60
62
  buildAndServe(host?: string): Promise<void>;
61
- private showListeningMessage;
62
63
  }
63
64
  export {};
package/core/koala-app.js CHANGED
@@ -16,6 +16,7 @@ const ilogging_service_1 = require("../services/logging/ilogging.service");
16
16
  const koala_global_vars_1 = require("./koala-global-vars");
17
17
  const env_config_1 = require("./utils/env.config");
18
18
  const instanciate_class_with_dependencies_injection_1 = require("./utils/instanciate-class-with-dependencies-injection");
19
+ const utils_1 = require("@koalarx/utils");
19
20
  class KoalaApp {
20
21
  app;
21
22
  _globalExceptionFilter;
@@ -39,6 +40,32 @@ class KoalaApp {
39
40
  this._domainExceptionFilter = new domain_errors_filter_1.DomainErrorsFilter(loggingService);
40
41
  this._zodExceptionFilter = new zod_errors_filter_1.ZodErrorsFilter(loggingService);
41
42
  }
43
+ showListeningMessage(port, host = 'localhost') {
44
+ const envService = this.app.get(env_service_1.EnvService);
45
+ console.log('------------------------------');
46
+ if (this._apiReferenceEndpoint) {
47
+ consola.info('API Reference:', `http://${host}:${port}${this._apiReferenceEndpoint}`);
48
+ }
49
+ consola.info('Health Check:', `http://${host}:${port}/health`);
50
+ consola.info('Internal Host:', `http://${host}:${port}`);
51
+ if (this._ngrokUrl) {
52
+ consola.info('External Host:', this._ngrokUrl);
53
+ consola.info('External Inspect:', `http://${host}:4040/inspect/http`);
54
+ }
55
+ consola.box('Environment:', envService.get('NODE_ENV'));
56
+ console.log('------------------------------');
57
+ }
58
+ async startJobs() {
59
+ await (0, utils_1.delay)(5000);
60
+ const cronJobs = await Promise.all(this._cronJobs.map((job) => this.app.resolve(job)));
61
+ for (const cronJob of cronJobs) {
62
+ cronJob.start();
63
+ }
64
+ const eventJobs = await Promise.all(this._eventJobs.map((job) => this.app.resolve(job)));
65
+ for (const eventJob of eventJobs) {
66
+ eventJob.setupSubscriptions();
67
+ }
68
+ }
42
69
  addGlobalGuard(Guard) {
43
70
  this._guards.push((0, instanciate_class_with_dependencies_injection_1.instanciateClassWithDependenciesInjection)(this.app, Guard));
44
71
  return this;
@@ -194,14 +221,6 @@ class KoalaApp {
194
221
  this.app.useGlobalFilters(this._prismaValidationExceptionFilter);
195
222
  }
196
223
  this.app.useGlobalFilters(this._globalExceptionFilter, this._domainExceptionFilter, this._zodExceptionFilter);
197
- const cronJobs = await Promise.all(this._cronJobs.map((job) => this.app.resolve(job)));
198
- for (const cronJob of cronJobs) {
199
- cronJob.start();
200
- }
201
- const eventJobs = await Promise.all(this._eventJobs.map((job) => this.app.resolve(job)));
202
- for (const eventJob of eventJobs) {
203
- eventJob.setupSubscriptions();
204
- }
205
224
  for (const guard of this._guards) {
206
225
  this.app.useGlobalGuards(guard);
207
226
  }
@@ -217,6 +236,7 @@ class KoalaApp {
217
236
  this._ngrokUrl = url;
218
237
  });
219
238
  }
239
+ this.startJobs();
220
240
  return this.app;
221
241
  }
222
242
  async serve(host) {
@@ -228,20 +248,5 @@ class KoalaApp {
228
248
  await this.build();
229
249
  await this.serve(host);
230
250
  }
231
- showListeningMessage(port, host = 'localhost') {
232
- const envService = this.app.get(env_service_1.EnvService);
233
- console.log('------------------------------');
234
- if (this._apiReferenceEndpoint) {
235
- consola.info('API Reference:', `http://${host}:${port}${this._apiReferenceEndpoint}`);
236
- }
237
- consola.info('Health Check:', `http://${host}:${port}/health`);
238
- consola.info('Internal Host:', `http://${host}:${port}`);
239
- if (this._ngrokUrl) {
240
- consola.info('External Host:', this._ngrokUrl);
241
- consola.info('External Inspect:', `http://${host}:4040/inspect/http`);
242
- }
243
- consola.box('Environment:', envService.get('NODE_ENV'));
244
- console.log('------------------------------');
245
- }
246
251
  }
247
252
  exports.KoalaApp = KoalaApp;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalarx/nest",
3
- "version": "1.18.3",
3
+ "version": "1.18.4",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",