@avleon/core 0.0.24 → 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.
@@ -1,5 +1,26 @@
1
1
  import { Constructor } from "./helpers";
2
2
  import { RouteShorthandMethod } from "fastify";
3
+ export interface AvleonApplication {
4
+ useCors: () => void;
5
+ useOpenApi: () => void;
6
+ useView: () => void;
7
+ useAuth: () => void;
8
+ useMultipart: () => void;
9
+ useDataSource: () => void;
10
+ useMiddlewares: () => void;
11
+ useControllers: () => void;
12
+ useAutoControllers: () => void;
13
+ useStaticFiles: () => void;
14
+ useCustomErrorHandler: () => void;
15
+ mapGroup: () => any;
16
+ mapGet: () => any;
17
+ mapPost: () => any;
18
+ mapPut: () => any;
19
+ mapPatch: () => any;
20
+ mapDelete: () => any;
21
+ mapView: () => any;
22
+ run: (port: number) => void;
23
+ }
3
24
  export interface InlineRoutes {
4
25
  get: RouteShorthandMethod;
5
26
  post: RouteShorthandMethod;
@@ -0,0 +1,12 @@
1
+ import type { Redis } from 'ioredis';
2
+ export declare class CacheManager {
3
+ private store;
4
+ private tagsMap;
5
+ private redis;
6
+ constructor(redisInstance?: Redis);
7
+ private redisTagKey;
8
+ get<T>(key: string): Promise<T | null>;
9
+ set<T>(key: string, value: T, tags?: string[], ttl?: number): Promise<void>;
10
+ delete(key: string): Promise<void>;
11
+ invalidateTag(tag: string): Promise<void>;
12
+ }
package/dist/cache.js ADDED
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CacheManager = void 0;
4
+ class CacheManager {
5
+ constructor(redisInstance) {
6
+ this.store = new Map();
7
+ this.tagsMap = new Map();
8
+ this.redis = null;
9
+ this.redis = redisInstance || null;
10
+ }
11
+ redisTagKey(tag) {
12
+ return `cache-tags:${tag}`;
13
+ }
14
+ async get(key) {
15
+ if (this.redis) {
16
+ const val = await this.redis.get(key);
17
+ return val ? JSON.parse(val) : null;
18
+ }
19
+ const cached = this.store.get(key);
20
+ return cached ? cached.data : null;
21
+ }
22
+ async set(key, value, tags = [], ttl = 3600) {
23
+ const entry = {
24
+ data: value,
25
+ timestamp: Date.now(),
26
+ };
27
+ if (this.redis) {
28
+ await this.redis.set(key, JSON.stringify(entry.data), 'EX', ttl);
29
+ for (const tag of tags) {
30
+ await this.redis.sadd(this.redisTagKey(tag), key);
31
+ }
32
+ }
33
+ else {
34
+ this.store.set(key, entry);
35
+ for (const tag of tags) {
36
+ if (!this.tagsMap.has(tag))
37
+ this.tagsMap.set(tag, new Set());
38
+ this.tagsMap.get(tag).add(key);
39
+ }
40
+ }
41
+ }
42
+ async delete(key) {
43
+ if (this.redis) {
44
+ await this.redis.del(key);
45
+ // Also clean up from any tag sets
46
+ const tagKeys = await this.redis.keys('cache-tags:*');
47
+ for (const tagKey of tagKeys) {
48
+ await this.redis.srem(tagKey, key);
49
+ }
50
+ }
51
+ else {
52
+ this.store.delete(key);
53
+ for (const keys of this.tagsMap.values()) {
54
+ keys.delete(key);
55
+ }
56
+ }
57
+ }
58
+ async invalidateTag(tag) {
59
+ if (this.redis) {
60
+ const tagKey = this.redisTagKey(tag);
61
+ const keys = await this.redis.smembers(tagKey);
62
+ if (keys.length) {
63
+ await this.redis.del(...keys); // delete all cached keys
64
+ await this.redis.del(tagKey); // delete the tag set
65
+ }
66
+ }
67
+ else {
68
+ const keys = this.tagsMap.get(tag);
69
+ if (keys) {
70
+ for (const key of keys) {
71
+ this.store.delete(key);
72
+ }
73
+ this.tagsMap.delete(tag);
74
+ }
75
+ }
76
+ }
77
+ }
78
+ exports.CacheManager = CacheManager;
@@ -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
@@ -8,7 +8,7 @@ import { FastifyReply, FastifyRequest, HookHandlerDoneFunction, InjectOptions, L
8
8
  import { Constructable } from "typedi";
9
9
  import { Constructor } from "./helpers";
10
10
  import { PathLike } from "fs";
11
- import { DataSourceOptions } from "typeorm";
11
+ import { DataSource, DataSourceOptions } from "typeorm";
12
12
  import { AppMiddleware } from "./middleware";
13
13
  import { OpenApiOptions, OpenApiUiOptions } from "./openapi";
14
14
  import { IConfig } from "./config";
@@ -78,19 +78,24 @@ type MultipartOptions = {
78
78
  } & FastifyMultipartOptions;
79
79
  export type TestAppOptions = {
80
80
  controllers: Constructor[];
81
+ dataSource?: DataSource;
81
82
  };
82
83
  export interface AvleonTestAppliction {
83
84
  addDataSource: (dataSourceOptions: DataSourceOptions) => void;
84
85
  getApp: (options?: TestAppOptions) => any;
85
- getController: <T>(controller: Constructor<T>) => T;
86
+ getController: <T>(controller: Constructor<T>, deps: any[]) => T;
86
87
  }
88
+ export type AutoControllerOptions = {
89
+ auto: true;
90
+ path?: string;
91
+ };
87
92
  export interface IAvleonApplication {
88
93
  isDevelopment(): boolean;
89
94
  useCors(corsOptions?: FastifyCorsOptions): void;
90
95
  useDataSource<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
91
96
  useOpenApi<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
92
- useSwagger(options: OpenApiUiOptions): Promise<void>;
93
97
  useMultipart(options: MultipartOptions): void;
98
+ useCache(options: any): void;
94
99
  useMiddlewares<T extends AppMiddleware>(mclasses: Constructor<T>[]): void;
95
100
  useAuthoriztion<T extends any>(middleware: Constructor<T>): void;
96
101
  mapRoute<T extends (...args: any[]) => any>(method: "get" | "post" | "put" | "delete", path: string, fn: T): Promise<void>;
@@ -98,11 +103,17 @@ export interface IAvleonApplication {
98
103
  mapPost<T extends (...args: any[]) => any>(path: string, fn: T): any;
99
104
  mapPut<T extends (...args: any[]) => any>(path: string, fn: T): any;
100
105
  mapDelete<T extends (...args: any[]) => any>(path: string, fn: T): any;
101
- mapControllers(controllers: any[]): any;
106
+ useControllers(controllers: any[]): any;
107
+ useControllers(controllersOptions: AutoControllerOptions): any;
108
+ useControllers(controllersOrOptions: any[] | AutoControllerOptions): any;
102
109
  useStaticFiles(options?: StaticFileOptions): void;
103
110
  run(port?: number): Promise<void>;
104
111
  getTestApp(): TestApplication;
105
112
  }
113
+ type OpenApiConfigClass<T = any> = Constructable<IConfig<T>>;
114
+ type OpenApiConfigInput<T = any> = OpenApiConfigClass<T> | T;
115
+ type ConfigClass<T = any> = Constructable<IConfig<T>>;
116
+ type ConfigInput<T = any> = ConfigClass<T> | T;
106
117
  export declare class AvleonApplication {
107
118
  private static instance;
108
119
  private static buildOptions;
@@ -120,73 +131,23 @@ export declare class AvleonApplication {
120
131
  private appConfig;
121
132
  private dataSource?;
122
133
  private isMapFeatures;
134
+ private registerControllerAuto;
135
+ private registerControllerPath;
123
136
  private metaCache;
124
137
  private multipartOptions;
125
138
  private constructor();
126
- private isTest;
127
139
  static getApp(): AvleonApplication;
128
140
  static getInternalApp(buildOptions: any): AvleonApplication;
129
141
  isDevelopment(): boolean;
130
142
  private initSwagger;
131
- useCors(corsOptions?: FastifyCorsOptions): void;
132
- useOpenApi<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
133
- /**
134
- * Registers the fastify-multipart plugin with the Fastify instance.
135
- * This enables handling of multipart/form-data requests, typically used for file uploads.
136
- *
137
- * @param {MultipartOptions} options - Options to configure the fastify-multipart plugin.
138
- * @param {FastifyInstance} this.app - The Fastify instance to register the plugin with.
139
- * @property {MultipartOptions} this.multipartOptions - Stores the provided multipart options.
140
- * @see {@link https://github.com/fastify/fastify-multipart} for more details on available options.
141
- */
142
- useMultipart(options: MultipartOptions): void;
143
- /**
144
- * Configures and initializes a TypeORM DataSource based on the provided configuration class.
145
- * It retrieves the configuration from the application's configuration service and allows for optional modification.
146
- * The initialized DataSource is then stored and registered within a dependency injection container.
147
- *
148
- * @template T - A generic type extending the `IConfig` interface, representing the configuration class.
149
- * @template R - A generic type representing the return type of the configuration method of the `ConfigClass`.
150
- * @param {Constructable<T>} ConfigClass - The constructor of the configuration class to be used for creating the DataSource.
151
- * @param {(config: R) => R} [modifyConfig] - An optional function that takes the initial configuration and returns a modified configuration.
152
- * @returns {void}
153
- * @property {DataSourceOptions} this.dataSourceOptions - Stores the final DataSource options after potential modification.
154
- * @property {DataSource} this.dataSource - Stores the initialized TypeORM DataSource instance.
155
- * @see {@link https://typeorm.io/} for more information about TypeORM.
156
- */
157
- useDataSource<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
158
- /**
159
- * Registers an array of middleware classes to be executed before request handlers.
160
- * It retrieves instances of the middleware classes from the dependency injection container
161
- * and adds them as 'preHandler' hooks to the Fastify application.
162
- *
163
- * @template T - A generic type extending the `AppMiddleware` interface, representing the middleware class.
164
- * @param {Constructor<T>[]} mclasses - An array of middleware class constructors to be registered.
165
- * @returns {void}
166
- * @property {Map<string, T>} this.middlewares - Stores the registered middleware instances, keyed by their class names.
167
- * @see {@link https://www.fastify.io/docs/latest/Reference/Hooks/#prehandler} for more information about Fastify preHandler hooks.
168
- */
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;
169
149
  useMiddlewares<T extends AppMiddleware>(mclasses: Constructor<T>[]): void;
170
- /**
171
- * Registers a middleware constructor to be used for authorization purposes.
172
- * The specific implementation and usage of this middleware will depend on the application's authorization logic.
173
- *
174
- * @template T - A generic type representing the constructor of the authorization middleware.
175
- * @param {Constructor<T>} middleware - The constructor of the middleware to be used for authorization.
176
- * @returns {void}
177
- * @property {any} this.authorizeMiddleware - Stores the constructor of the authorization middleware.
178
- */
179
150
  useAuthoriztion<T extends any>(middleware: Constructor<T>): void;
180
- /**
181
- * Registers the `@fastify/static` plugin to serve static files.
182
- * It configures the root directory and URL prefix for serving static assets.
183
- *
184
- * @param {StaticFileOptions} [options={ path: undefined, prefix: undefined }] - Optional configuration for serving static files.
185
- * @param {string} [options.path] - The absolute path to the static files directory. Defaults to 'process.cwd()/public'.
186
- * @param {string} [options.prefix] - The URL prefix for serving static files. Defaults to '/static/'.
187
- * @returns {void}
188
- * @see {@link https://github.com/fastify/fastify-static} for more details on available options.
189
- */
190
151
  useStaticFiles(options?: StaticFileOptions): void;
191
152
  private handleMiddlewares;
192
153
  private executeMiddlewares;
@@ -210,12 +171,10 @@ export declare class AvleonApplication {
210
171
  * @returns
211
172
  */
212
173
  private _processMeta;
213
- autoControllers(): Promise<void>;
214
- mapControllers(controllers: Function[]): void;
215
- mapFeature(): void;
174
+ private _resolveControllerDir;
175
+ private autoControllers;
176
+ useControllers(controllers: Constructor[] | AutoControllerOptions): void;
216
177
  private _mapControllers;
217
- mapControllersAuto(): void;
218
- handleRoute(args: any): Promise<void>;
219
178
  private mapFn;
220
179
  private _handleError;
221
180
  mapRoute<T extends (...args: any[]) => any>(method: "get" | "post" | "put" | "delete", path: string | undefined, fn: T): Promise<void>;
@@ -251,20 +210,15 @@ export interface IAppBuilder {
251
210
  addDataSource<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>, modifyConfig?: (config: R) => R): void;
252
211
  build<T extends IAvleonApplication>(): T;
253
212
  }
254
- export declare class TestBuilder {
255
- private static instance;
256
- private app;
257
- private dataSourceOptions?;
213
+ export declare class AvleonTest {
258
214
  private constructor();
259
- static createBuilder(): TestBuilder;
260
- addDatasource(options: DataSourceOptions): void;
261
- private getController;
215
+ static getController<T>(controller: Constructor<T>, deps?: any[]): T;
262
216
  private getService;
263
- getTestApplication(options: TestAppOptions): TestApplication;
264
- build(app: IAvleonApplication): TestApplication;
265
- fromApplication(app: IAvleonApplication): TestApplication;
217
+ static createTestApplication(options: TestAppOptions): TestApplication;
218
+ static from(app: AvleonApplication): TestApplication;
219
+ static clean(): void;
266
220
  }
267
- export declare class Builder {
221
+ export declare class Avleon {
268
222
  static createApplication(): AvleonApplication;
269
223
  }
270
224
  export {};