@avleon/core 0.0.4 → 0.0.6

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.
Files changed (44) hide show
  1. package/README.md +3 -0
  2. package/dist/authentication.d.ts +7 -0
  3. package/dist/authentication.js +11 -0
  4. package/dist/collection.d.ts +52 -0
  5. package/dist/collection.js +282 -0
  6. package/dist/config.d.ts +7 -8
  7. package/dist/config.js +10 -8
  8. package/dist/container.d.ts +5 -5
  9. package/dist/container.js +10 -13
  10. package/dist/controller.d.ts +2 -1
  11. package/dist/controller.js +17 -3
  12. package/dist/decorators.d.ts +2 -1
  13. package/dist/decorators.js +12 -2
  14. package/dist/environment-variables.d.ts +3 -0
  15. package/dist/environment-variables.js +33 -0
  16. package/dist/exceptions/http-exceptions.d.ts +24 -1
  17. package/dist/exceptions/http-exceptions.js +33 -2
  18. package/dist/helpers.d.ts +9 -1
  19. package/dist/helpers.js +78 -27
  20. package/dist/icore.d.ts +70 -16
  21. package/dist/icore.js +408 -135
  22. package/dist/index.d.ts +11 -6
  23. package/dist/index.js +7 -1
  24. package/dist/map-types.js +1 -2
  25. package/dist/middleware.d.ts +24 -0
  26. package/dist/middleware.js +59 -0
  27. package/dist/params.d.ts +1 -0
  28. package/dist/params.js +13 -9
  29. package/dist/queue.d.ts +30 -0
  30. package/dist/queue.js +96 -0
  31. package/dist/render.d.ts +1 -0
  32. package/dist/render.js +8 -0
  33. package/dist/response.d.ts +3 -2
  34. package/dist/response.js +9 -15
  35. package/dist/types/app-builder.interface.d.ts +9 -0
  36. package/dist/types/app-builder.interface.js +2 -0
  37. package/dist/types/application.interface.d.ts +2 -0
  38. package/dist/types/application.interface.js +2 -0
  39. package/dist/validation.d.ts +23 -0
  40. package/dist/validation.js +98 -0
  41. package/dist/validator-extend.js +2 -2
  42. package/package.json +45 -39
  43. package/dist/repository.d.ts +0 -0
  44. package/dist/repository.js +0 -1
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NotFoundException = exports.InternalErrorException = exports.BadRequestException = exports.BaseHttpException = void 0;
3
+ exports.httpExcepitoins = exports.ForbiddenException = exports.UnauthorizedException = exports.NotFoundException = exports.InternalErrorException = exports.ValidationErrorException = exports.BadRequestException = exports.BaseHttpException = void 0;
4
4
  class BaseHttpException extends Error {
5
5
  constructor(message) {
6
- super(message);
6
+ super(JSON.stringify(message));
7
7
  this.code = 500;
8
8
  this.name = "HttpException";
9
9
  }
@@ -20,6 +20,13 @@ class BadRequestException extends BaseHttpException {
20
20
  }
21
21
  }
22
22
  exports.BadRequestException = BadRequestException;
23
+ class ValidationErrorException extends BadRequestException {
24
+ constructor() {
25
+ super(...arguments);
26
+ this.name = "ValidationError";
27
+ }
28
+ }
29
+ exports.ValidationErrorException = ValidationErrorException;
23
30
  class InternalErrorException extends BaseHttpException {
24
31
  constructor(message = "Something going wrong") {
25
32
  super(message);
@@ -36,3 +43,27 @@ class NotFoundException extends BaseHttpException {
36
43
  }
37
44
  }
38
45
  exports.NotFoundException = NotFoundException;
46
+ class UnauthorizedException extends BaseHttpException {
47
+ constructor(message) {
48
+ super(message);
49
+ this.name = "Unauthorized";
50
+ this.code = 401;
51
+ }
52
+ }
53
+ exports.UnauthorizedException = UnauthorizedException;
54
+ class ForbiddenException extends BaseHttpException {
55
+ constructor(message) {
56
+ super(message);
57
+ this.name = "Forbidden";
58
+ this.code = 403;
59
+ }
60
+ }
61
+ exports.ForbiddenException = ForbiddenException;
62
+ exports.httpExcepitoins = {
63
+ NotFound: (message) => new NotFoundException(message),
64
+ ValidationError: (message) => new ValidationErrorException(message),
65
+ BadRequest: (message) => new BadRequestException(message),
66
+ Unauthorized: (message) => new UnauthorizedException(message),
67
+ Forbidden: (message) => new ForbiddenException(message),
68
+ InternalError: (message) => new InternalErrorException(message)
69
+ };
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,7 @@
1
+ export declare const uuid: `${string}-${string}-${string}-${string}-${string}`;
1
2
  export declare function inject<T>(cls: new (...args: any[]) => T): T;
2
3
  export type Constructor<T = any> = new (...args: any[]) => T;
4
+ export declare function isConstructor(func: any): boolean;
3
5
  export declare function formatUrl(path: string): string;
4
6
  export declare function parsedPath(ipath: string): string;
5
7
  export declare const isClassValidator: (target: Constructor) => boolean;
@@ -21,4 +23,10 @@ export declare function jsonToJs(value: string): any;
21
23
  export declare function jsonToInstance(value: string, instance: Constructor): any;
22
24
  export declare function transformObjectByInstanceToObject(instance: Constructor, value: object): Record<string, any>;
23
25
  export declare const isClassValidatorClass: (target: Constructor) => boolean;
24
- export declare function validateObjectByInstance(target: Constructor, value: object): Promise<any>;
26
+ export declare function validateObjectByInstance(target: Constructor, value?: object, options?: 'object' | 'array'): Promise<any>;
27
+ type ValidationError = {
28
+ count: number;
29
+ errors: any;
30
+ };
31
+ export declare function validateRequestBody(target: Constructor, value: object, options?: 'object' | 'array'): ValidationError;
32
+ export {};
package/dist/helpers.js CHANGED
@@ -3,8 +3,9 @@ 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
+ exports.isConstructor = isConstructor;
8
9
  exports.formatUrl = formatUrl;
9
10
  exports.parsedPath = parsedPath;
10
11
  exports.normalizePath = normalizePath;
@@ -17,34 +18,67 @@ exports.jsonToJs = jsonToJs;
17
18
  exports.jsonToInstance = jsonToInstance;
18
19
  exports.transformObjectByInstanceToObject = transformObjectByInstanceToObject;
19
20
  exports.validateObjectByInstance = validateObjectByInstance;
21
+ exports.validateRequestBody = validateRequestBody;
20
22
  const class_transformer_1 = require("class-transformer");
21
23
  const exceptions_1 = require("./exceptions");
22
24
  const fs_1 = __importDefault(require("fs"));
23
25
  const container_1 = __importDefault(require("./container"));
26
+ const system_exception_1 = require("./exceptions/system-exception");
27
+ const crypto_1 = __importDefault(require("crypto"));
28
+ const class_validator_1 = require("class-validator");
29
+ exports.uuid = crypto_1.default.randomUUID();
24
30
  function inject(cls) {
25
- return container_1.default.get(cls);
31
+ try {
32
+ return container_1.default.get(cls);
33
+ }
34
+ catch (error) {
35
+ throw new system_exception_1.SystemUseError(`Not a project class. Maybe you wanna register it first.`);
36
+ }
37
+ }
38
+ function isConstructor(func) {
39
+ // Check if the func is a function
40
+ if (typeof func !== 'function') {
41
+ return false;
42
+ }
43
+ // Check if it's an arrow function or a built-in JavaScript function
44
+ if (func === Function.prototype.bind || func instanceof RegExp) {
45
+ return false;
46
+ }
47
+ // Check if it has a `prototype` property
48
+ if (func.prototype && typeof func.prototype === 'object') {
49
+ return true;
50
+ }
51
+ // If it's not a constructor, check if it can be called with the new keyword
52
+ try {
53
+ const instance = new func();
54
+ return typeof instance === 'object';
55
+ }
56
+ catch (e) {
57
+ return false;
58
+ }
26
59
  }
27
60
  function formatUrl(path) {
28
- if (typeof path !== 'string') {
29
- throw new Error('The path must be a string');
61
+ if (typeof path !== "string") {
62
+ throw new Error("The path must be a string");
30
63
  }
31
64
  path = path.trim();
32
- if (!path.startsWith('/')) {
33
- path = '/' + path;
65
+ if (!path.startsWith("/")) {
66
+ path = "/" + path;
34
67
  }
35
- path = path.replace(/\/\/+/g, '/');
36
- if (path.endsWith('/')) {
68
+ path = path.replace(/\/\/+/g, "/");
69
+ if (path.endsWith("/")) {
37
70
  path = path.slice(0, -1);
38
71
  }
39
72
  return path;
40
73
  }
41
74
  function parsedPath(ipath) {
42
- return !ipath.startsWith('/') ? '/' + ipath : ipath;
75
+ return !ipath.startsWith("/") ? "/" + ipath : ipath;
43
76
  }
44
77
  const isClassValidator = (target) => {
45
78
  try {
46
79
  const clsval = require("class-validator");
47
- const result = clsval.getMetadataStorage().getTargetValidationMetadatas(target, undefined, false, false);
80
+ const result = (0, class_validator_1.getMetadataStorage)()
81
+ .getTargetValidationMetadatas(target, '', false, false);
48
82
  return result.length > 0;
49
83
  }
50
84
  catch (err) {
@@ -57,22 +91,21 @@ const getLineNumber = (filePath, rpath) => {
57
91
  var _a;
58
92
  let numbers = [];
59
93
  try {
60
- const fileContent = fs_1.default.readFileSync(filePath, 'utf8'); // Read file content
61
- const lines = fileContent.split('\n'); // Split content into line
94
+ const fileContent = fs_1.default.readFileSync(filePath, "utf8");
95
+ const lines = fileContent.split("\n");
62
96
  for (let i = 0; i < lines.length; i++) {
63
97
  const match = lines[i].match(rpath);
64
98
  if (match) {
65
99
  console.log(match);
66
100
  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
101
+ line: i + 1,
102
+ column: (_a = match.index) !== null && _a !== void 0 ? _a : 0,
69
103
  });
70
104
  }
71
105
  }
72
- return numbers; // Class not found
106
+ return numbers;
73
107
  }
74
108
  catch (error) {
75
- //console.error(`Error reading file: ${error.message}`);
76
109
  return numbers;
77
110
  }
78
111
  };
@@ -81,10 +114,12 @@ function normalizePath(base = "/", subPath = "/") {
81
114
  return `/${base}/${subPath}`.replace(/\/+/g, "/").replace(/\/$/, "");
82
115
  }
83
116
  function extrctParamFromUrl(url) {
84
- const splitPart = url.split("/").filter(x => x.startsWith(':') || x.startsWith("?:"));
85
- return splitPart.map(f => ({
117
+ const splitPart = url
118
+ .split("/")
119
+ .filter((x) => x.startsWith(":") || x.startsWith("?:"));
120
+ return splitPart.map((f) => ({
86
121
  key: f.replace(/(\?|:)/g, ""),
87
- required: !f.startsWith("?:")
122
+ required: !f.startsWith("?:"),
88
123
  }));
89
124
  }
90
125
  function findDuplicates(arr) {
@@ -98,13 +133,13 @@ function findDuplicates(arr) {
98
133
  seen.add(str);
99
134
  }
100
135
  }
101
- return Array.from(duplicates); // Convert duplicates to an array if needed
136
+ return Array.from(duplicates);
102
137
  }
103
138
  function getDataType(expectedType) {
104
139
  switch (expectedType.name) {
105
140
  case "Object":
106
141
  if (Array.isArray(expectedType)) {
107
- return 'array';
142
+ return "array";
108
143
  }
109
144
  return "object";
110
145
  case "String":
@@ -157,12 +192,17 @@ function jsonToInstance(value, instance) {
157
192
  }
158
193
  }
159
194
  function transformObjectByInstanceToObject(instance, value) {
160
- return (0, class_transformer_1.instanceToPlain)((0, class_transformer_1.plainToInstance)(instance, value), { excludeExtraneousValues: true, exposeUnsetFields: true });
195
+ return (0, class_transformer_1.instanceToPlain)((0, class_transformer_1.plainToInstance)(instance, value), {
196
+ excludeExtraneousValues: true,
197
+ exposeUnsetFields: true,
198
+ });
161
199
  }
162
200
  const isClassValidatorClass = (target) => {
163
201
  try {
164
202
  const clsval = require("class-validator");
165
- const result = clsval.getMetadataStorage().getTargetValidationMetadatas(target, undefined, false, false);
203
+ const result = clsval
204
+ .getMetadataStorage()
205
+ .getTargetValidationMetadatas(target, undefined, false, false);
166
206
  return result.length > 0;
167
207
  }
168
208
  catch (err) {
@@ -170,19 +210,19 @@ const isClassValidatorClass = (target) => {
170
210
  }
171
211
  };
172
212
  exports.isClassValidatorClass = isClassValidatorClass;
173
- async function validateObjectByInstance(target, value) {
213
+ async function validateObjectByInstance(target, value = {}, options = 'array') {
174
214
  try {
175
215
  const { validateOrReject } = require("class-validator");
176
216
  const { plainToInstance } = require("class-transformer");
177
217
  await validateOrReject(plainToInstance(target, value));
178
218
  }
179
219
  catch (error) {
180
- if (typeof error == 'object' && Array.isArray(error)) {
181
- const errors = error.reduce((acc, x) => {
220
+ if (typeof error == "object" && Array.isArray(error)) {
221
+ const errors = options == 'object' ? error.reduce((acc, x) => {
182
222
  //acc[x.property] = Object.values(x.constraints);
183
223
  acc[x.property] = x.constraints;
184
224
  return acc;
185
- }, {});
225
+ }, {}) : error.map(x => ({ path: x.property, constraints: x.constraints }));
186
226
  return errors;
187
227
  }
188
228
  else {
@@ -190,3 +230,14 @@ async function validateObjectByInstance(target, value) {
190
230
  }
191
231
  }
192
232
  }
233
+ function validateRequestBody(target, value, options = 'array') {
234
+ if (!(0, exports.isClassValidatorClass)(target))
235
+ return { count: 0, errors: {} };
236
+ const error = (0, class_validator_1.validateSync)((0, class_transformer_1.plainToInstance)(target, value ? value : {}));
237
+ const errors = options == 'object' ? error.reduce((acc, x) => {
238
+ //acc[x.property] = Object.values(x.constraints);
239
+ acc[x.property] = x.constraints;
240
+ return acc;
241
+ }, {}) : error.map(x => ({ path: x.property, constraints: x.constraints }));
242
+ return { count: error.length, errors };
243
+ }
package/dist/icore.d.ts CHANGED
@@ -1,12 +1,25 @@
1
- import { FastifyReply, FastifyRequest } from "fastify";
1
+ import { FastifyInstance, FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
2
+ import { Constructor } from "./helpers";
3
+ import { PathLike } from "fs";
4
+ import { DataSourceOptions } from "typeorm";
5
+ import { AppMiddleware } from "./middleware";
6
+ import { OpenApiOptions, OpenApiUiOptions } from "./openapi";
7
+ export type FuncRoute = {
8
+ handler: any;
9
+ middlewares?: any[];
10
+ schema?: {};
11
+ };
2
12
  export interface IRequest extends FastifyRequest {
3
13
  params: any;
4
14
  query: any;
5
15
  body: any;
6
16
  headers: any;
17
+ user?: any;
7
18
  }
8
19
  export interface IResponse extends FastifyReply {
9
20
  }
21
+ export interface DoneFunction extends HookHandlerDoneFunction {
22
+ }
10
23
  export interface ParamMetaOptions {
11
24
  index: number;
12
25
  key: string;
@@ -15,44 +28,85 @@ export interface ParamMetaOptions {
15
28
  validate: boolean;
16
29
  dataType: any;
17
30
  validatorClass: boolean;
18
- type: "route:param" | "route:query" | "route:body" | "route:header";
31
+ type: "route:param" | "route:query" | "route:body" | "route:header" | "route:user";
19
32
  }
20
33
  export interface MethodParamMeta {
21
34
  params: ParamMetaOptions[];
22
35
  query: ParamMetaOptions[];
23
36
  body: ParamMetaOptions[];
24
37
  headers: ParamMetaOptions[];
38
+ currentUser: ParamMetaOptions[];
39
+ swagger?: OpenApiUiOptions;
25
40
  }
26
- declare class _InternalApplication {
41
+ type StaticFileOptions = {
42
+ path?: PathLike;
43
+ prefix?: string;
44
+ };
45
+ declare class AvleonApplication {
27
46
  private static instance;
28
47
  private static buildOptions;
29
48
  private app;
30
49
  private routeSet;
31
50
  private alreadyRun;
32
51
  private routes;
52
+ private middlewares;
53
+ private rMap;
54
+ private hasSwagger;
55
+ private globalSwaggerOptions;
56
+ private controllers;
57
+ private authorizeMiddleware?;
33
58
  private constructor();
34
- static getInternalApp(buildOptions: any): _InternalApplication;
59
+ static getInternalApp(buildOptions: any): AvleonApplication;
60
+ isDevelopment(): boolean;
61
+ private initSwagger;
62
+ useSwagger(options: OpenApiUiOptions): Promise<void>;
63
+ private handleMiddlewares;
64
+ private executeMiddlewares;
35
65
  private buildController;
36
66
  private _mapArgs;
67
+ private metaCache;
37
68
  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>;
69
+ autoControllers(): Promise<void>;
70
+ mapControllers(controllers: Function[]): void;
45
71
  private _mapControllers;
72
+ mapControllersAuto(): void;
73
+ handleRoute(args: any): Promise<void>;
74
+ private mapFn;
75
+ useMiddlewares<T extends AppMiddleware>(mclasses: Constructor<T>[]): void;
76
+ useAuthoriztion<T extends any>(middleware: Constructor<T>): void;
77
+ private _handleError;
78
+ mapRoute<T extends (...args: any[]) => any>(method: "get" | "post" | "put" | "delete", path: string | undefined, fn: T): Promise<void>;
79
+ private _routeHandler;
80
+ mapGet<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
81
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
82
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
83
+ };
84
+ mapPost<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
85
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
86
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
87
+ };
88
+ mapPut<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
89
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
90
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
91
+ };
92
+ mapDelete<T extends (...args: any[]) => any>(path: string | undefined, fn: T): {
93
+ useMiddleware: <M extends AppMiddleware>(middlewares: Constructor<AppMiddleware>[]) => /*elided*/ any;
94
+ useSwagger: (options: OpenApiOptions) => /*elided*/ any;
95
+ };
96
+ useStaticFiles(options?: StaticFileOptions): void;
46
97
  run(port?: number): Promise<void>;
98
+ getTestApp(app: AvleonApplication): FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>;
47
99
  }
48
- export declare class AppBuilder {
100
+ export declare class Builder {
49
101
  private static instance;
50
102
  private alreadyBuilt;
51
- private databse;
103
+ private database;
104
+ private dataSource?;
52
105
  private constructor();
53
- static createBuilder(): AppBuilder;
106
+ static createAppBuilder(): Builder;
107
+ static creatTestAppBilder(): Builder;
54
108
  registerPlugin<T extends Function, S extends {}>(plugin: T, options: S): Promise<void>;
55
- useDatabase(): Promise<void>;
56
- build(): Promise<_InternalApplication>;
109
+ addDataSource(config: DataSourceOptions): Promise<void>;
110
+ build(): AvleonApplication;
57
111
  }
58
112
  export {};