@avleon/core 0.0.7 → 0.0.8

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/dist/config.d.ts CHANGED
@@ -1,29 +1,10 @@
1
- export interface IDBConfig {
2
- type: string;
3
- host: string;
4
- port: number | string;
5
- username: string;
6
- password: string;
7
- database: string;
8
- synchronize: boolean;
9
- logging: boolean;
10
- entities: any[];
11
- migrations?: string[];
12
- subscribers?: string[];
1
+ import { Constructable } from "typedi";
2
+ import { Environment } from "./environment-variables";
3
+ export interface IConfig<T = any> {
4
+ config(env: Environment): T;
13
5
  }
14
- export interface Environment extends NodeJS.ProcessEnv {
15
- [key: string]: string | undefined;
6
+ export declare function Config<T extends IConfig>(target: Constructable<T>): void;
7
+ export declare class AppConfig {
8
+ get<T extends IConfig<R>, R>(configClass: Constructable<T>): R;
16
9
  }
17
- export interface IAppConfig {
18
- apiKey: string;
19
- timezone: string;
20
- }
21
- export interface IConfig {
22
- config(env: Environment): object;
23
- }
24
- export declare function Config<T extends IConfig>(target: {
25
- new (): T;
26
- }): void;
27
- export declare function GetConfig<T extends IConfig>(ConfigClass: {
28
- new (): T;
29
- }): ReturnType<T["config"]>;
10
+ export declare function GetConfig<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>['config']>>(ConfigClass: Constructable<T>): R;
package/dist/config.js CHANGED
@@ -1,21 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppConfig = void 0;
3
4
  exports.Config = Config;
4
5
  exports.GetConfig = GetConfig;
5
- const CONFIG_METADATA_KEY = Symbol("config");
6
- const configInstances = new Map();
6
+ const typedi_1 = require("typedi");
7
+ const environment_variables_1 = require("./environment-variables");
7
8
  function Config(target) {
8
- if (typeof target.prototype.config !== "function") {
9
- throw new Error(`Class "${target.name}" must implement a "config" method.`);
9
+ typedi_1.Container.set({ id: target, type: target });
10
+ }
11
+ class AppConfig {
12
+ get(configClass) {
13
+ const instance = typedi_1.Container.get(configClass);
14
+ if (!instance) {
15
+ throw new Error(`Configuration for ${configClass.name} not found.`);
16
+ }
17
+ return instance.config(new environment_variables_1.Environment());
10
18
  }
11
- Reflect.defineMetadata(CONFIG_METADATA_KEY, target, target);
12
- // Auto-instantiate and store the config instance
13
- configInstances.set(target.name, new target());
14
19
  }
20
+ exports.AppConfig = AppConfig;
15
21
  function GetConfig(ConfigClass) {
16
- const instance = configInstances.get(ConfigClass.name);
22
+ const instance = typedi_1.Container.get(ConfigClass);
17
23
  if (!instance) {
18
24
  throw new Error(`Class "${ConfigClass.name}" is not registered as a config.`);
19
25
  }
20
- return instance.config(process.env);
26
+ return instance.config(new environment_variables_1.Environment());
21
27
  }
@@ -1,3 +1,5 @@
1
- export declare const e: Record<string, string>;
2
- export type Env = typeof e;
3
- export declare const env: Env;
1
+ export declare class Environment {
2
+ private parseEnvFile;
3
+ get<T = any>(key: string): T;
4
+ getAll<T = any>(): T;
5
+ }
@@ -1,33 +1,47 @@
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
+ };
2
8
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
10
  };
5
11
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.env = exports.e = void 0;
12
+ exports.Environment = void 0;
7
13
  const dotenv_1 = __importDefault(require("dotenv"));
8
14
  const path_1 = __importDefault(require("path"));
9
15
  const fs_1 = __importDefault(require("fs"));
16
+ const typedi_1 = require("typedi");
17
+ const system_exception_1 = require("./exceptions/system-exception");
10
18
  // Load environment variables
11
19
  dotenv_1.default.config({ path: path_1.default.join(process.cwd(), ".env") });
12
- // Read the .env file and infer keys dynamically
13
- const envFilePath = path_1.default.join(process.cwd(), ".env");
14
- const envContents = fs_1.default.readFileSync(envFilePath, "utf-8");
15
- // Parse .env file manually
16
- const parsedEnv = Object.fromEntries(envContents
17
- .split("\n")
18
- .filter((line) => line.trim() && !line.startsWith("#")) // Ignore empty lines and comments
19
- .map((line) => {
20
- const [key, ...valueParts] = line.split("="); // Split key and value
21
- return [key.trim(), valueParts.join("=").trim()]; // Handle values with `=`
22
- }));
23
- const inferType = (value) => {
24
- if (!isNaN(Number(value)))
25
- return Number(value);
26
- if (value.toLowerCase() === "true")
27
- return true;
28
- if (value.toLowerCase() === "false")
29
- return false;
30
- return value;
20
+ let Environment = class Environment {
21
+ parseEnvFile(filePath) {
22
+ try {
23
+ const fileContent = fs_1.default.readFileSync(filePath, 'utf8');
24
+ const parsedEnv = dotenv_1.default.parse(fileContent);
25
+ return Object.assign(Object.assign({}, parsedEnv), process.env);
26
+ }
27
+ catch (error) {
28
+ console.error(`Error parsing .env file: ${error}`);
29
+ return {};
30
+ }
31
+ }
32
+ get(key) {
33
+ const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), '.env'));
34
+ if (!Object(parsedEnv).hasOwnProperty(key)) {
35
+ throw new system_exception_1.EnvironmentVariableNotFound(key);
36
+ }
37
+ return parsedEnv[key];
38
+ }
39
+ getAll() {
40
+ const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), '.env'));
41
+ return parsedEnv;
42
+ }
31
43
  };
32
- exports.e = parsedEnv;
33
- exports.env = exports.e;
44
+ exports.Environment = Environment;
45
+ exports.Environment = Environment = __decorate([
46
+ (0, typedi_1.Service)()
47
+ ], Environment);
@@ -11,3 +11,6 @@ export declare class SystemUseError extends Error {
11
11
  export declare class DuplicateRouteException extends Error {
12
12
  constructor(params: IRouteDuplicateErr);
13
13
  }
14
+ export declare class EnvironmentVariableNotFound extends Error {
15
+ constructor(key: string);
16
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DuplicateRouteException = exports.SystemUseError = void 0;
3
+ exports.EnvironmentVariableNotFound = exports.DuplicateRouteException = exports.SystemUseError = void 0;
4
4
  class SystemUseError extends Error {
5
5
  constructor(message) {
6
6
  super(message);
@@ -16,3 +16,9 @@ class DuplicateRouteException extends Error {
16
16
  }
17
17
  }
18
18
  exports.DuplicateRouteException = DuplicateRouteException;
19
+ class EnvironmentVariableNotFound extends Error {
20
+ constructor(key) {
21
+ super(`${key} not found in environment variables.`);
22
+ }
23
+ }
24
+ exports.EnvironmentVariableNotFound = EnvironmentVariableNotFound;
package/dist/icore.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { FastifyInstance, FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
2
+ import { Constructable } from "typedi";
2
3
  import { Constructor } from "./helpers";
3
4
  import { PathLike } from "fs";
4
5
  import { DataSourceOptions } from "typeorm";
5
6
  import { AppMiddleware } from "./middleware";
6
7
  import { OpenApiOptions, OpenApiUiOptions } from "./openapi";
8
+ import { IConfig } from "./config";
7
9
  export type FuncRoute = {
8
10
  handler: any;
9
11
  middlewares?: any[];
@@ -55,10 +57,12 @@ declare class AvleonApplication {
55
57
  private globalSwaggerOptions;
56
58
  private controllers;
57
59
  private authorizeMiddleware?;
60
+ private appConfig;
58
61
  private constructor();
59
62
  static getInternalApp(buildOptions: any): AvleonApplication;
60
63
  isDevelopment(): boolean;
61
64
  private initSwagger;
65
+ useOpenApi<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>['config']>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
62
66
  useSwagger(options: OpenApiUiOptions): Promise<void>;
63
67
  private handleMiddlewares;
64
68
  private executeMiddlewares;
@@ -104,7 +108,7 @@ export declare class Builder {
104
108
  private dataSource?;
105
109
  private constructor();
106
110
  static createAppBuilder(): Builder;
107
- static creatTestAppBilder(): Builder;
111
+ static creatTestApplication(): Builder;
108
112
  registerPlugin<T extends Function, S extends {}>(plugin: T, options: S): Promise<void>;
109
113
  addDataSource(config: DataSourceOptions): Promise<void>;
110
114
  build(): AvleonApplication;
package/dist/icore.js CHANGED
@@ -65,6 +65,7 @@ const system_exception_1 = require("./exceptions/system-exception");
65
65
  const fs_1 = require("fs");
66
66
  const exceptions_1 = require("./exceptions");
67
67
  const swagger_1 = __importDefault(require("@fastify/swagger"));
68
+ const config_1 = require("./config");
68
69
  const environment_variables_1 = require("./environment-variables");
69
70
  const isTsNode = process.env.TS_NODE_DEV ||
70
71
  process.env.TS_NODE_PROJECT ||
@@ -84,6 +85,7 @@ class AvleonApplication {
84
85
  this.authorizeMiddleware = undefined;
85
86
  this.metaCache = new Map();
86
87
  this.app = (0, fastify_1.default)();
88
+ this.appConfig = new config_1.AppConfig();
87
89
  // this.app.setValidatorCompiler(() => () => true);
88
90
  }
89
91
  static getInternalApp(buildOptions) {
@@ -96,7 +98,8 @@ class AvleonApplication {
96
98
  return AvleonApplication.instance;
97
99
  }
98
100
  isDevelopment() {
99
- return environment_variables_1.env["NODE_ENV"] == "development";
101
+ const env = container_1.default.get(environment_variables_1.Environment);
102
+ return env.get("NODE_ENV") == "development";
100
103
  }
101
104
  async initSwagger(options) {
102
105
  const { routePrefix, logo, theme } = options, restOptions = __rest(options, ["routePrefix", "logo", "theme"]);
@@ -120,6 +123,17 @@ class AvleonApplication {
120
123
  },
121
124
  });
122
125
  }
126
+ useOpenApi(ConfigClass, modifyConfig) {
127
+ const openApiConfig = this.appConfig.get(ConfigClass);
128
+ if (modifyConfig) {
129
+ const modifiedConfig = modifyConfig(openApiConfig);
130
+ this.globalSwaggerOptions = modifiedConfig;
131
+ }
132
+ else {
133
+ this.globalSwaggerOptions = openApiConfig;
134
+ }
135
+ this.hasSwagger = true;
136
+ }
123
137
  async useSwagger(options) {
124
138
  this.hasSwagger = true;
125
139
  this.globalSwaggerOptions = options;
@@ -155,7 +169,6 @@ class AvleonApplication {
155
169
  return this.authorizeMiddleware.authorize(req);
156
170
  });
157
171
  }
158
- console.log("ClassMiddlware:", tag + ":", authClsMeata);
159
172
  try {
160
173
  for (var _d = true, methods_1 = __asyncValues(methods), methods_1_1; methods_1_1 = await methods_1.next(), _a = methods_1_1.done, !_a; _d = true) {
161
174
  _c = methods_1_1.value;
@@ -298,12 +311,10 @@ class AvleonApplication {
298
311
  }
299
312
  }
300
313
  async handleRoute(args) {
301
- console.log(args);
302
314
  }
303
315
  async mapFn(fn) {
304
316
  const original = fn;
305
317
  fn = function () {
306
- console.log(arguments);
307
318
  };
308
319
  return fn;
309
320
  }
@@ -443,7 +454,7 @@ class AvleonApplication {
443
454
  });
444
455
  await this.app.ready();
445
456
  await this.app.listen({ port });
446
- console.log(`Application running on port: 0.0.0.0:${port}`);
457
+ console.log(`Application running on http://127.0.0.1:${port}`);
447
458
  }
448
459
  getTestApp(app) {
449
460
  return this.app;
@@ -462,7 +473,7 @@ class Builder {
462
473
  }
463
474
  return Builder.instance;
464
475
  }
465
- static creatTestAppBilder() {
476
+ static creatTestApplication() {
466
477
  if (!Builder.instance) {
467
478
  Builder.instance = new Builder();
468
479
  }
@@ -487,7 +498,6 @@ class Builder {
487
498
  await datasource.initialize();
488
499
  }
489
500
  catch (error) {
490
- console.log(error);
491
501
  console.error("Database Initialize Error:", error.message);
492
502
  }
493
503
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avleon/core",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "scripts": {
@@ -34,7 +34,7 @@
34
34
  "typeorm": "^0.3.20"
35
35
  },
36
36
  "peerDependencies": {
37
- "@scalar/fastify-api-reference":"^1.25.130"
37
+ "@scalar/fastify-api-reference": "^1.25.130"
38
38
  },
39
39
  "directories": {
40
40
  "test": "tests"