@avleon/core 0.0.25 → 0.0.26

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.
@@ -38,4 +38,12 @@ export declare class ForbiddenException extends BaseHttpException {
38
38
  code: number;
39
39
  constructor(message: any);
40
40
  }
41
- export type HttpException = NotFoundException | BadRequestException | UnauthorizedException | InternalErrorException | ForbiddenException;
41
+ export type HttpExceptionTypes = NotFoundException | BadRequestException | UnauthorizedException | InternalErrorException | ForbiddenException;
42
+ export declare const HttpExceptions: {
43
+ notFound: (message?: any) => NotFoundException;
44
+ validationError: (message?: any) => ValidationErrorException;
45
+ badRequest: (message?: any) => BadRequestException;
46
+ unauthorized: (message?: any) => UnauthorizedException;
47
+ forbidden: (message?: any) => ForbiddenException;
48
+ internalError: (message?: any) => InternalErrorException;
49
+ };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ForbiddenException = exports.UnauthorizedException = exports.NotFoundException = exports.InternalErrorException = exports.ValidationErrorException = exports.BadRequestException = exports.BaseHttpException = void 0;
3
+ exports.HttpExceptions = exports.ForbiddenException = exports.UnauthorizedException = exports.NotFoundException = exports.InternalErrorException = exports.ValidationErrorException = exports.BadRequestException = exports.BaseHttpException = void 0;
4
4
  /**
5
5
  * @copyright 2024
6
6
  * @author Tareq Hossain
@@ -73,11 +73,11 @@ exports.ForbiddenException = ForbiddenException;
73
73
  // Forbidden: (message: any) => ForbiddenException,
74
74
  // InternalError: (message: any) => InternalErrorException
75
75
  // }
76
- // export const httpExcepitoins: HttpExceptions = {
77
- // NotFound:(message:any)=>new NotFoundException(message),
78
- // ValidationError:(message:any)=>new ValidationErrorException(message),
79
- // BadRequest:(message:any)=>new BadRequestException(message),
80
- // Unauthorized:(message:any)=>new UnauthorizedException(message),
81
- // Forbidden:(message:any)=>new ForbiddenException(message),
82
- // InternalError: (message:any)=> new InternalErrorException(message)
83
- // }
76
+ exports.HttpExceptions = {
77
+ notFound: (message = "") => new NotFoundException(message),
78
+ validationError: (message = "") => new ValidationErrorException(message),
79
+ badRequest: (message = "") => new BadRequestException(message),
80
+ unauthorized: (message = "") => new UnauthorizedException(message),
81
+ forbidden: (message = "") => new ForbiddenException(message),
82
+ internalError: (message = "") => new InternalErrorException(message)
83
+ };
package/dist/icore.d.ts CHANGED
@@ -112,6 +112,8 @@ export interface IAvleonApplication {
112
112
  }
113
113
  type OpenApiConfigClass<T = any> = Constructable<IConfig<T>>;
114
114
  type OpenApiConfigInput<T = any> = OpenApiConfigClass<T> | T;
115
+ type ConfigClass<T = any> = Constructable<IConfig<T>>;
116
+ type ConfigInput<T = any> = ConfigClass<T> | T;
115
117
  export declare class AvleonApplication {
116
118
  private static instance;
117
119
  private static buildOptions;
@@ -134,71 +136,18 @@ export declare class AvleonApplication {
134
136
  private metaCache;
135
137
  private multipartOptions;
136
138
  private constructor();
137
- private isTest;
138
139
  static getApp(): AvleonApplication;
139
140
  static getInternalApp(buildOptions: any): AvleonApplication;
140
141
  isDevelopment(): boolean;
141
142
  private initSwagger;
142
- useCors(corsOptions?: FastifyCorsOptions): void;
143
- useOpenApi<T = OpenApiUiOptions>(configOrClass: OpenApiConfigInput<T>, modifyConfig?: (config: T) => T): void;
144
- /**
145
- * Registers the fastify-multipart plugin with the Fastify instance.
146
- * This enables handling of multipart/form-data requests, typically used for file uploads.
147
- *
148
- * @param {MultipartOptions} options - Options to configure the fastify-multipart plugin.
149
- * @param {FastifyInstance} this.app - The Fastify instance to register the plugin with.
150
- * @property {MultipartOptions} this.multipartOptions - Stores the provided multipart options.
151
- * @see {@link https://github.com/fastify/fastify-multipart} for more details on available options.
152
- */
153
- useMultipart(options: MultipartOptions): void;
154
- /**
155
- * Configures and initializes a TypeORM DataSource based on the provided configuration class.
156
- * It retrieves the configuration from the application's configuration service and allows for optional modification.
157
- * The initialized DataSource is then stored and registered within a dependency injection container.
158
- *
159
- * @template T - A generic type extending the `IConfig` interface, representing the configuration class.
160
- * @template R - A generic type representing the return type of the configuration method of the `ConfigClass`.
161
- * @param {Constructable<T>} ConfigClass - The constructor of the configuration class to be used for creating the DataSource.
162
- * @param {(config: R) => R} [modifyConfig] - An optional function that takes the initial configuration and returns a modified configuration.
163
- * @returns {void}
164
- * @property {DataSourceOptions} this.dataSourceOptions - Stores the final DataSource options after potential modification.
165
- * @property {DataSource} this.dataSource - Stores the initialized TypeORM DataSource instance.
166
- * @see {@link https://typeorm.io/} for more information about TypeORM.
167
- */
168
- useDataSource<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
169
- useCache(options: any): void;
170
- /**
171
- * Registers an array of middleware classes to be executed before request handlers.
172
- * It retrieves instances of the middleware classes from the dependency injection container
173
- * and adds them as 'preHandler' hooks to the Fastify application.
174
- *
175
- * @template T - A generic type extending the `AppMiddleware` interface, representing the middleware class.
176
- * @param {Constructor<T>[]} mclasses - An array of middleware class constructors to be registered.
177
- * @returns {void}
178
- * @property {Map<string, T>} this.middlewares - Stores the registered middleware instances, keyed by their class names.
179
- * @see {@link https://www.fastify.io/docs/latest/Reference/Hooks/#prehandler} for more information about Fastify preHandler hooks.
180
- */
143
+ private _isConfigClass;
144
+ useCors<T = FastifyCorsOptions>(corsOptions?: ConfigInput<T>): void;
145
+ useOpenApi<T = OpenApiUiOptions>(configOrClass: OpenApiConfigInput<T>): void;
146
+ useMultipart<T extends MultipartOptions>(options: ConfigInput<T>): void;
147
+ useDataSource<T extends DataSourceOptions>(options: ConfigInput<T>): void;
148
+ private _useCache;
181
149
  useMiddlewares<T extends AppMiddleware>(mclasses: Constructor<T>[]): void;
182
- /**
183
- * Registers a middleware constructor to be used for authorization purposes.
184
- * The specific implementation and usage of this middleware will depend on the application's authorization logic.
185
- *
186
- * @template T - A generic type representing the constructor of the authorization middleware.
187
- * @param {Constructor<T>} middleware - The constructor of the middleware to be used for authorization.
188
- * @returns {void}
189
- * @property {any} this.authorizeMiddleware - Stores the constructor of the authorization middleware.
190
- */
191
150
  useAuthoriztion<T extends any>(middleware: Constructor<T>): void;
192
- /**
193
- * Registers the `@fastify/static` plugin to serve static files.
194
- * It configures the root directory and URL prefix for serving static assets.
195
- *
196
- * @param {StaticFileOptions} [options={ path: undefined, prefix: undefined }] - Optional configuration for serving static files.
197
- * @param {string} [options.path] - The absolute path to the static files directory. Defaults to 'process.cwd()/public'.
198
- * @param {string} [options.prefix] - The URL prefix for serving static files. Defaults to '/static/'.
199
- * @returns {void}
200
- * @see {@link https://github.com/fastify/fastify-static} for more details on available options.
201
- */
202
151
  useStaticFiles(options?: StaticFileOptions): void;
203
152
  private handleMiddlewares;
204
153
  private executeMiddlewares;
@@ -262,12 +211,8 @@ export interface IAppBuilder {
262
211
  build<T extends IAvleonApplication>(): T;
263
212
  }
264
213
  export declare class AvleonTest {
265
- private static instance;
266
- private app;
267
- private dataSourceOptions?;
268
214
  private constructor();
269
- private addDatasource;
270
- getController<T>(controller: Constructor<T>, deps?: any[]): T;
215
+ static getController<T>(controller: Constructor<T>, deps?: any[]): T;
271
216
  private getService;
272
217
  static createTestApplication(options: TestAppOptions): TestApplication;
273
218
  static from(app: AvleonApplication): TestApplication;
package/dist/icore.js CHANGED
@@ -83,7 +83,6 @@ class AvleonApplication {
83
83
  this.app = (0, fastify_1.default)();
84
84
  this.appConfig = new config_1.AppConfig();
85
85
  }
86
- isTest() { }
87
86
  static getApp() {
88
87
  let isTestEnv = process.env.NODE_ENV == "test";
89
88
  if (!AvleonApplication.instance) {
@@ -151,90 +150,69 @@ class AvleonApplication {
151
150
  });
152
151
  }
153
152
  }
154
- useCors(corsOptions = {}) {
155
- this.app.register(cors_1.default, corsOptions);
153
+ _isConfigClass(input) {
154
+ var _a;
155
+ return (typeof input === 'function' &&
156
+ typeof input.prototype === 'object' &&
157
+ ((_a = input.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === input);
158
+ }
159
+ useCors(corsOptions) {
160
+ let coptions = {};
161
+ if (corsOptions) {
162
+ if (this._isConfigClass(corsOptions)) {
163
+ coptions = this.appConfig.get(corsOptions);
164
+ }
165
+ else {
166
+ coptions = corsOptions;
167
+ }
168
+ }
169
+ this.app.register(cors_1.default, coptions);
156
170
  }
157
- useOpenApi(configOrClass, modifyConfig) {
171
+ useOpenApi(configOrClass) {
158
172
  let openApiConfig;
159
- const isClass = (input) => {
160
- var _a;
161
- return (typeof input === 'function' &&
162
- typeof input.prototype === 'object' &&
163
- ((_a = input.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === input);
164
- };
165
- if (isClass(configOrClass)) {
166
- // It's a class constructor
173
+ if (this._isConfigClass(configOrClass)) {
167
174
  openApiConfig = this.appConfig.get(configOrClass);
168
175
  }
169
176
  else {
170
- // It's a plain object
171
177
  openApiConfig = configOrClass;
172
178
  }
173
- if (modifyConfig) {
174
- this.globalSwaggerOptions = modifyConfig(openApiConfig);
175
- }
176
- else {
177
- this.globalSwaggerOptions = openApiConfig;
178
- }
179
+ this.globalSwaggerOptions = openApiConfig;
179
180
  this.hasSwagger = true;
180
181
  }
181
- /**
182
- * Registers the fastify-multipart plugin with the Fastify instance.
183
- * This enables handling of multipart/form-data requests, typically used for file uploads.
184
- *
185
- * @param {MultipartOptions} options - Options to configure the fastify-multipart plugin.
186
- * @param {FastifyInstance} this.app - The Fastify instance to register the plugin with.
187
- * @property {MultipartOptions} this.multipartOptions - Stores the provided multipart options.
188
- * @see {@link https://github.com/fastify/fastify-multipart} for more details on available options.
189
- */
190
182
  useMultipart(options) {
191
- this.multipartOptions = options;
192
- this.app.register(multipart_1.default, {
193
- ...this.multipartOptions,
194
- attachFieldsToBody: true,
195
- });
183
+ let multipartOptions;
184
+ if (this._isConfigClass(options)) {
185
+ multipartOptions = this.appConfig.get(options);
186
+ }
187
+ else {
188
+ multipartOptions = options;
189
+ }
190
+ if (multipartOptions) {
191
+ this.multipartOptions = multipartOptions;
192
+ this.app.register(multipart_1.default, {
193
+ ...this.multipartOptions,
194
+ attachFieldsToBody: true,
195
+ });
196
+ }
196
197
  }
197
- /**
198
- * Configures and initializes a TypeORM DataSource based on the provided configuration class.
199
- * It retrieves the configuration from the application's configuration service and allows for optional modification.
200
- * The initialized DataSource is then stored and registered within a dependency injection container.
201
- *
202
- * @template T - A generic type extending the `IConfig` interface, representing the configuration class.
203
- * @template R - A generic type representing the return type of the configuration method of the `ConfigClass`.
204
- * @param {Constructable<T>} ConfigClass - The constructor of the configuration class to be used for creating the DataSource.
205
- * @param {(config: R) => R} [modifyConfig] - An optional function that takes the initial configuration and returns a modified configuration.
206
- * @returns {void}
207
- * @property {DataSourceOptions} this.dataSourceOptions - Stores the final DataSource options after potential modification.
208
- * @property {DataSource} this.dataSource - Stores the initialized TypeORM DataSource instance.
209
- * @see {@link https://typeorm.io/} for more information about TypeORM.
210
- */
211
- useDataSource(ConfigClass, modifyConfig) {
212
- const dsConfig = this.appConfig.get(ConfigClass);
213
- if (modifyConfig) {
214
- const modifiedConfig = modifyConfig(dsConfig);
215
- this.dataSourceOptions = modifiedConfig;
198
+ useDataSource(options) {
199
+ let dataSourceOptions;
200
+ if (this._isConfigClass(options)) {
201
+ dataSourceOptions = this.appConfig.get(options);
216
202
  }
217
203
  else {
218
- this.dataSourceOptions = dsConfig;
204
+ dataSourceOptions = options;
219
205
  }
206
+ if (!dataSourceOptions)
207
+ throw new system_exception_1.SystemUseError("Invlaid datasource options.");
208
+ this.dataSourceOptions = dataSourceOptions;
220
209
  const typeorm = require("typeorm");
221
- const datasource = new typeorm.DataSource(dsConfig);
210
+ const datasource = new typeorm.DataSource(dataSourceOptions);
222
211
  this.dataSource = datasource;
223
212
  typedi_1.default.set("idatasource", datasource);
224
213
  }
225
- useCache(options) {
214
+ _useCache(options) {
226
215
  }
227
- /**
228
- * Registers an array of middleware classes to be executed before request handlers.
229
- * It retrieves instances of the middleware classes from the dependency injection container
230
- * and adds them as 'preHandler' hooks to the Fastify application.
231
- *
232
- * @template T - A generic type extending the `AppMiddleware` interface, representing the middleware class.
233
- * @param {Constructor<T>[]} mclasses - An array of middleware class constructors to be registered.
234
- * @returns {void}
235
- * @property {Map<string, T>} this.middlewares - Stores the registered middleware instances, keyed by their class names.
236
- * @see {@link https://www.fastify.io/docs/latest/Reference/Hooks/#prehandler} for more information about Fastify preHandler hooks.
237
- */
238
216
  useMiddlewares(mclasses) {
239
217
  for (const mclass of mclasses) {
240
218
  const cls = typedi_1.default.get(mclass);
@@ -242,28 +220,9 @@ class AvleonApplication {
242
220
  this.app.addHook("preHandler", cls.invoke);
243
221
  }
244
222
  }
245
- /**
246
- * Registers a middleware constructor to be used for authorization purposes.
247
- * The specific implementation and usage of this middleware will depend on the application's authorization logic.
248
- *
249
- * @template T - A generic type representing the constructor of the authorization middleware.
250
- * @param {Constructor<T>} middleware - The constructor of the middleware to be used for authorization.
251
- * @returns {void}
252
- * @property {any} this.authorizeMiddleware - Stores the constructor of the authorization middleware.
253
- */
254
223
  useAuthoriztion(middleware) {
255
224
  this.authorizeMiddleware = middleware;
256
225
  }
257
- /**
258
- * Registers the `@fastify/static` plugin to serve static files.
259
- * It configures the root directory and URL prefix for serving static assets.
260
- *
261
- * @param {StaticFileOptions} [options={ path: undefined, prefix: undefined }] - Optional configuration for serving static files.
262
- * @param {string} [options.path] - The absolute path to the static files directory. Defaults to 'process.cwd()/public'.
263
- * @param {string} [options.prefix] - The URL prefix for serving static files. Defaults to '/static/'.
264
- * @returns {void}
265
- * @see {@link https://github.com/fastify/fastify-static} for more details on available options.
266
- */
267
226
  useStaticFiles(options = { path: undefined, prefix: undefined }) {
268
227
  this.app.register(require("@fastify/static"), {
269
228
  root: options.path ? options.path : path_1.default.join(process.cwd(), "public"),
@@ -744,10 +703,7 @@ class AvleonTest {
744
703
  constructor() {
745
704
  process.env.NODE_ENV = "test";
746
705
  }
747
- addDatasource(options) {
748
- this.dataSourceOptions = options;
749
- }
750
- getController(controller, deps = []) {
706
+ static getController(controller, deps = []) {
751
707
  const paramTypes = Reflect.getMetadata('design:paramtypes', controller) || [];
752
708
  deps.forEach((dep, i) => {
753
709
  typedi_1.default.set(paramTypes[i], dep);
@@ -0,0 +1,27 @@
1
+ interface AvleonApplication {
2
+ useCors: () => void;
3
+ /**
4
+ * function for register database
5
+ * @param options datasource options. options can be plain object or avleon config class
6
+ * */
7
+ useDatasource: () => void;
8
+ useMultipart: () => void;
9
+ useOpenApi: () => void;
10
+ useMiddlewares: () => void;
11
+ useAuthorization: () => void;
12
+ useSerialization: () => void;
13
+ useControllers: () => void;
14
+ useStaticFiles: () => void;
15
+ /**
16
+ * @experimental
17
+ * use https as defalut http protocol
18
+ * */
19
+ useHttps: () => void;
20
+ mapGet: () => void;
21
+ mapPost: () => void;
22
+ mapPut: () => void;
23
+ mapPatch: () => void;
24
+ mapOptions: () => void;
25
+ mapGroup: () => void;
26
+ run: () => void;
27
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -1,5 +1,5 @@
1
1
  import { IRequest, IResponse } from "./icore";
2
- import { HttpException } from "./exceptions";
2
+ import { HttpExceptionTypes as HttpException } from "./exceptions";
3
3
  export declare abstract class AppMiddleware {
4
4
  abstract invoke(req: IRequest, res?: IResponse): Promise<IRequest | HttpException>;
5
5
  }
@@ -14,13 +14,3 @@ export declare class HttpResponse {
14
14
  static Created<T>(obj: any, s?: ClassConstructor<T>): IHttpResponse<T>;
15
15
  static NoContent(): IHttpResponse<null>;
16
16
  }
17
- export declare class HttpExceptions {
18
- static BadRequest(message: string, data?: any): IHttpResponse<any>;
19
- static Unauthorized(message: string, data?: any): IHttpResponse<any>;
20
- static Forbidden(message: string, data?: any): IHttpResponse<any>;
21
- static NotFound(message: string, data?: any): IHttpResponse<any>;
22
- static InternalServerError(message?: string, data?: any): IHttpResponse<any>;
23
- static Conflict(message: string, data?: any): IHttpResponse<any>;
24
- static UnprocessableEntity(message: string, data?: any): IHttpResponse<any>;
25
- static TooManyRequests(message: string, data?: any): IHttpResponse<any>;
26
- }
package/dist/response.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpExceptions = exports.HttpResponse = void 0;
3
+ exports.HttpResponse = void 0;
4
4
  /**
5
5
  * @copyright 2024
6
6
  * @author Tareq Hossain
@@ -54,30 +54,3 @@ class HttpResponse {
54
54
  }
55
55
  }
56
56
  exports.HttpResponse = HttpResponse;
57
- class HttpExceptions {
58
- static BadRequest(message, data = null) {
59
- return { message: message, data: data };
60
- }
61
- static Unauthorized(message, data = null) {
62
- return { message: message, data: data };
63
- }
64
- static Forbidden(message, data = null) {
65
- return { message: message, data: data };
66
- }
67
- static NotFound(message, data = null) {
68
- return { message: message, data: data };
69
- }
70
- static InternalServerError(message = "Internal server error", data = null) {
71
- return { message: message, data: data };
72
- }
73
- static Conflict(message, data = null) {
74
- return { message: message, data: data };
75
- }
76
- static UnprocessableEntity(message, data = null) {
77
- return { message: message, data: data };
78
- }
79
- static TooManyRequests(message, data = null) {
80
- return { message: message, data: data };
81
- }
82
- }
83
- exports.HttpExceptions = HttpExceptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avleon/core",
3
- "version": "0.0.25",
3
+ "version": "0.0.26",
4
4
  "main": "./dist/index.js",
5
5
  "types": ["./dist/icore.d.ts"],
6
6
  "scripts": {
@@ -61,7 +61,7 @@ export class ForbiddenException extends BaseHttpException {
61
61
  }
62
62
  }
63
63
 
64
- export type HttpException =
64
+ export type HttpExceptionTypes =
65
65
  | NotFoundException
66
66
  | BadRequestException
67
67
  | UnauthorizedException
@@ -76,11 +76,11 @@ export type HttpException =
76
76
  // Forbidden: (message: any) => ForbiddenException,
77
77
  // InternalError: (message: any) => InternalErrorException
78
78
  // }
79
- // export const httpExcepitoins: HttpExceptions = {
80
- // NotFound:(message:any)=>new NotFoundException(message),
81
- // ValidationError:(message:any)=>new ValidationErrorException(message),
82
- // BadRequest:(message:any)=>new BadRequestException(message),
83
- // Unauthorized:(message:any)=>new UnauthorizedException(message),
84
- // Forbidden:(message:any)=>new ForbiddenException(message),
85
- // InternalError: (message:any)=> new InternalErrorException(message)
86
- // }
79
+ export const HttpExceptions = {
80
+ notFound:(message:any="")=>new NotFoundException(message),
81
+ validationError:(message:any="")=>new ValidationErrorException(message),
82
+ badRequest:(message:any="")=>new BadRequestException(message),
83
+ unauthorized:(message:any="")=>new UnauthorizedException(message),
84
+ forbidden:(message:any="")=>new ForbiddenException(message),
85
+ internalError: (message:any="")=> new InternalErrorException(message)
86
+ }
package/src/icore.ts CHANGED
@@ -201,7 +201,6 @@ export interface IAvleonApplication {
201
201
  fn: T,
202
202
  ): Promise<void>;
203
203
  mapGet<T extends (...args: any[]) => any>(path: string, fn: T): any;
204
-
205
204
  mapPost<T extends (...args: any[]) => any>(path: string, fn: T): any;
206
205
  mapPut<T extends (...args: any[]) => any>(path: string, fn: T): any;
207
206
  mapDelete<T extends (...args: any[]) => any>(path: string, fn: T): any;
@@ -214,6 +213,9 @@ export interface IAvleonApplication {
214
213
  }
215
214
  type OpenApiConfigClass<T = any> = Constructable<IConfig<T>>;
216
215
  type OpenApiConfigInput<T = any> = OpenApiConfigClass<T> | T;
216
+
217
+ type ConfigClass<T = any> = Constructable<IConfig<T>>;
218
+ type ConfigInput<T = any> = ConfigClass<T> | T;
217
219
  // InternalApplication
218
220
  export class AvleonApplication {
219
221
  private static instance: AvleonApplication;
@@ -242,7 +244,6 @@ export class AvleonApplication {
242
244
  this.appConfig = new AppConfig();
243
245
  }
244
246
 
245
- private isTest() { }
246
247
 
247
248
  static getApp(): AvleonApplication {
248
249
  let isTestEnv = process.env.NODE_ENV == "test";
@@ -323,89 +324,71 @@ export class AvleonApplication {
323
324
  });
324
325
  }
325
326
  }
326
- useCors(corsOptions: FastifyCorsOptions = {}) {
327
- this.app.register(cors, corsOptions);
327
+
328
+ private _isConfigClass<T>(input: any): input is ConfigClass<T> {
329
+ return (
330
+ typeof input === 'function' &&
331
+ typeof input.prototype === 'object' &&
332
+ input.prototype?.constructor === input
333
+ );
334
+ }
335
+ useCors<T = FastifyCorsOptions>(corsOptions?: ConfigInput<T>) {
336
+ let coptions: any = {};
337
+ if (corsOptions) {
338
+ if (this._isConfigClass<T>(corsOptions)) {
339
+ coptions = this.appConfig.get(corsOptions) as T;
340
+ } else {
341
+ coptions = corsOptions as T;
342
+ }
343
+ }
344
+ this.app.register(cors, coptions);
328
345
  }
329
346
 
330
347
  useOpenApi<T = OpenApiUiOptions>(
331
- configOrClass: OpenApiConfigInput<T>,
332
- modifyConfig?: (config: T) => T
348
+ configOrClass: OpenApiConfigInput<T>
333
349
  ) {
334
350
  let openApiConfig: T;
335
-
336
- const isClass = (input: any): input is OpenApiConfigClass<T> => {
337
- return (
338
- typeof input === 'function' &&
339
- typeof input.prototype === 'object' &&
340
- input.prototype?.constructor === input
341
- );
342
- };
343
-
344
- if (isClass(configOrClass)) {
345
- // It's a class constructor
351
+ if (this._isConfigClass(configOrClass)) {
346
352
  openApiConfig = this.appConfig.get(configOrClass);
347
353
  } else {
348
- // It's a plain object
349
354
  openApiConfig = configOrClass as T;
350
355
  }
356
+ this.globalSwaggerOptions = openApiConfig;
357
+ this.hasSwagger = true;
358
+ }
351
359
 
352
- if (modifyConfig) {
353
- this.globalSwaggerOptions = modifyConfig(openApiConfig);
360
+ useMultipart<T extends MultipartOptions>(options: ConfigInput<T>) {
361
+ let multipartOptions: T;
362
+ if (this._isConfigClass(options)) {
363
+ multipartOptions = this.appConfig.get(options);
354
364
  } else {
355
- this.globalSwaggerOptions = openApiConfig;
365
+ multipartOptions = options as T;
366
+ }
367
+ if (multipartOptions) {
368
+ this.multipartOptions = multipartOptions;
369
+ this.app.register(fastifyMultipart, {
370
+ ...this.multipartOptions,
371
+ attachFieldsToBody: true,
372
+ });
356
373
  }
357
-
358
- this.hasSwagger = true;
359
374
  }
360
375
 
361
376
 
362
- /**
363
- * Registers the fastify-multipart plugin with the Fastify instance.
364
- * This enables handling of multipart/form-data requests, typically used for file uploads.
365
- *
366
- * @param {MultipartOptions} options - Options to configure the fastify-multipart plugin.
367
- * @param {FastifyInstance} this.app - The Fastify instance to register the plugin with.
368
- * @property {MultipartOptions} this.multipartOptions - Stores the provided multipart options.
369
- * @see {@link https://github.com/fastify/fastify-multipart} for more details on available options.
370
- */
371
- useMultipart(options: MultipartOptions) {
372
- this.multipartOptions = options;
373
- this.app.register(fastifyMultipart, {
374
- ...this.multipartOptions,
375
- attachFieldsToBody: true,
376
- });
377
- }
377
+ useDataSource<T extends DataSourceOptions>(options: ConfigInput<T>) {
378
378
 
379
-
380
- /**
381
- * Configures and initializes a TypeORM DataSource based on the provided configuration class.
382
- * It retrieves the configuration from the application's configuration service and allows for optional modification.
383
- * The initialized DataSource is then stored and registered within a dependency injection container.
384
- *
385
- * @template T - A generic type extending the `IConfig` interface, representing the configuration class.
386
- * @template R - A generic type representing the return type of the configuration method of the `ConfigClass`.
387
- * @param {Constructable<T>} ConfigClass - The constructor of the configuration class to be used for creating the DataSource.
388
- * @param {(config: R) => R} [modifyConfig] - An optional function that takes the initial configuration and returns a modified configuration.
389
- * @returns {void}
390
- * @property {DataSourceOptions} this.dataSourceOptions - Stores the final DataSource options after potential modification.
391
- * @property {DataSource} this.dataSource - Stores the initialized TypeORM DataSource instance.
392
- * @see {@link https://typeorm.io/} for more information about TypeORM.
393
- */
394
- useDataSource<
395
- T extends IConfig<R>,
396
- R = ReturnType<InstanceType<Constructable<T>>["config"]>,
397
- >(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R) {
398
- const dsConfig: R = this.appConfig.get(ConfigClass);
399
- if (modifyConfig) {
400
- const modifiedConfig: R = modifyConfig(dsConfig);
401
- this.dataSourceOptions = modifiedConfig as unknown as DataSourceOptions;
379
+ let dataSourceOptions: T;
380
+ if (this._isConfigClass(options)) {
381
+ dataSourceOptions = this.appConfig.get(options);
402
382
  } else {
403
- this.dataSourceOptions = dsConfig as unknown as DataSourceOptions;
383
+ dataSourceOptions = options as T;
404
384
  }
405
385
 
386
+ if (!dataSourceOptions) throw new SystemUseError("Invlaid datasource options.")
387
+
388
+ this.dataSourceOptions = dataSourceOptions;
406
389
  const typeorm = require("typeorm");
407
390
  const datasource = new typeorm.DataSource(
408
- dsConfig,
391
+ dataSourceOptions,
409
392
  ) as DataSource;
410
393
 
411
394
  this.dataSource = datasource;
@@ -413,23 +396,16 @@ export class AvleonApplication {
413
396
  Container.set<DataSource>("idatasource",
414
397
  datasource,
415
398
  );
399
+
400
+
416
401
  }
417
402
 
418
- useCache(options: any) {
403
+ private _useCache(options: any) {
419
404
 
420
405
  }
421
406
 
422
- /**
423
- * Registers an array of middleware classes to be executed before request handlers.
424
- * It retrieves instances of the middleware classes from the dependency injection container
425
- * and adds them as 'preHandler' hooks to the Fastify application.
426
- *
427
- * @template T - A generic type extending the `AppMiddleware` interface, representing the middleware class.
428
- * @param {Constructor<T>[]} mclasses - An array of middleware class constructors to be registered.
429
- * @returns {void}
430
- * @property {Map<string, T>} this.middlewares - Stores the registered middleware instances, keyed by their class names.
431
- * @see {@link https://www.fastify.io/docs/latest/Reference/Hooks/#prehandler} for more information about Fastify preHandler hooks.
432
- */
407
+
408
+
433
409
  useMiddlewares<T extends AppMiddleware>(mclasses: Constructor<T>[]) {
434
410
  for (const mclass of mclasses) {
435
411
  const cls = Container.get<T>(mclass);
@@ -439,31 +415,11 @@ export class AvleonApplication {
439
415
  }
440
416
 
441
417
 
442
- /**
443
- * Registers a middleware constructor to be used for authorization purposes.
444
- * The specific implementation and usage of this middleware will depend on the application's authorization logic.
445
- *
446
- * @template T - A generic type representing the constructor of the authorization middleware.
447
- * @param {Constructor<T>} middleware - The constructor of the middleware to be used for authorization.
448
- * @returns {void}
449
- * @property {any} this.authorizeMiddleware - Stores the constructor of the authorization middleware.
450
- */
451
418
  useAuthoriztion<T extends any>(middleware: Constructor<T>) {
452
419
  this.authorizeMiddleware = middleware as any;
453
420
  }
454
421
 
455
422
 
456
-
457
- /**
458
- * Registers the `@fastify/static` plugin to serve static files.
459
- * It configures the root directory and URL prefix for serving static assets.
460
- *
461
- * @param {StaticFileOptions} [options={ path: undefined, prefix: undefined }] - Optional configuration for serving static files.
462
- * @param {string} [options.path] - The absolute path to the static files directory. Defaults to 'process.cwd()/public'.
463
- * @param {string} [options.prefix] - The URL prefix for serving static files. Defaults to '/static/'.
464
- * @returns {void}
465
- * @see {@link https://github.com/fastify/fastify-static} for more details on available options.
466
- */
467
423
  useStaticFiles(
468
424
  options: StaticFileOptions = { path: undefined, prefix: undefined },
469
425
  ) {
@@ -473,10 +429,6 @@ export class AvleonApplication {
473
429
  });
474
430
  }
475
431
 
476
-
477
-
478
-
479
-
480
432
  private handleMiddlewares<T extends AppMiddleware>(
481
433
  mclasses: Constructor<T>[],
482
434
  ) {
@@ -1086,18 +1038,10 @@ export interface IAppBuilder {
1086
1038
  }
1087
1039
 
1088
1040
  export class AvleonTest {
1089
- private static instance: AvleonTest;
1090
- private app: any;
1091
- private dataSourceOptions?: DataSourceOptions | undefined;
1092
1041
  private constructor() {
1093
1042
  process.env.NODE_ENV = "test";
1094
1043
  }
1095
-
1096
- private addDatasource(options: DataSourceOptions) {
1097
- this.dataSourceOptions = options;
1098
- }
1099
-
1100
- getController<T>(controller: Constructor<T>, deps: any[] = []) {
1044
+ static getController<T>(controller: Constructor<T>, deps: any[] = []) {
1101
1045
  const paramTypes = Reflect.getMetadata('design:paramtypes', controller) || [];
1102
1046
 
1103
1047
  deps.forEach((dep, i) => {
@@ -0,0 +1,40 @@
1
+
2
+
3
+ interface AvleonApplication {
4
+
5
+ // all use
6
+ useCors: () => void;
7
+ /**
8
+ * function for register database
9
+ * @param options datasource options. options can be plain object or avleon config class
10
+ * */
11
+ useDatasource: () => void;
12
+ useMultipart: () => void;
13
+ useOpenApi: () => void;
14
+ useMiddlewares: () => void;
15
+ useAuthorization: () => void;
16
+ useSerialization: () => void;
17
+ useControllers: () => void;
18
+ useStaticFiles: () => void;
19
+ /**
20
+ * @experimental
21
+ * use https as defalut http protocol
22
+ * */
23
+ useHttps: () => void;
24
+
25
+
26
+ // all map
27
+ mapGet: () => void;
28
+ mapPost: () => void;
29
+ mapPut: () => void;
30
+ mapPatch: () => void;
31
+ mapOptions: () => void;
32
+ mapGroup: () => void;
33
+ // all others
34
+ // run
35
+ run: () => void;
36
+ }
37
+
38
+
39
+
40
+
package/src/middleware.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { Service } from "typedi";
8
8
  import { IRequest, IResponse } from "./icore";
9
- import { HttpException, UnauthorizedException } from "./exceptions";
9
+ import { HttpExceptionTypes as HttpException, UnauthorizedException } from "./exceptions";
10
10
  import Container, { AUTHORIZATION_META_KEY } from "./container";
11
11
 
12
12
  export abstract class AppMiddleware {
package/src/response.ts CHANGED
@@ -72,46 +72,3 @@ export class HttpResponse {
72
72
  return { message: "no content", data: null };
73
73
  }
74
74
  }
75
-
76
- export class HttpExceptions {
77
- static BadRequest(message: string, data: any = null): IHttpResponse<any> {
78
- return { message: message, data: data };
79
- }
80
-
81
- static Unauthorized(message: string, data: any = null): IHttpResponse<any> {
82
- return { message: message, data: data };
83
- }
84
-
85
- static Forbidden(message: string, data: any = null): IHttpResponse<any> {
86
- return { message: message, data: data };
87
- }
88
-
89
- static NotFound(message: string, data: any = null): IHttpResponse<any> {
90
- return { message: message, data: data };
91
- }
92
-
93
- static InternalServerError(
94
- message: string = "Internal server error",
95
- data: any = null
96
- ): IHttpResponse<any> {
97
- return { message: message, data: data };
98
- }
99
-
100
- static Conflict(message: string, data: any = null): IHttpResponse<any> {
101
- return { message: message, data: data };
102
- }
103
-
104
- static UnprocessableEntity(
105
- message: string,
106
- data: any = null
107
- ): IHttpResponse<any> {
108
- return { message: message, data: data };
109
- }
110
-
111
- static TooManyRequests(
112
- message: string,
113
- data: any = null
114
- ): IHttpResponse<any> {
115
- return { message: message, data: data };
116
- }
117
- }