@avleon/core 0.0.4 → 0.0.5

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/helpers.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isClassValidatorClass = exports.getLineNumber = exports.isClassValidator = void 0;
6
+ exports.isClassValidatorClass = exports.getLineNumber = exports.isClassValidator = exports.uuid = void 0;
7
7
  exports.inject = inject;
8
8
  exports.formatUrl = formatUrl;
9
9
  exports.parsedPath = parsedPath;
@@ -17,34 +17,45 @@ exports.jsonToJs = jsonToJs;
17
17
  exports.jsonToInstance = jsonToInstance;
18
18
  exports.transformObjectByInstanceToObject = transformObjectByInstanceToObject;
19
19
  exports.validateObjectByInstance = validateObjectByInstance;
20
+ exports.validateRequestBody = validateRequestBody;
20
21
  const class_transformer_1 = require("class-transformer");
21
22
  const exceptions_1 = require("./exceptions");
22
23
  const fs_1 = __importDefault(require("fs"));
23
24
  const container_1 = __importDefault(require("./container"));
25
+ const system_exception_1 = require("./exceptions/system-exception");
26
+ const crypto_1 = __importDefault(require("crypto"));
27
+ const class_validator_1 = require("class-validator");
28
+ exports.uuid = crypto_1.default.randomUUID();
24
29
  function inject(cls) {
25
- return container_1.default.get(cls);
30
+ try {
31
+ return container_1.default.get(cls);
32
+ }
33
+ catch (error) {
34
+ throw new system_exception_1.SystemUseError(`Not a project class. Maybe you wanna register it first.`);
35
+ }
26
36
  }
27
37
  function formatUrl(path) {
28
- if (typeof path !== 'string') {
29
- throw new Error('The path must be a string');
38
+ if (typeof path !== "string") {
39
+ throw new Error("The path must be a string");
30
40
  }
31
41
  path = path.trim();
32
- if (!path.startsWith('/')) {
33
- path = '/' + path;
42
+ if (!path.startsWith("/")) {
43
+ path = "/" + path;
34
44
  }
35
- path = path.replace(/\/\/+/g, '/');
36
- if (path.endsWith('/')) {
45
+ path = path.replace(/\/\/+/g, "/");
46
+ if (path.endsWith("/")) {
37
47
  path = path.slice(0, -1);
38
48
  }
39
49
  return path;
40
50
  }
41
51
  function parsedPath(ipath) {
42
- return !ipath.startsWith('/') ? '/' + ipath : ipath;
52
+ return !ipath.startsWith("/") ? "/" + ipath : ipath;
43
53
  }
44
54
  const isClassValidator = (target) => {
45
55
  try {
46
56
  const clsval = require("class-validator");
47
- const result = clsval.getMetadataStorage().getTargetValidationMetadatas(target, undefined, false, false);
57
+ const result = (0, class_validator_1.getMetadataStorage)()
58
+ .getTargetValidationMetadatas(target, '', false, false);
48
59
  return result.length > 0;
49
60
  }
50
61
  catch (err) {
@@ -57,22 +68,21 @@ const getLineNumber = (filePath, rpath) => {
57
68
  var _a;
58
69
  let numbers = [];
59
70
  try {
60
- const fileContent = fs_1.default.readFileSync(filePath, 'utf8'); // Read file content
61
- const lines = fileContent.split('\n'); // Split content into line
71
+ const fileContent = fs_1.default.readFileSync(filePath, "utf8");
72
+ const lines = fileContent.split("\n");
62
73
  for (let i = 0; i < lines.length; i++) {
63
74
  const match = lines[i].match(rpath);
64
75
  if (match) {
65
76
  console.log(match);
66
77
  numbers.push({
67
- line: i + 1, // 1-based line number
68
- column: (_a = match.index) !== null && _a !== void 0 ? _a : 0 // 0-based column index
78
+ line: i + 1,
79
+ column: (_a = match.index) !== null && _a !== void 0 ? _a : 0,
69
80
  });
70
81
  }
71
82
  }
72
- return numbers; // Class not found
83
+ return numbers;
73
84
  }
74
85
  catch (error) {
75
- //console.error(`Error reading file: ${error.message}`);
76
86
  return numbers;
77
87
  }
78
88
  };
@@ -81,10 +91,12 @@ function normalizePath(base = "/", subPath = "/") {
81
91
  return `/${base}/${subPath}`.replace(/\/+/g, "/").replace(/\/$/, "");
82
92
  }
83
93
  function extrctParamFromUrl(url) {
84
- const splitPart = url.split("/").filter(x => x.startsWith(':') || x.startsWith("?:"));
85
- return splitPart.map(f => ({
94
+ const splitPart = url
95
+ .split("/")
96
+ .filter((x) => x.startsWith(":") || x.startsWith("?:"));
97
+ return splitPart.map((f) => ({
86
98
  key: f.replace(/(\?|:)/g, ""),
87
- required: !f.startsWith("?:")
99
+ required: !f.startsWith("?:"),
88
100
  }));
89
101
  }
90
102
  function findDuplicates(arr) {
@@ -98,13 +110,13 @@ function findDuplicates(arr) {
98
110
  seen.add(str);
99
111
  }
100
112
  }
101
- return Array.from(duplicates); // Convert duplicates to an array if needed
113
+ return Array.from(duplicates);
102
114
  }
103
115
  function getDataType(expectedType) {
104
116
  switch (expectedType.name) {
105
117
  case "Object":
106
118
  if (Array.isArray(expectedType)) {
107
- return 'array';
119
+ return "array";
108
120
  }
109
121
  return "object";
110
122
  case "String":
@@ -157,12 +169,17 @@ function jsonToInstance(value, instance) {
157
169
  }
158
170
  }
159
171
  function transformObjectByInstanceToObject(instance, value) {
160
- return (0, class_transformer_1.instanceToPlain)((0, class_transformer_1.plainToInstance)(instance, value), { excludeExtraneousValues: true, exposeUnsetFields: true });
172
+ return (0, class_transformer_1.instanceToPlain)((0, class_transformer_1.plainToInstance)(instance, value), {
173
+ excludeExtraneousValues: true,
174
+ exposeUnsetFields: true,
175
+ });
161
176
  }
162
177
  const isClassValidatorClass = (target) => {
163
178
  try {
164
179
  const clsval = require("class-validator");
165
- const result = clsval.getMetadataStorage().getTargetValidationMetadatas(target, undefined, false, false);
180
+ const result = clsval
181
+ .getMetadataStorage()
182
+ .getTargetValidationMetadatas(target, undefined, false, false);
166
183
  return result.length > 0;
167
184
  }
168
185
  catch (err) {
@@ -170,19 +187,19 @@ const isClassValidatorClass = (target) => {
170
187
  }
171
188
  };
172
189
  exports.isClassValidatorClass = isClassValidatorClass;
173
- async function validateObjectByInstance(target, value) {
190
+ async function validateObjectByInstance(target, value = {}, options = 'array') {
174
191
  try {
175
192
  const { validateOrReject } = require("class-validator");
176
193
  const { plainToInstance } = require("class-transformer");
177
194
  await validateOrReject(plainToInstance(target, value));
178
195
  }
179
196
  catch (error) {
180
- if (typeof error == 'object' && Array.isArray(error)) {
181
- const errors = error.reduce((acc, x) => {
197
+ if (typeof error == "object" && Array.isArray(error)) {
198
+ const errors = options == 'object' ? error.reduce((acc, x) => {
182
199
  //acc[x.property] = Object.values(x.constraints);
183
200
  acc[x.property] = x.constraints;
184
201
  return acc;
185
- }, {});
202
+ }, {}) : error.map(x => ({ path: x.property, constraints: x.constraints }));
186
203
  return errors;
187
204
  }
188
205
  else {
@@ -190,3 +207,14 @@ async function validateObjectByInstance(target, value) {
190
207
  }
191
208
  }
192
209
  }
210
+ function validateRequestBody(target, value, options = 'array') {
211
+ if (!(0, exports.isClassValidatorClass)(target))
212
+ return { count: 0, errors: {} };
213
+ const error = (0, class_validator_1.validateSync)((0, class_transformer_1.plainToInstance)(target, value ? value : {}));
214
+ const errors = options == 'object' ? error.reduce((acc, x) => {
215
+ //acc[x.property] = Object.values(x.constraints);
216
+ acc[x.property] = x.constraints;
217
+ return acc;
218
+ }, {}) : error.map(x => ({ path: x.property, constraints: x.constraints }));
219
+ return { count: error.length, errors };
220
+ }
package/dist/icore.d.ts CHANGED
@@ -1,12 +1,24 @@
1
- import { FastifyReply, FastifyRequest } from "fastify";
1
+ import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
2
+ import { Constructor } from "./helpers";
3
+ import { DataSourceOptions } from "typeorm";
4
+ import { AppMiddleware } from "./middleware";
5
+ import { OpenApiOptions, OpenApiUiOptions } from "./openapi";
6
+ export type FuncRoute = {
7
+ handler: any;
8
+ middlewares?: any[];
9
+ schema?: {};
10
+ };
2
11
  export interface IRequest extends FastifyRequest {
3
12
  params: any;
4
13
  query: any;
5
14
  body: any;
6
15
  headers: any;
16
+ user?: any;
7
17
  }
8
18
  export interface IResponse extends FastifyReply {
9
19
  }
20
+ export interface DoneFunction extends HookHandlerDoneFunction {
21
+ }
10
22
  export interface ParamMetaOptions {
11
23
  index: number;
12
24
  key: string;
@@ -15,44 +27,76 @@ export interface ParamMetaOptions {
15
27
  validate: boolean;
16
28
  dataType: any;
17
29
  validatorClass: boolean;
18
- type: "route:param" | "route:query" | "route:body" | "route:header";
30
+ type: "route:param" | "route:query" | "route:body" | "route:header" | "route:user";
19
31
  }
20
32
  export interface MethodParamMeta {
21
33
  params: ParamMetaOptions[];
22
34
  query: ParamMetaOptions[];
23
35
  body: ParamMetaOptions[];
24
36
  headers: ParamMetaOptions[];
37
+ currentUser: ParamMetaOptions[];
38
+ swagger?: OpenApiUiOptions;
25
39
  }
26
- declare class _InternalApplication {
40
+ declare class AvleonApplication {
27
41
  private static instance;
28
42
  private static buildOptions;
29
43
  private app;
30
44
  private routeSet;
31
45
  private alreadyRun;
32
46
  private routes;
47
+ private middlewares;
48
+ private rMap;
49
+ private hasSwagger;
50
+ private globalSwaggerOptions;
51
+ private controllers;
33
52
  private constructor();
34
- static getInternalApp(buildOptions: any): _InternalApplication;
53
+ static getInternalApp(buildOptions: any): AvleonApplication;
54
+ isDevelopment(): boolean;
55
+ private initSwagger;
56
+ useSwagger(options: OpenApiUiOptions): Promise<void>;
57
+ private handleMiddlewares;
58
+ private executeMiddlewares;
35
59
  private buildController;
36
60
  private _mapArgs;
61
+ private metaCache;
37
62
  private _processMeta;
38
- mapControllers(): Promise<void>;
39
- mapGroup(path: string): Promise<void>;
40
- handleRoute(args: any): Promise<void>;
41
- mapGet(path: string | undefined, fn: Function): Promise<void>;
42
- mapPost(): Promise<void>;
43
- mapPut(): Promise<void>;
44
- mapDelete(): Promise<void>;
63
+ autoControllers(): Promise<void>;
64
+ mapControllers(controllers: Function[]): void;
45
65
  private _mapControllers;
66
+ mapControllersAuto(): void;
67
+ handleRoute(args: any): Promise<void>;
68
+ private mapFn;
69
+ useMiddlewares<T extends AppMiddleware>(mclasses: Constructor<T>[]): void;
70
+ private _handleError;
71
+ mapRoute<T extends (...args: any[]) => any>(method: "get" | "post" | "put" | "delete", path: string | undefined, fn: T): Promise<void>;
72
+ private _routeHandler;
73
+ mapGet<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
74
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
75
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
76
+ };
77
+ mapPost<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
78
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
79
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
80
+ };
81
+ mapPut<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
82
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
83
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
84
+ };
85
+ mapDelete<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
86
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
87
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
88
+ };
46
89
  run(port?: number): Promise<void>;
47
90
  }
48
- export declare class AppBuilder {
91
+ export declare class Builder {
49
92
  private static instance;
50
93
  private alreadyBuilt;
51
- private databse;
94
+ private database;
95
+ private dataSource?;
52
96
  private constructor();
53
- static createBuilder(): AppBuilder;
97
+ static createAppBuilder(): Builder;
54
98
  registerPlugin<T extends Function, S extends {}>(plugin: T, options: S): Promise<void>;
55
- useDatabase(): Promise<void>;
56
- build(): Promise<_InternalApplication>;
99
+ addDataSource(config: DataSourceOptions): Promise<void>;
100
+ build(): AvleonApplication;
57
101
  }
58
102
  export {};