@avleon/core 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,4 @@
1
1
  # avleon-core
2
+
3
+
4
+ # Api (V0.0.)
@@ -0,0 +1,9 @@
1
+ export type CurrentUser = {};
2
+ export declare abstract class Authetication {
3
+ abstract login(): void;
4
+ abstract register(): void;
5
+ abstract verifyToken(): boolean;
6
+ abstract currentUser(): CurrentUser;
7
+ }
8
+ export declare function Authorized(): void;
9
+ export declare function CurrentUser(): void;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Authetication = void 0;
4
+ exports.Authorized = Authorized;
5
+ exports.CurrentUser = CurrentUser;
6
+ class Authetication {
7
+ }
8
+ exports.Authetication = Authetication;
9
+ function Authorized() {
10
+ }
11
+ function CurrentUser() { }
@@ -0,0 +1,52 @@
1
+ import { EntityTarget, FindOneOptions, ObjectLiteral, Repository as TypeOrmRepository } from "typeorm";
2
+ type PaginationOptions = {
3
+ take: number;
4
+ skip?: number;
5
+ };
6
+ type Predicate<T> = (item: T) => boolean;
7
+ export type PaginationResult<T> = {
8
+ total: number;
9
+ data: T[];
10
+ next?: number | null;
11
+ prev?: number | null;
12
+ first?: number | null;
13
+ last?: number | null;
14
+ totalPage?: number;
15
+ };
16
+ export declare class Repository<Entity extends ObjectLiteral> extends TypeOrmRepository<Entity> {
17
+ paginate(options?: PaginationOptions): Promise<PaginationResult<Entity>>;
18
+ }
19
+ type ICollection<T> = {
20
+ findAll(): T[] | Promise<T[]>;
21
+ };
22
+ declare class BasicCollection<T> implements ICollection<T> {
23
+ private items;
24
+ private constructor();
25
+ static from<T>(items: T[]): BasicCollection<T>;
26
+ findAll(predicate?: Predicate<T>): T[];
27
+ findOne(predicate: Predicate<T> | FindOneOptions<T>): T | Promise<T | null>;
28
+ private isFunction;
29
+ add(item: Partial<T>): T;
30
+ addAll(items: T[]): void;
31
+ update(predicate: (item: T) => boolean, updater: Partial<T>): void;
32
+ updateAll(predicate: (item: T) => boolean, updater: (item: T) => T): void;
33
+ delete(predicate: (item: T) => boolean): void;
34
+ deleteAll(predicate: (item: T) => boolean): void;
35
+ max<K extends keyof T>(key: K & string): number;
36
+ min<K extends keyof T>(key: K & string): number;
37
+ sum<K extends keyof T>(key: K & string): number;
38
+ avg<K extends keyof T>(key: K & string): number;
39
+ paginate(options?: PaginationOptions): {
40
+ total: number;
41
+ totalPage: number;
42
+ next: number | null;
43
+ data: T[];
44
+ };
45
+ private getDeepValue;
46
+ }
47
+ export declare class Collection {
48
+ private constructor();
49
+ static from<T>(items: T[]): BasicCollection<T>;
50
+ static fromRepositry<T extends ObjectLiteral>(entity: EntityTarget<T>): Repository<T>;
51
+ }
52
+ export {};
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Collection = exports.Repository = void 0;
7
+ const typedi_1 = __importDefault(require("typedi"));
8
+ const exceptions_1 = require("./exceptions");
9
+ const typeorm_1 = require("typeorm");
10
+ class Repository extends typeorm_1.Repository {
11
+ async paginate(options = { take: 10, skip: 0 }) {
12
+ const total = await this.count();
13
+ const data = await this.find({
14
+ take: options.take || 10,
15
+ skip: options.skip || 0,
16
+ });
17
+ return { total, data };
18
+ }
19
+ }
20
+ exports.Repository = Repository;
21
+ class BasicCollection {
22
+ constructor(items) {
23
+ this.items = items;
24
+ }
25
+ static from(items) {
26
+ return new BasicCollection(items);
27
+ }
28
+ findAll(predicate) {
29
+ const results = Array.from(this.items);
30
+ return results;
31
+ }
32
+ findOne(predicate) {
33
+ if (this.isFunction(predicate)) {
34
+ return this.items.find(predicate);
35
+ }
36
+ throw new Error("Invalid predicate type");
37
+ }
38
+ // Utility function to check if a value is a function
39
+ isFunction(value) {
40
+ return typeof value === "function";
41
+ }
42
+ add(item) {
43
+ this.items.push(item);
44
+ return this.items[this.items.length - 1];
45
+ }
46
+ addAll(items) {
47
+ this.items.push(...items);
48
+ }
49
+ update(predicate, updater) {
50
+ const item = this.items.find(predicate);
51
+ if (item) {
52
+ const index = this.items.indexOf(item);
53
+ this.items[index] = Object.assign(Object.assign({}, item), updater);
54
+ }
55
+ else {
56
+ throw new exceptions_1.NotFoundException("Item not found");
57
+ }
58
+ }
59
+ updateAll(predicate, updater) {
60
+ for (let i = 0; i < this.items.length; i++) {
61
+ if (predicate(this.items[i])) {
62
+ this.items[i] = updater(this.items[i]);
63
+ }
64
+ }
65
+ }
66
+ delete(predicate) {
67
+ const index = this.items.findIndex(predicate);
68
+ if (index !== -1) {
69
+ this.items.splice(index, 1);
70
+ }
71
+ }
72
+ deleteAll(predicate) {
73
+ this.items = this.items.filter((item) => !predicate(item));
74
+ }
75
+ max(key) {
76
+ return Math.max(...this.items.map((item) => item[key]));
77
+ }
78
+ min(key) {
79
+ return Math.max(...this.items.map((item) => item[key]));
80
+ }
81
+ sum(key) {
82
+ const nums = this.items.flatMap((x) => x[key]);
83
+ return nums.reduce((sum, num) => sum + num, 0);
84
+ }
85
+ avg(key) {
86
+ const nums = this.items.flatMap((x) => x[key]);
87
+ return nums.reduce((sum, num) => sum + num, 0) / nums.length;
88
+ }
89
+ paginate(options) {
90
+ const take = (options === null || options === void 0 ? void 0 : options.take) || 10;
91
+ const skip = (options === null || options === void 0 ? void 0 : options.skip) || 0;
92
+ const total = this.items.length;
93
+ const data = this.items.slice(skip, take);
94
+ return {
95
+ total,
96
+ totalPage: Math.ceil(total / take),
97
+ next: skip + take < total ? skip + take : null,
98
+ data,
99
+ };
100
+ }
101
+ getDeepValue(item, path) {
102
+ if (typeof path !== "string")
103
+ return item[path];
104
+ return path.split(".").reduce((acc, key) => acc === null || acc === void 0 ? void 0 : acc[key], item);
105
+ }
106
+ }
107
+ class AsynchronousCollection {
108
+ constructor(model) {
109
+ this.model = model;
110
+ }
111
+ static fromRepository(model) {
112
+ return new AsynchronousCollection(model);
113
+ }
114
+ getRepository() {
115
+ if (!this.repo) {
116
+ const dataSource = typedi_1.default.get("idatasource");
117
+ const repository = dataSource.getRepository(this.model).extend({
118
+ paginate: this.paginate,
119
+ });
120
+ this.repo = repository;
121
+ return repository;
122
+ }
123
+ return this.repo;
124
+ }
125
+ // Pagination with query builder
126
+ async paginate(options) {
127
+ const take = (options === null || options === void 0 ? void 0 : options.take) || 10;
128
+ const skip = (options === null || options === void 0 ? void 0 : options.skip) || 0;
129
+ const [data, total] = await this.getRepository().findAndCount({
130
+ take,
131
+ skip,
132
+ });
133
+ return {
134
+ total,
135
+ totalPage: Math.ceil(total / take),
136
+ next: skip + take < total ? skip + take : null,
137
+ data,
138
+ };
139
+ }
140
+ createQueryBuilder(alias, queryRunner) {
141
+ return this.getRepository().createQueryBuilder(alias, queryRunner);
142
+ }
143
+ hasId(entity) {
144
+ return this.getRepository().hasId(entity);
145
+ }
146
+ getId(entity) {
147
+ return this.getRepository().getId(entity);
148
+ }
149
+ create(entityLike) {
150
+ return this.getRepository().create(entityLike);
151
+ }
152
+ merge(mergeIntoEntity, ...entityLikes) {
153
+ return this.getRepository().merge(mergeIntoEntity, ...entityLikes);
154
+ }
155
+ async preload(entityLike) {
156
+ return this.getRepository().preload(entityLike);
157
+ }
158
+ async save(entities, options) {
159
+ return this.getRepository().save(entities, options);
160
+ }
161
+ async remove(entity) {
162
+ return this.getRepository().remove(entity);
163
+ }
164
+ async softRemove(entity) {
165
+ return this.getRepository().softRemove(entity);
166
+ }
167
+ async recover(entity) {
168
+ return this.getRepository().recover(entity);
169
+ }
170
+ async insert(entity) {
171
+ await this.getRepository().insert(entity);
172
+ }
173
+ async update(criteria, partialEntity) {
174
+ return this.getRepository().update(criteria, partialEntity);
175
+ }
176
+ async upsert(entityOrEntities, conflictPathsOrOptions) {
177
+ await this.getRepository().upsert(entityOrEntities, conflictPathsOrOptions);
178
+ }
179
+ async delete(criteria) {
180
+ return this.getRepository().delete(criteria);
181
+ }
182
+ async softDelete(criteria) {
183
+ return this.getRepository().softDelete(criteria);
184
+ }
185
+ async restore(criteria) {
186
+ return this.getRepository().restore(criteria);
187
+ }
188
+ async exist(options) {
189
+ return (await this.getRepository().count(options)) > 0;
190
+ }
191
+ async exists(options) {
192
+ return this.exist(options);
193
+ }
194
+ async existsBy(where) {
195
+ return (await this.getRepository().count({ where })) > 0;
196
+ }
197
+ async count(options) {
198
+ return this.getRepository().count(options);
199
+ }
200
+ async countBy(where) {
201
+ return this.getRepository().count({ where });
202
+ }
203
+ async sum(columnName, where) {
204
+ return this.getRepository()
205
+ .createQueryBuilder()
206
+ .select(`SUM(${columnName})`, "sum")
207
+ .where(where || {})
208
+ .getRawOne()
209
+ .then((res) => (res === null || res === void 0 ? void 0 : res.sum) || null);
210
+ }
211
+ async average(columnName, where) {
212
+ return this.getRepository()
213
+ .createQueryBuilder()
214
+ .select(`AVG(${columnName})`, "average")
215
+ .where(where || {})
216
+ .getRawOne()
217
+ .then((res) => (res === null || res === void 0 ? void 0 : res.average) || null);
218
+ }
219
+ async minimum(columnName, where) {
220
+ return this.getRepository()
221
+ .createQueryBuilder()
222
+ .select(`MIN(${columnName})`, "minimum")
223
+ .where(where || {})
224
+ .getRawOne()
225
+ .then((res) => (res === null || res === void 0 ? void 0 : res.minimum) || null);
226
+ }
227
+ async maximum(columnName, where) {
228
+ return this.getRepository().maximum(columnName, where);
229
+ }
230
+ async find(options) {
231
+ return await this.getRepository().find(options);
232
+ }
233
+ async findBy(where) {
234
+ return this.getRepository().findBy(where);
235
+ }
236
+ async findAndCount(options) {
237
+ return this.getRepository().findAndCount(options);
238
+ }
239
+ async findAndCountBy(where) {
240
+ return this.getRepository().findAndCount({ where });
241
+ }
242
+ async findByIds(ids) {
243
+ return this.getRepository().findBy(ids);
244
+ }
245
+ async findOne(options) {
246
+ return this.getRepository().findOne(options);
247
+ }
248
+ async findOneBy(where) {
249
+ return this.getRepository().findOneBy(where);
250
+ }
251
+ async findOneById(id) {
252
+ return this.getRepository().findOneBy({ id });
253
+ }
254
+ async findOneOrFail(options) {
255
+ return this.getRepository().findOneOrFail(options);
256
+ }
257
+ async findOneByOrFail(where) {
258
+ return this.getRepository().findOneByOrFail(where);
259
+ }
260
+ async query(query, parameters) {
261
+ return this.getRepository().query(query, parameters);
262
+ }
263
+ async clear() {
264
+ await this.getRepository().clear();
265
+ }
266
+ async increment(conditions, propertyPath, value) {
267
+ return this.getRepository().increment(conditions, propertyPath, value);
268
+ }
269
+ async decrement(conditions, propertyPath, value) {
270
+ return this.getRepository().decrement(conditions, propertyPath, value);
271
+ }
272
+ }
273
+ class Collection {
274
+ constructor() { }
275
+ static from(items) {
276
+ return BasicCollection.from(items);
277
+ }
278
+ static fromRepositry(entity) {
279
+ return AsynchronousCollection.fromRepository(entity);
280
+ }
281
+ }
282
+ exports.Collection = Collection;
package/dist/config.d.ts CHANGED
@@ -26,5 +26,5 @@ export declare function Config(target: {
26
26
  }): void;
27
27
  export declare function GetConfig<T extends ConfigClass>(ConfigClass: {
28
28
  new (...args: any[]): T;
29
- }): ReturnType<T['invoke']>;
29
+ }): ReturnType<T["invoke"]>;
30
30
  export {};
package/dist/config.js CHANGED
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Config = Config;
4
4
  exports.GetConfig = GetConfig;
5
- const CONFIG_METADATA_KEY = Symbol('config');
5
+ const CONFIG_METADATA_KEY = Symbol("config");
6
6
  function Config(target) {
7
- if (typeof target.prototype.invoke !== 'function') {
7
+ if (typeof target.prototype.invoke !== "function") {
8
8
  throw new Error(`Class "${target.name}" must implement an "invoke" method.`);
9
9
  }
10
10
  Reflect.defineMetadata(CONFIG_METADATA_KEY, target, target);
@@ -1,19 +1,18 @@
1
- import { ContainerInstance } from "typedi";
1
+ import TypediContainer from "typedi";
2
2
  export declare const ROUTE_META_KEY: unique symbol;
3
3
  export declare const CONTROLLER_META_KEY: unique symbol;
4
4
  export declare const PARAM_META_KEY: unique symbol;
5
5
  export declare const QUERY_META_KEY: unique symbol;
6
6
  export declare const REQUEST_BODY_META_KEY: unique symbol;
7
+ export declare const REQUEST_USER_META_KEY: unique symbol;
7
8
  export declare const REQUEST_HEADER_META_KEY: unique symbol;
8
9
  export declare const DATASOURCE_META_KEY: unique symbol;
9
- export interface IContainer extends ContainerInstance {
10
- registerHandler: IContainer;
11
- }
12
- declare const Container: IContainer;
10
+ declare const Container: typeof TypediContainer;
13
11
  export declare function registerController(controller: Function): void;
14
12
  export declare function registerService(service: Function): void;
15
13
  export declare function getRegisteredServices(): Function[];
16
14
  export declare function getRegisteredControllers(): Function[];
17
15
  export declare const API_CONTROLLER_METADATA_KEY: unique symbol;
18
16
  export declare function isApiController(target: Function): boolean;
17
+ export declare function registerDataSource(dataSource: any): void;
19
18
  export default Container;
package/dist/container.js CHANGED
@@ -3,24 +3,26 @@ 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.API_CONTROLLER_METADATA_KEY = exports.DATASOURCE_META_KEY = exports.REQUEST_HEADER_META_KEY = exports.REQUEST_BODY_META_KEY = exports.QUERY_META_KEY = exports.PARAM_META_KEY = exports.CONTROLLER_META_KEY = exports.ROUTE_META_KEY = void 0;
6
+ exports.API_CONTROLLER_METADATA_KEY = exports.DATASOURCE_META_KEY = exports.REQUEST_HEADER_META_KEY = exports.REQUEST_USER_META_KEY = exports.REQUEST_BODY_META_KEY = exports.QUERY_META_KEY = exports.PARAM_META_KEY = exports.CONTROLLER_META_KEY = exports.ROUTE_META_KEY = void 0;
7
7
  exports.registerController = registerController;
8
8
  exports.registerService = registerService;
9
9
  exports.getRegisteredServices = getRegisteredServices;
10
10
  exports.getRegisteredControllers = getRegisteredControllers;
11
11
  exports.isApiController = isApiController;
12
+ exports.registerDataSource = registerDataSource;
12
13
  const typedi_1 = __importDefault(require("typedi"));
13
14
  exports.ROUTE_META_KEY = Symbol("iroute:options");
14
15
  exports.CONTROLLER_META_KEY = Symbol("icontroller:options");
15
16
  exports.PARAM_META_KEY = Symbol("iparam:options");
16
17
  exports.QUERY_META_KEY = Symbol("iparam:options");
17
18
  exports.REQUEST_BODY_META_KEY = Symbol("iparam:options");
19
+ exports.REQUEST_USER_META_KEY = Symbol("iparam:options");
18
20
  exports.REQUEST_HEADER_META_KEY = Symbol("iheader:options");
19
21
  exports.DATASOURCE_META_KEY = Symbol("idatasource:options");
20
22
  const controllerRegistry = new Set();
21
23
  const serviceRegistry = new Set();
22
24
  const optionsRegistry = new Map();
23
- const Container = typedi_1.default.of("avContriner");
25
+ const Container = typedi_1.default;
24
26
  function registerController(controller) {
25
27
  controllerRegistry.add(controller);
26
28
  }
@@ -34,18 +36,12 @@ function getRegisteredServices() {
34
36
  function getRegisteredControllers() {
35
37
  return Array.from(controllerRegistry);
36
38
  }
37
- // export const APP_DC_TOKEN = new Token<DataSource>();
38
- // Container.set(APP_DC_TOKEN, DataSource);
39
- exports.API_CONTROLLER_METADATA_KEY = Symbol('apiController');
40
- // export type DBContext = Record<string, ReturnType<DataSource['getRepository']>>;
41
- // export function registerDataSource(dc: DataSource) {
42
- // Container.set({
43
- // id: APP_DC_TOKEN,
44
- // factory: () => dc,
45
- // });
46
- // }
39
+ exports.API_CONTROLLER_METADATA_KEY = Symbol("apiController");
47
40
  function isApiController(target) {
48
41
  return Reflect.getMetadata(exports.API_CONTROLLER_METADATA_KEY, target) === true;
49
42
  }
50
- Container.set('appName', 'Iqra');
43
+ Container.set("appName", "Iqra");
44
+ function registerDataSource(dataSource) {
45
+ Container.set("idatasource", dataSource);
46
+ }
51
47
  exports.default = Container;
@@ -1,5 +1,6 @@
1
1
  import { Service as _service } from "typedi";
2
- export declare const AppService: typeof _service;
2
+ export declare function AppService(target: any): void;
3
+ export declare function AppService(): any;
3
4
  export * from "./controller";
4
5
  export * from "./route-methods";
5
6
  export * from "./openapi";
@@ -14,9 +14,19 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Helper = exports.Utility = exports.AppService = void 0;
17
+ exports.Helper = exports.Utility = void 0;
18
+ exports.AppService = AppService;
18
19
  const typedi_1 = require("typedi");
19
- exports.AppService = typedi_1.Service;
20
+ function AppService(target) {
21
+ if (target) {
22
+ (0, typedi_1.Service)()(target);
23
+ }
24
+ else {
25
+ return function (tg) {
26
+ (0, typedi_1.Service)()(tg);
27
+ };
28
+ }
29
+ }
20
30
  __exportStar(require("./controller"), exports);
21
31
  __exportStar(require("./route-methods"), exports);
22
32
  __exportStar(require("./openapi"), exports);
@@ -0,0 +1,3 @@
1
+ export declare const e: Record<string, string>;
2
+ export type Env = typeof e;
3
+ export declare const env: Env;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.env = exports.e = void 0;
7
+ const dotenv_1 = __importDefault(require("dotenv"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ // Load environment variables
11
+ dotenv_1.default.config({ path: path_1.default.join(process.cwd(), ".env") });
12
+ // Read the .env file and infer keys dynamically
13
+ const envFilePath = path_1.default.join(process.cwd(), ".env");
14
+ const envContents = fs_1.default.readFileSync(envFilePath, "utf-8");
15
+ // Parse .env file manually
16
+ const parsedEnv = Object.fromEntries(envContents
17
+ .split("\n")
18
+ .filter((line) => line.trim() && !line.startsWith("#")) // Ignore empty lines and comments
19
+ .map((line) => {
20
+ const [key, ...valueParts] = line.split("="); // Split key and value
21
+ return [key.trim(), valueParts.join("=").trim()]; // Handle values with `=`
22
+ }));
23
+ const inferType = (value) => {
24
+ if (!isNaN(Number(value)))
25
+ return Number(value);
26
+ if (value.toLowerCase() === "true")
27
+ return true;
28
+ if (value.toLowerCase() === "false")
29
+ return false;
30
+ return value;
31
+ };
32
+ exports.e = parsedEnv;
33
+ exports.env = exports.e;
@@ -1,4 +1,4 @@
1
- export declare class BaseHttpException extends Error {
1
+ export declare abstract class BaseHttpException extends Error {
2
2
  code: number;
3
3
  name: string;
4
4
  constructor(message: any);
@@ -9,6 +9,9 @@ export declare class BadRequestException extends BaseHttpException {
9
9
  code: number;
10
10
  constructor(message: any);
11
11
  }
12
+ export declare class ValidationErrorException extends BadRequestException {
13
+ name: string;
14
+ }
12
15
  export declare class InternalErrorException extends BaseHttpException {
13
16
  name: string;
14
17
  code: number;
@@ -19,3 +22,23 @@ export declare class NotFoundException extends BaseHttpException {
19
22
  code: number;
20
23
  constructor(message: any);
21
24
  }
25
+ export declare class UnauthorizedException extends BaseHttpException {
26
+ name: string;
27
+ code: number;
28
+ constructor(message: any);
29
+ }
30
+ export declare class ForbiddenException extends BaseHttpException {
31
+ name: string;
32
+ code: number;
33
+ constructor(message: any);
34
+ }
35
+ export type HttpException = NotFoundException | BadRequestException | UnauthorizedException | InternalErrorException | ForbiddenException;
36
+ export type HttpExceptions = {
37
+ NotFound: (message: any) => NotFoundException;
38
+ ValidationError: (message: any) => ValidationErrorException;
39
+ BadRequest: (message: any) => BadRequestException;
40
+ Unauthorized: (message: any) => UnauthorizedException;
41
+ Forbidden: (message: any) => ForbiddenException;
42
+ InternalError: (message: any) => InternalErrorException;
43
+ };
44
+ export declare const httpExcepitoins: HttpExceptions;
@@ -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,3 +1,4 @@
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;
3
4
  export declare function formatUrl(path: string): string;
@@ -21,4 +22,10 @@ export declare function jsonToJs(value: string): any;
21
22
  export declare function jsonToInstance(value: string, instance: Constructor): any;
22
23
  export declare function transformObjectByInstanceToObject(instance: Constructor, value: object): Record<string, any>;
23
24
  export declare const isClassValidatorClass: (target: Constructor) => boolean;
24
- export declare function validateObjectByInstance(target: Constructor, value: object): Promise<any>;
25
+ export declare function validateObjectByInstance(target: Constructor, value?: object, options?: 'object' | 'array'): Promise<any>;
26
+ type ValidationError = {
27
+ count: number;
28
+ errors: any;
29
+ };
30
+ export declare function validateRequestBody(target: Constructor, value: object, options?: 'object' | 'array'): ValidationError;
31
+ export {};