@avleon/core 0.0.19 → 0.0.24

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 (72) hide show
  1. package/README.md +559 -2
  2. package/dist/application.d.ts +26 -0
  3. package/dist/application.js +50 -0
  4. package/dist/collection.js +3 -2
  5. package/dist/container.d.ts +1 -0
  6. package/dist/container.js +2 -1
  7. package/dist/environment-variables.js +1 -1
  8. package/dist/file-storage.js +0 -128
  9. package/dist/helpers.d.ts +2 -0
  10. package/dist/helpers.js +41 -4
  11. package/dist/icore.d.ts +68 -26
  12. package/dist/icore.js +235 -212
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +4 -2
  15. package/dist/middleware.js +0 -8
  16. package/dist/multipart.js +4 -1
  17. package/dist/openapi.d.ts +37 -37
  18. package/dist/params.js +2 -2
  19. package/dist/response.js +6 -2
  20. package/dist/route-methods.js +1 -1
  21. package/dist/swagger-schema.js +4 -1
  22. package/dist/testing.js +5 -2
  23. package/dist/utils/index.d.ts +2 -0
  24. package/dist/utils/index.js +18 -0
  25. package/dist/utils/optional-require.d.ts +8 -0
  26. package/dist/utils/optional-require.js +70 -0
  27. package/dist/validation.d.ts +4 -1
  28. package/dist/validation.js +10 -5
  29. package/package.json +19 -11
  30. package/src/application.ts +96 -0
  31. package/src/authentication.ts +16 -0
  32. package/src/collection.ts +254 -0
  33. package/src/config.ts +39 -0
  34. package/src/constants.ts +1 -0
  35. package/src/container.ts +54 -0
  36. package/src/controller.ts +128 -0
  37. package/src/decorators.ts +27 -0
  38. package/src/environment-variables.ts +46 -0
  39. package/src/exceptions/http-exceptions.ts +86 -0
  40. package/src/exceptions/index.ts +1 -0
  41. package/src/exceptions/system-exception.ts +34 -0
  42. package/src/file-storage.ts +206 -0
  43. package/src/helpers.ts +328 -0
  44. package/src/icore.ts +1064 -0
  45. package/src/index.ts +30 -0
  46. package/src/logger.ts +72 -0
  47. package/src/map-types.ts +159 -0
  48. package/src/middleware.ts +98 -0
  49. package/src/multipart.ts +116 -0
  50. package/src/openapi.ts +372 -0
  51. package/src/params.ts +111 -0
  52. package/src/queue.ts +126 -0
  53. package/src/response.ts +117 -0
  54. package/src/results.ts +30 -0
  55. package/src/route-methods.ts +186 -0
  56. package/src/swagger-schema.ts +213 -0
  57. package/src/testing.ts +220 -0
  58. package/src/types/app-builder.interface.ts +19 -0
  59. package/src/types/application.interface.ts +9 -0
  60. package/src/utils/hash.ts +5 -0
  61. package/src/utils/index.ts +2 -0
  62. package/src/utils/optional-require.ts +50 -0
  63. package/src/validation.ts +156 -0
  64. package/src/validator-extend.ts +25 -0
  65. package/dist/classToOpenapi.d.ts +0 -0
  66. package/dist/classToOpenapi.js +0 -1
  67. package/dist/render.d.ts +0 -1
  68. package/dist/render.js +0 -8
  69. package/jest.config.ts +0 -9
  70. package/tsconfig.json +0 -25
  71. /package/dist/{security.d.ts → utils/hash.d.ts} +0 -0
  72. /package/dist/{security.js → utils/hash.js} +0 -0
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+
8
+ export type CurrentUser = {};
9
+
10
+ export abstract class BaseAuthetication {
11
+ abstract authenticate(): Promise<Boolean>;
12
+ abstract authorize(): Promise<Boolean>;
13
+ }
14
+
15
+ export function Authorized() {}
16
+ export function CurrentUser() {}
@@ -0,0 +1,254 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ import Container from "typedi";
8
+ import { NotFoundException } from "./exceptions";
9
+ import {
10
+ DataSource,
11
+ EntityTarget,
12
+ FindOneOptions,
13
+ ObjectLiteral,
14
+ Repository,
15
+ } from "typeorm";
16
+ import { UpsertOptions } from "typeorm/repository/UpsertOptions";
17
+
18
+ type ObjKey<T> = keyof T;
19
+ type ObjKeys<T> = ObjKey<T>[];
20
+ type PaginationOptions = {
21
+ take: number;
22
+ skip?: number;
23
+ };
24
+
25
+ type Predicate<T> = (item: T) => boolean;
26
+ interface TypeormEnitity extends ObjectLiteral {}
27
+
28
+ export type PaginationResult<T> = {
29
+ total: number;
30
+ data: T[];
31
+ next?: number | null;
32
+ prev?: number | null;
33
+ first?: number | null;
34
+ last?: number | null;
35
+ totalPage?: number;
36
+ };
37
+
38
+ type ICollection<T> = {
39
+ findAll(): T[] | Promise<T[]>;
40
+ };
41
+
42
+ type EntityCollection<T extends ObjectLiteral> = {};
43
+
44
+ class BasicCollection<T> implements ICollection<T> {
45
+ private items: T[];
46
+
47
+ private constructor(items: T[]) {
48
+ this.items = items;
49
+ }
50
+
51
+ static from<T>(items: T[]): BasicCollection<T> {
52
+ return new BasicCollection(items);
53
+ }
54
+
55
+ findAll(predicate?: Predicate<T>) {
56
+ const results = Array.from(this.items);
57
+ return results;
58
+ }
59
+
60
+ findOne(predicate: Predicate<T> | FindOneOptions<T>): T | Promise<T | null> {
61
+ if (this.isFunction(predicate)) {
62
+ return this.items.find(predicate as Predicate<T>) as T;
63
+ }
64
+ throw new Error("Invalid predicate type");
65
+ }
66
+
67
+ // Utility function to check if a value is a function
68
+ private isFunction(value: unknown): value is Function {
69
+ return typeof value === "function";
70
+ }
71
+
72
+ add(item: Partial<T>): T;
73
+ add(item: Partial<T>): T | Promise<T> {
74
+ this.items.push(item as T);
75
+ return this.items[this.items.length - 1];
76
+ }
77
+
78
+ addAll(items: T[]): void {
79
+ this.items.push(...items);
80
+ }
81
+ update(predicate: (item: T) => boolean, updater: Partial<T>): void {
82
+ const item = this.items.find(predicate);
83
+ if (item) {
84
+ const index = this.items.indexOf(item)!;
85
+ this.items[index] = { ...item, ...updater };
86
+ } else {
87
+ throw new NotFoundException("Item not found");
88
+ }
89
+ }
90
+
91
+ updateAll(predicate: (item: T) => boolean, updater: (item: T) => T): void {
92
+ for (let i = 0; i < this.items.length; i++) {
93
+ if (predicate(this.items[i])) {
94
+ this.items[i] = updater(this.items[i]);
95
+ }
96
+ }
97
+ }
98
+ delete(predicate: (item: T) => boolean): void {
99
+ const index = this.items.findIndex(predicate);
100
+ if (index !== -1) {
101
+ this.items.splice(index, 1);
102
+ }
103
+ }
104
+ deleteAll(predicate: (item: T) => boolean): void {
105
+ this.items = this.items.filter((item) => !predicate(item));
106
+ }
107
+ max<K extends keyof T>(key: K & string): number {
108
+ return Math.max(...this.items.map((item) => item[key] as number));
109
+ }
110
+
111
+ min<K extends keyof T>(key: K & string): number {
112
+ return Math.max(...this.items.map((item) => item[key] as number));
113
+ }
114
+
115
+ sum<K extends keyof T>(key: K & string): number {
116
+ const nums = this.items.flatMap((x) => x[key]) as number[];
117
+ return nums.reduce((sum, num) => sum + num, 0);
118
+ }
119
+
120
+ avg<K extends keyof T>(key: K & string): number {
121
+ const nums = this.items.flatMap((x) => x[key]) as number[];
122
+ return nums.reduce((sum, num) => sum + num, 0) / nums.length;
123
+ }
124
+
125
+ paginate(options?: PaginationOptions) {
126
+ const take = options?.take || 10;
127
+ const skip = options?.skip || 0;
128
+ const total = this.items.length;
129
+ const data = this.items.slice(skip, take);
130
+ return {
131
+ total,
132
+ totalPage: Math.ceil(total / take),
133
+ next: skip + take < total ? skip + take : null,
134
+ data,
135
+ };
136
+ }
137
+
138
+ private getDeepValue(item: any, path: string | keyof T): any {
139
+ if (typeof path !== "string") return item[path];
140
+ return path.split(".").reduce((acc, key) => acc?.[key], item);
141
+ }
142
+ }
143
+
144
+ class AsynchronousCollection<T extends ObjectLiteral> {
145
+ private model: EntityTarget<T>;
146
+ private repo?: Repository<T>;
147
+
148
+ private constructor(model: EntityTarget<T>) {
149
+ this.model = model;
150
+ }
151
+
152
+ static fromRepository<T extends ObjectLiteral>(
153
+ model: EntityTarget<T>,
154
+ ): AsynchronousCollection<T> {
155
+ return new AsynchronousCollection(model);
156
+ }
157
+
158
+ getRepository() {
159
+ if (!this.repo) {
160
+ const dataSourceKey = "idatasource";
161
+ const dataSource = Container.get(dataSourceKey) as DataSource;
162
+ console.log('datasource', dataSource);
163
+ const repository = dataSource.getRepository<T>(this.model);
164
+ this.repo = repository;
165
+ return repository;
166
+ }
167
+ return this.repo;
168
+ }
169
+
170
+ // Pagination with query builder
171
+ async paginate(options?: PaginationOptions): Promise<PaginationResult<T>> {
172
+ const take = options?.take || 10;
173
+ const skip = options?.skip || 0;
174
+
175
+ const [data, total] = await this.getRepository().findAndCount({
176
+ take,
177
+ skip,
178
+ });
179
+
180
+ return {
181
+ total,
182
+ totalPage: Math.ceil(total / take),
183
+ next: skip + take < total ? skip + take : null,
184
+ prev: skip + take < total ? skip + take : null,
185
+ data,
186
+ };
187
+ }
188
+ }
189
+
190
+ export class Collection {
191
+ private constructor() {}
192
+
193
+ static from<T>(items: T[]): BasicCollection<T> {
194
+ return BasicCollection.from(items);
195
+ }
196
+ // Example refactoring of Collection.fromRepository for better type safety
197
+ static fromRepository<T extends ObjectLiteral>(
198
+ entity: EntityTarget<T>,
199
+ ): Repository<T> {
200
+ const asyncCollection = AsynchronousCollection.fromRepository(entity);
201
+ // Assuming AsynchronousCollection has a method to get the Repository<T>
202
+ return asyncCollection.getRepository();
203
+ }
204
+ }
205
+
206
+ export function InjectRepository<T extends Repository<T>>(
207
+ model: EntityTarget<T>,
208
+ ) {
209
+ return function (
210
+ object: any,
211
+ propertyName: string | undefined,
212
+ index?: number,
213
+ ) {
214
+ let repo!: any | Repository<T>;
215
+ try {
216
+ Container.registerHandler({
217
+ object,
218
+ propertyName,
219
+ index,
220
+ value: (containerInstance) => {
221
+ const dataSource = containerInstance.get<DataSource>("idatasource");
222
+
223
+ repo = dataSource
224
+ .getRepository<T>(model)
225
+ .extend({ paginate: () => {} });
226
+ repo.paginate = async function (
227
+ options: PaginationOptions = { take: 10, skip: 0 },
228
+ ): Promise<PaginationResult<T>> {
229
+ const [data, total] = await this.findAndCount({
230
+ take: options.take || 10,
231
+ skip: options.skip || 0,
232
+ });
233
+
234
+ return {
235
+ total,
236
+ totalPage: Math.ceil(total / (options.take || 10)),
237
+ next:
238
+ options.skip! + options.take! < total
239
+ ? options.skip! + options.take!
240
+ : null,
241
+ data,
242
+ };
243
+ };
244
+ return repo;
245
+ },
246
+ });
247
+ } catch (error: any) {
248
+ console.log(error);
249
+ if (error.name && error.name == "ServiceNotFoundError") {
250
+ console.log("Database didn't initialized.");
251
+ }
252
+ }
253
+ };
254
+ }
package/src/config.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ import { Container, Service, Constructable } from "typedi";
8
+ import { Environment } from "./environment-variables";
9
+
10
+ export interface IConfig<T = any> {
11
+ config(env: Environment): T;
12
+ }
13
+
14
+ export function Config<T extends IConfig>(target: Constructable<T>) {
15
+ Container.set({ id: target, type: target });
16
+ }
17
+
18
+ export class AppConfig {
19
+ get<T extends IConfig<R>, R>(configClass: Constructable<T>): R {
20
+ const instance = Container.get(configClass);
21
+ if (!instance) {
22
+ throw new Error(`Configuration for ${configClass.name} not found.`);
23
+ }
24
+ return instance.config(new Environment());
25
+ }
26
+ }
27
+
28
+ export function GetConfig<
29
+ T extends IConfig<R>,
30
+ R = ReturnType<InstanceType<Constructable<T>>["config"]>,
31
+ >(ConfigClass: Constructable<T>): R {
32
+ const instance = Container.get(ConfigClass);
33
+ if (!instance) {
34
+ throw new Error(
35
+ `Class "${ConfigClass.name}" is not registered as a config.`,
36
+ );
37
+ }
38
+ return instance.config(new Environment());
39
+ }
@@ -0,0 +1 @@
1
+ export const TEST_DATASOURCE_OPTIONS_KEY = Symbol("itestdatasource");
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ import TypediContainer, { ContainerInstance, Token } from "typedi";
8
+ import { DataSource } from "typeorm";
9
+
10
+ export const FEATURE_KEY = Symbol.for("features");
11
+ export const ROUTE_META_KEY = Symbol("iroute:options");
12
+ export const CONTROLLER_META_KEY = Symbol("icontroller:options");
13
+ export const PARAM_META_KEY = Symbol("iparam:options");
14
+ export const QUERY_META_KEY = Symbol("iparam:options");
15
+ export const REQUEST_BODY_META_KEY = Symbol("iparam:options");
16
+ export const REQUEST_BODY_FILE_KEY = Symbol("iparam:options");
17
+ export const REQUEST_BODY_FILES_KEY = Symbol("iparam:options");
18
+ export const REQUEST_USER_META_KEY = Symbol("iparam:options");
19
+ export const REQUEST_HEADER_META_KEY = Symbol("iheader:options");
20
+ export const DATASOURCE_META_KEY = Symbol("idatasource:options");
21
+ export const AUTHORIZATION_META_KEY = Symbol("idatasource:authorization");
22
+
23
+ const controllerRegistry = new Set<Function>();
24
+ const serviceRegistry = new Set<Function>();
25
+ const optionsRegistry = new Map<string, any>();
26
+
27
+ const Container = TypediContainer;
28
+
29
+ export function registerController(controller: Function) {
30
+ controllerRegistry.add(controller);
31
+ }
32
+ export function registerService(service: Function) {
33
+ Container.set(service, service);
34
+ serviceRegistry.add(service);
35
+ }
36
+
37
+ export function getRegisteredServices(): Function[] {
38
+ return Array.from(serviceRegistry);
39
+ }
40
+ export function getRegisteredControllers(): Function[] {
41
+ return Array.from(controllerRegistry);
42
+ }
43
+
44
+ export const API_CONTROLLER_METADATA_KEY = Symbol("apiController");
45
+
46
+ export function isApiController(target: Function): boolean {
47
+ return Reflect.getMetadata(API_CONTROLLER_METADATA_KEY, target) === true;
48
+ }
49
+ Container.set<string>("appName", "Iqra");
50
+
51
+ export function registerDataSource(dataSource: any) {
52
+ Container.set<DataSource>("idatasource", dataSource);
53
+ }
54
+ export default Container;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+
8
+
9
+ import Container, { Service } from "typedi";
10
+ import container, {
11
+ API_CONTROLLER_METADATA_KEY,
12
+ CONTROLLER_META_KEY,
13
+ registerController,
14
+ } from "./container";
15
+
16
+ /**
17
+ * Options for configuring a controller.
18
+ * @remarks
19
+ * Controller default options
20
+ * @type {Object} ControllerOptions
21
+ * @property {string} [name] - The name of the controller.
22
+ * @property {string} [path] - The base path for the controller's routes.
23
+ * @property {string} [version] - The version of the controller. If not provided, it will default to the version from `package.json`.
24
+ * @property {string} [since] - The date or version since the controller was introduced.
25
+ * @property {any} [meta] - Additional metadata associated with the controller.
26
+ */
27
+ export type ControllerOptions = {
28
+ /**
29
+ *@property {string} name
30
+ *@description Name of the controller. If specified it'll used as swagger tags
31
+ *@default Contorller class name
32
+ * */
33
+ name?: string;
34
+ path?: string;
35
+ version?: string; // Will look at package.json if not set
36
+ since?: string;
37
+ meta?: any;
38
+ };
39
+
40
+ export function createControllerDecorator(
41
+ type: "api" | "web" = "web",
42
+ ): (
43
+ pathOrOptions?: string | ControllerOptions,
44
+ maybeOptions?: ControllerOptions,
45
+ ) => ClassDecorator {
46
+ return function (
47
+ pathOrOptions?: string | ControllerOptions,
48
+ maybeOptions?: ControllerOptions,
49
+ ): ClassDecorator {
50
+ return function (target: Function) {
51
+ let path = "/";
52
+ let options: ControllerOptions = {};
53
+
54
+ if (typeof pathOrOptions === "string") {
55
+ path = pathOrOptions;
56
+ options = maybeOptions || {};
57
+ } else if (typeof pathOrOptions === "object") {
58
+ options = pathOrOptions;
59
+ path = options.path || "/";
60
+ }
61
+ Reflect.defineMetadata(API_CONTROLLER_METADATA_KEY, true, target);
62
+ // Ensure Service is applied as a ClassDecorator
63
+ if (typeof Service === "function") {
64
+ registerController(target); // Add to custom registry
65
+ Service()(target); // Apply DI decorator
66
+ Reflect.defineMetadata(
67
+ CONTROLLER_META_KEY,
68
+ { type, path, options },
69
+ target,
70
+ );
71
+ } else {
72
+ throw new Error("Service decorator is not a function");
73
+ }
74
+ };
75
+ };
76
+ }
77
+
78
+ // Predefined Controller Decorators
79
+ //export const Controller = createControllerDecorator("web");
80
+ /**
81
+ *@description Api controller's are used for rest . It will populate
82
+ * json on return and all it http methods {get} {post} etc must return
83
+ *Results.*
84
+ * @param path {string} this will used as route prefix
85
+ *
86
+ **/
87
+
88
+ export function ApiController(target: Function): void;
89
+ export function ApiController(path: string): ClassDecorator;
90
+ /**
91
+ *@description Api controller's are used for rest . It will populate
92
+ * json on return and all it http methods {get} {post} etc must return
93
+ * Results.*
94
+ * @param {ControllerOptions} options this will used as route prefix
95
+ *
96
+ **/
97
+ export function ApiController(options: ControllerOptions): ClassDecorator;
98
+ export function ApiController(
99
+ path: string,
100
+ options?: ControllerOptions,
101
+ ): ClassDecorator;
102
+ export function ApiController(
103
+ pathOrOptions: Function |string | ControllerOptions = "/",
104
+ mayBeOptions?: ControllerOptions,
105
+ ): any {
106
+ if (typeof pathOrOptions == 'function') {
107
+ Reflect.defineMetadata(API_CONTROLLER_METADATA_KEY, true, pathOrOptions);
108
+ // Ensure Service is applied as a ClassDecorator
109
+ if (typeof Service === "function") {
110
+ registerController(pathOrOptions); // Add to custom registry
111
+ Service()(pathOrOptions); // Apply DI decorator
112
+ Reflect.defineMetadata(
113
+ CONTROLLER_META_KEY,
114
+ { type: 'api', path: "/", options: {} },
115
+ pathOrOptions,
116
+ );
117
+ } else {
118
+ throw new Error("Service decorator is not a function");
119
+ }
120
+ } else {
121
+ if (mayBeOptions) {
122
+ return createControllerDecorator("api")(pathOrOptions, mayBeOptions);
123
+ }
124
+ return createControllerDecorator("api")(pathOrOptions);
125
+ }
126
+
127
+ }
128
+
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+
8
+ import { Service as _service } from "typedi";
9
+ import container, { registerService } from "./container";
10
+ export function AppService(target: any): void;
11
+ export function AppService(): any;
12
+ export function AppService(target?: any) {
13
+ if (target) {
14
+ _service()(target);
15
+ } else {
16
+ return function (tg: any) {
17
+ _service()(tg);
18
+ };
19
+ }
20
+ }
21
+
22
+ export * from "./controller";
23
+ export * from "./route-methods";
24
+ export * from "./openapi";
25
+ export const Utility = _service;
26
+ export const Helper = _service;
27
+ export * from "./params";
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+
8
+ import dotenv from "dotenv";
9
+ import path from "path";
10
+ import fs from "fs";
11
+ import { Service } from "typedi";
12
+ import { EnvironmentVariableNotFound, SystemUseError } from "./exceptions/system-exception";
13
+
14
+ dotenv.config({ path: path.join(process.cwd(), ".env") });
15
+
16
+ @Service()
17
+ export class Environment {
18
+ private parseEnvFile(filePath: string): any {
19
+ try {
20
+ const fileContent = fs.readFileSync(filePath, 'utf8');
21
+ const parsedEnv = dotenv.parse(fileContent);
22
+ return { ...parsedEnv, ...process.env };
23
+ } catch (error) {
24
+ console.error(`Error parsing .env file: ${error}`);
25
+ return {};
26
+ }
27
+ }
28
+
29
+ get<T = any>(key: string): T {
30
+ const parsedEnv = this.parseEnvFile(path.join(process.cwd(), '.env'));
31
+ return parsedEnv[key] as T;
32
+ }
33
+
34
+ getOrThrow<T = any>(key: string): T {
35
+ const parsedEnv = this.parseEnvFile(path.join(process.cwd(), '.env'));
36
+ if (!Object(parsedEnv).hasOwnProperty(key)) {
37
+ throw new EnvironmentVariableNotFound(key)
38
+ }
39
+ return parsedEnv[key] as T;
40
+ }
41
+
42
+ getAll<T = any>(): T {
43
+ const parsedEnv = this.parseEnvFile(path.join(process.cwd(), '.env'));
44
+ return parsedEnv as T;
45
+ }
46
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ export abstract class BaseHttpException extends Error {
8
+ code: number = 500;
9
+ name: string = "HttpException";
10
+ constructor(message: any) {
11
+ super(JSON.stringify(message));
12
+ }
13
+ isCustomException() {
14
+ return true;
15
+ }
16
+ }
17
+
18
+ export class BadRequestException extends BaseHttpException {
19
+ name: string = "BadRequest";
20
+ code: number = 400;
21
+
22
+ constructor(message: any) {
23
+ super(message);
24
+ }
25
+ }
26
+
27
+ export class ValidationErrorException extends BadRequestException {
28
+ name: string = "ValidationError";
29
+ }
30
+
31
+ export class InternalErrorException extends BaseHttpException {
32
+ name: string = "InternalError";
33
+ code: number = 500;
34
+
35
+ constructor(message: any = "Something going wrong") {
36
+ super(message);
37
+ }
38
+ }
39
+
40
+ export class NotFoundException extends BaseHttpException {
41
+ name: string = "NotFound";
42
+ code: number = 404;
43
+ constructor(message: any) {
44
+ super(message);
45
+ }
46
+ }
47
+
48
+ export class UnauthorizedException extends BaseHttpException {
49
+ name: string = "Unauthorized";
50
+ code: number = 401;
51
+ constructor(message: any) {
52
+ super(message);
53
+ }
54
+ }
55
+
56
+ export class ForbiddenException extends BaseHttpException {
57
+ name: string = "Forbidden";
58
+ code: number = 403;
59
+ constructor(message: any) {
60
+ super(message);
61
+ }
62
+ }
63
+
64
+ export type HttpException =
65
+ | NotFoundException
66
+ | BadRequestException
67
+ | UnauthorizedException
68
+ | InternalErrorException
69
+ | ForbiddenException;
70
+
71
+ // export type HttpExceptions = {
72
+ // NotFound: (message: any) => NotFoundException,
73
+ // ValidationError: (message: any) =>ValidationErrorException,
74
+ // BadRequest: (message: any) => BadRequestException,
75
+ // Unauthorized: (message: any) => UnauthorizedException,
76
+ // Forbidden: (message: any) => ForbiddenException,
77
+ // InternalError: (message: any) => InternalErrorException
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
+ // }
@@ -0,0 +1 @@
1
+ export * from './http-exceptions';
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ export interface IRouteDuplicateErr {
8
+ path: string,
9
+ mpath: string,
10
+ method: string,
11
+ controller: string,
12
+ inverseController?: string
13
+ }
14
+
15
+ export class SystemUseError extends Error {
16
+ constructor(message: string) {
17
+ super(message);
18
+ }
19
+ }
20
+ export class DuplicateRouteException extends Error {
21
+ constructor(params: IRouteDuplicateErr) {
22
+ let sameController = params.controller == params.inverseController;
23
+ let message = `Duplicate route found for method ${params.method.toUpperCase()}:${params.path == "" ? "'/'" : params.path} `
24
+ message += sameController ? `in ${params.controller}` : `both in ${params.controller} and ${params.inverseController}`;
25
+ super(message);
26
+ }
27
+ }
28
+
29
+
30
+ export class EnvironmentVariableNotFound extends Error{
31
+ constructor(key: string) {
32
+ super(`${key} not found in environment variables.`)
33
+ }
34
+ }