@xrystal/core 3.20.2 → 3.20.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.20.2",
4
+ "version": "3.20.4",
5
5
  "description": "Project core for xrystal",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -1,6 +1,6 @@
1
- import { IService } from "../../utils";
1
+ import { ILifeCycle } from "../../utils";
2
2
  import ConfigsService from "../configs";
3
- export default class ClientsService implements IService {
3
+ export default class ClientsService implements ILifeCycle<any> {
4
4
  #private;
5
5
  private _instances;
6
6
  constructor({ configsService }: {
@@ -1,5 +1,5 @@
1
1
  import SystemService from '../system/index';
2
- import { IService, ModeEnum } from '../../utils';
2
+ import { ILifeCycle, ModeEnum } from '../../utils';
3
3
  export interface IConfig {
4
4
  worker: boolean;
5
5
  mode: ModeEnum;
@@ -30,7 +30,7 @@ export interface IConfig {
30
30
  }
31
31
  export interface IConfigsService extends IConfig {
32
32
  }
33
- export default class ConfigsService implements IService {
33
+ export default class ConfigsService implements ILifeCycle<any> {
34
34
  #private;
35
35
  readonly publicFolderName: string;
36
36
  readonly kafkaLogsTopic: string;
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { ProtocolEnum } from '../../utils/index';
2
+ import { ILifeCycle, ProtocolEnum } from '../../utils/index';
3
3
  import LoggerService from '../logger';
4
4
  import SystemService from '../system';
5
5
  export declare const controllerContextStorage: AsyncLocalStorage<{
@@ -63,7 +63,7 @@ declare abstract class Controller {
63
63
  protected get req(): CustomRequest;
64
64
  protected get res(): CustomResponse;
65
65
  }
66
- export declare abstract class ControllerService extends Controller {
66
+ export declare abstract class ControllerService extends Controller implements ILifeCycle<any> {
67
67
  protected systemService: SystemService;
68
68
  constructor({ systemService }: {
69
69
  systemService: SystemService;
@@ -1,6 +1,6 @@
1
- import { IService } from '../../utils/index';
1
+ import { ILifeCycle } from '../../utils/index';
2
2
  import LoggerService from '../logger/index';
3
- export default class EventsService implements IService {
3
+ export default class EventsService implements ILifeCycle<any> {
4
4
  #private;
5
5
  constructor({ loggerService }: {
6
6
  loggerService: LoggerService;
@@ -9,5 +9,6 @@ export default class EventsService implements IService {
9
9
  logger: LoggerService;
10
10
  }) => any;
11
11
  private _globalLoader;
12
+ private _DILoader;
12
13
  get global(): any;
13
14
  }
@@ -1,4 +1,4 @@
1
- import { LoggerLayerEnum } from '../../utils/index';
1
+ import { LoggerLayerEnum, x } from '../../utils/index';
2
2
  export default class EventsService {
3
3
  #loggerService;
4
4
  constructor({ loggerService }) {
@@ -6,25 +6,38 @@ export default class EventsService {
6
6
  }
7
7
  load = ({}) => {
8
8
  this._globalLoader();
9
+ this._DILoader();
9
10
  };
10
11
  _globalLoader = () => {
11
12
  process.on("uncaughtException", (error, origin) => {
12
- this.#loggerService.winston.log({
13
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
14
- message: `UncaughtException: ${error.message}`,
15
- stack: error.stack,
16
- origin: origin
13
+ this.#loggerService.log({
14
+ level: LoggerLayerEnum.CRITICAL,
15
+ message: `Uncaught Exception: ${error.message}`,
16
+ payload: {
17
+ stack: error.stack,
18
+ origin: origin
19
+ }
17
20
  });
18
21
  });
19
22
  process.on("unhandledRejection", (reason, promise) => {
20
23
  const error = reason instanceof Error ? reason : new Error(String(reason));
21
- this.#loggerService.winston.log({
22
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
23
- message: `UnhandledRejection: ${error.message}`,
24
- stack: error.stack
24
+ this.#loggerService.log({
25
+ level: LoggerLayerEnum.CRITICAL,
26
+ message: `Unhandled Rejection: ${error.message}`,
27
+ payload: {
28
+ stack: error.stack,
29
+ }
25
30
  });
26
31
  });
27
32
  };
33
+ _DILoader = () => {
34
+ process.on('SIGTERM', () => {
35
+ x.shutdown();
36
+ });
37
+ process.on('SIGINT', () => {
38
+ x.shutdown();
39
+ });
40
+ };
28
41
  get global() {
29
42
  return this._globalLoader();
30
43
  }
@@ -1,7 +1,7 @@
1
1
  import ConfigsService from "../configs";
2
- import { IService } from "../../utils";
2
+ import { ILifeCycle } from "../../utils";
3
3
  import SystemService from "../system";
4
- export default class LocalizationsService implements IService {
4
+ export default class LocalizationsService implements ILifeCycle<any> {
5
5
  #private;
6
6
  _instance: any;
7
7
  constructor({ systemService, configsService, }: {
@@ -2,7 +2,7 @@ import winston from "winston";
2
2
  import "winston-daily-rotate-file";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import ConfigsService from "../configs";
5
- import { LoggerLayerEnum, IService } from "../../utils";
5
+ import { LoggerLayerEnum, ILifeCycle } from "../../utils";
6
6
  import SystemService from "../system";
7
7
  export interface ICustomLogger extends winston.Logger {
8
8
  critical: winston.LeveledLogMethod;
@@ -14,7 +14,7 @@ export interface ILog {
14
14
  payload?: any;
15
15
  code?: string | number;
16
16
  }
17
- export default class LoggerService implements IService {
17
+ export default class LoggerService implements ILifeCycle<any> {
18
18
  #private;
19
19
  static readonly storage: AsyncLocalStorage<Map<string, string>>;
20
20
  private serviceName;
@@ -54,7 +54,7 @@ export default class LoggerService {
54
54
  }
55
55
  load = async ({}) => {
56
56
  const loggersConfigs = this.#systemService.tmp.configs.loaders.loggers;
57
- this.serviceName = this.#systemService.tmp.configs?.serviceName;
57
+ this.serviceName = this.#systemService.tmp.configs.service;
58
58
  const { kafkaBrokers, isKafkaPassive } = this.#configsService.all;
59
59
  const brokers = kafkaBrokers ? String(kafkaBrokers).split(",").map((b) => b.trim()) : [];
60
60
  const isKafkaEnabled = isKafkaPassive === false && brokers.length > 0;
@@ -1,5 +1,5 @@
1
- import { IService } from "../../utils";
2
- export default class SystemService implements IService {
1
+ import { ILifeCycle } from "../../utils";
2
+ export default class SystemService implements ILifeCycle<any> {
3
3
  protected _core: Record<string, any>;
4
4
  protected _tmp: Record<string, any>;
5
5
  cwd: string;
@@ -1,3 +1,4 @@
1
- export declare class IService {
2
- load({}: {}): void;
1
+ export declare abstract class ILifeCycle<T = any> {
2
+ load(props?: T | {}): Promise<void>;
3
+ dispose?(_context?: any): Promise<void> | void;
3
4
  }
@@ -1,4 +1,6 @@
1
- export class IService {
2
- load({}) {
1
+ export class ILifeCycle {
2
+ async load(props = {}) {
3
+ }
4
+ dispose(_context) {
3
5
  }
4
6
  }
@@ -1,5 +1,8 @@
1
- import { LifetimeType } from 'awilix';
2
- declare class X<T = {}> {
1
+ import { AwilixContainer, LifetimeType } from 'awilix';
2
+ declare abstract class XHelper {
3
+ protected checkRegistration(container: AwilixContainer, name: string): boolean;
4
+ }
5
+ declare class X extends XHelper {
3
6
  private container;
4
7
  private initializedNames;
5
8
  constructor();
@@ -19,9 +22,9 @@ declare class X<T = {}> {
19
22
  service: any;
20
23
  props?: T;
21
24
  }[], verbose?: boolean): Promise<this>;
22
- get<T>(target: any): T;
25
+ shutdown(verbose?: boolean): Promise<void>;
26
+ get<T>(target: (new (...args: any[]) => T) | string): T;
23
27
  get cradle(): any;
24
- private isRegistered;
25
28
  }
26
- declare const _default: X<{}>;
29
+ declare const _default: X;
27
30
  export default _default;
@@ -1,10 +1,16 @@
1
1
  import { createContainer, asClass, asValue, InjectionMode, listModules, Lifetime } from 'awilix';
2
2
  import path from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
- class X {
4
+ class XHelper {
5
+ checkRegistration(container, name) {
6
+ return !!container.registrations[name] && container.registrations[name].resolve !== undefined;
7
+ }
8
+ }
9
+ class X extends XHelper {
5
10
  container;
6
11
  initializedNames = new Set();
7
12
  constructor() {
13
+ super();
8
14
  this.container = createContainer({
9
15
  injectionMode: InjectionMode.PROXY,
10
16
  strict: true
@@ -58,7 +64,7 @@ class X {
58
64
  if (isClass) {
59
65
  const className = dependency.name;
60
66
  const name = className.charAt(0).toLowerCase() + className.slice(1);
61
- if (!this.isRegistered(name)) {
67
+ if (!this.checkRegistration(this.container, name)) {
62
68
  this.container.register({
63
69
  [name]: asClass(dependency).setLifetime(lifetime)
64
70
  });
@@ -76,7 +82,7 @@ class X {
76
82
  if (!Dependency?.name)
77
83
  return this;
78
84
  const name = Dependency.name.charAt(0).toLowerCase() + Dependency.name.slice(1);
79
- if (this.isRegistered(name))
85
+ if (this.checkRegistration(this.container, name))
80
86
  return this;
81
87
  this.container.register({ [name]: asClass(Dependency).setLifetime(lifetime) });
82
88
  return this;
@@ -90,7 +96,7 @@ class X {
90
96
  if (!name)
91
97
  return this;
92
98
  const formattedName = name.charAt(0).toLowerCase() + name.slice(1);
93
- if (this.isRegistered(formattedName))
99
+ if (this.checkRegistration(this.container, formattedName))
94
100
  return this;
95
101
  this.container.register({ [formattedName]: asValue(instance) });
96
102
  return this;
@@ -122,15 +128,36 @@ class X {
122
128
  this.initializedNames.add(key);
123
129
  }
124
130
  catch (err) {
125
- console.error(`[DI] Initialization Failed: ${key} ->`, err.message);
131
+ if (verbose)
132
+ console.error(`[DI] Initialization Failed: ${key} ->`, err.message);
126
133
  }
127
134
  }
128
135
  }
129
136
  return this;
130
137
  }
138
+ async shutdown(verbose = false) {
139
+ const registrations = this.container.registrations;
140
+ for (const key in registrations) {
141
+ const instance = this.container.cradle[key];
142
+ const shutdownMethod = instance?.dispose || instance?.destroy;
143
+ if (instance && typeof shutdownMethod === 'function') {
144
+ try {
145
+ await shutdownMethod.call(instance);
146
+ if (verbose)
147
+ console.log(`[DI] Shutdown: ${key}`);
148
+ }
149
+ catch (err) {
150
+ console.error(`[DI] Shutdown Error (${key}):`, err.message);
151
+ }
152
+ }
153
+ }
154
+ await this.container.dispose();
155
+ }
131
156
  get(target) {
132
157
  try {
133
- const resolveName = typeof target === 'function' ? target.name.charAt(0).toLowerCase() + target.name.slice(1) : target;
158
+ const resolveName = typeof target === 'function'
159
+ ? target.name.charAt(0).toLowerCase() + target.name.slice(1)
160
+ : target;
134
161
  return this.container.resolve(resolveName);
135
162
  }
136
163
  catch (err) {
@@ -141,8 +168,5 @@ class X {
141
168
  }
142
169
  }
143
170
  get cradle() { return this.container.cradle; }
144
- isRegistered(name) {
145
- return !!this.container.registrations[name] && this.container.registrations[name].resolve !== undefined;
146
- }
147
171
  }
148
172
  export default new X();