@avleon/core 0.0.12 → 0.0.14

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/dist/icore.js CHANGED
@@ -94,7 +94,9 @@ class AvleonApplication {
94
94
  this.authorizeMiddleware = undefined;
95
95
  this.dataSource = undefined;
96
96
  this.metaCache = new Map();
97
- this.app = (0, fastify_1.default)();
97
+ this.app = (0, fastify_1.default)({
98
+ frameworkErrors: (error, req, res) => { },
99
+ });
98
100
  this.appConfig = new config_1.AppConfig();
99
101
  // this.app.setValidatorCompiler(() => () => true);
100
102
  }
@@ -163,8 +165,7 @@ class AvleonApplication {
163
165
  }
164
166
  useMultipart(options) {
165
167
  this.multipartOptions = options;
166
- this.app.register(multipart_1.default, options);
167
- return this;
168
+ this.app.register(multipart_1.default, Object.assign(Object.assign({}, this.multipartOptions), { attachFieldsToBody: true }));
168
169
  }
169
170
  handleMiddlewares(mclasses) {
170
171
  for (const mclass of mclasses) {
@@ -193,7 +194,6 @@ class AvleonApplication {
193
194
  return;
194
195
  const prototype = Object.getPrototypeOf(ctrl);
195
196
  const methods = Object.getOwnPropertyNames(prototype).filter((name) => name !== "constructor");
196
- let classMiddlewares = [];
197
197
  const tag = ctrl.constructor.name.replace("Controller", "");
198
198
  const swaggerControllerMeta = Reflect.getMetadata("controller:openapi", ctrl.constructor) || {};
199
199
  const authClsMeata = Reflect.getMetadata(container_1.AUTHORIZATION_META_KEY, ctrl.constructor) || { authorize: false, options: undefined };
@@ -223,11 +223,21 @@ class AvleonApplication {
223
223
  const swaggerMeta = Reflect.getMetadata("route:openapi", prototype, method) || {};
224
224
  const authClsMethodMeata = Reflect.getMetadata(container_1.AUTHORIZATION_META_KEY, ctrl.constructor, method) || { authorize: false, options: undefined };
225
225
  const allMeta = this._processMeta(prototype, method);
226
+ let bodySchema = null;
227
+ allMeta.body.forEach((r) => {
228
+ if (r.schema) {
229
+ bodySchema = Object.assign({}, r.schema);
230
+ }
231
+ });
226
232
  const routePath = methodmetaOptions.path == "" ? "/" : methodmetaOptions.path;
233
+ let schema = Object.assign(Object.assign(Object.assign({}, swaggerControllerMeta), swaggerMeta), { tags: [tag] });
234
+ if (!swaggerMeta.body && bodySchema) {
235
+ schema = Object.assign(Object.assign({}, schema), { body: bodySchema });
236
+ }
227
237
  this.app.route({
228
238
  url: routePath,
229
239
  method: methodmetaOptions.method.toUpperCase(),
230
- schema: Object.assign(Object.assign(Object.assign({}, swaggerControllerMeta), swaggerMeta), { tags: [tag] }),
240
+ schema: Object.assign({}, schema),
231
241
  handler: async (req, res) => {
232
242
  let reqClone = req;
233
243
  if (authClsMethodMeata.authorize && this.authorizeMiddleware) {
@@ -279,7 +289,8 @@ class AvleonApplication {
279
289
  * @returns
280
290
  */
281
291
  async _mapArgs(req, meta) {
282
- var _a, e_2, _b, _c;
292
+ var _a, e_2, _b, _c, _d, e_3, _e, _f;
293
+ var _g;
283
294
  if (!req.hasOwnProperty("_argsCache")) {
284
295
  Object.defineProperty(req, "_argsCache", {
285
296
  value: new Map(),
@@ -293,15 +304,15 @@ class AvleonApplication {
293
304
  }
294
305
  const args = meta.params.map((p) => req.params[p.key] || null);
295
306
  meta.query.forEach((q) => (args[q.index] = q.key === "all" ? req.query : req.query[q.key]));
296
- meta.body.forEach((body) => (args[body.index] = req.body));
307
+ meta.body.forEach((body) => (args[body.index] = Object.assign(Object.assign({}, req.body), req.formData)));
297
308
  meta.currentUser.forEach((user) => (args[user.index] = req.user));
298
309
  meta.headers.forEach((header) => (args[header.index] =
299
310
  header.key === "all" ? req.headers : req.headers[header.key]));
300
311
  if (meta.file) {
301
312
  try {
302
- for (var _d = true, _e = __asyncValues(meta.file), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) {
303
- _c = _f.value;
304
- _d = false;
313
+ for (var _h = true, _j = __asyncValues(meta.file), _k; _k = await _j.next(), _a = _k.done, !_a; _h = true) {
314
+ _c = _k.value;
315
+ _h = false;
305
316
  let f = _c;
306
317
  args[f.index] = await req.file();
307
318
  }
@@ -309,11 +320,49 @@ class AvleonApplication {
309
320
  catch (e_2_1) { e_2 = { error: e_2_1 }; }
310
321
  finally {
311
322
  try {
312
- if (!_d && !_a && (_b = _e.return)) await _b.call(_e);
323
+ if (!_h && !_a && (_b = _j.return)) await _b.call(_j);
313
324
  }
314
325
  finally { if (e_2) throw e_2.error; }
315
326
  }
316
327
  }
328
+ if (meta.files &&
329
+ ((_g = req.headers["content-type"]) === null || _g === void 0 ? void 0 : _g.startsWith("multipart/form-data")) === true) {
330
+ const files = await req.saveRequestFiles();
331
+ if (!files || files.length === 0) {
332
+ throw new exceptions_1.BadRequestException({ error: "No files uploaded" });
333
+ }
334
+ const fileInfo = files.map((file) => ({
335
+ type: file.type,
336
+ filepath: file.filepath,
337
+ fieldname: file.fieldname,
338
+ filename: file.filename,
339
+ encoding: file.encoding,
340
+ mimetype: file.mimetype,
341
+ fields: file.fields,
342
+ }));
343
+ try {
344
+ for (var _l = true, _m = __asyncValues(meta.files), _o; _o = await _m.next(), _d = _o.done, !_d; _l = true) {
345
+ _f = _o.value;
346
+ _l = false;
347
+ let f = _f;
348
+ const findex = fileInfo.findIndex((x) => x.fieldname == f.fieldName);
349
+ if (f.fieldName != "all" && findex == -1) {
350
+ throw new exceptions_1.BadRequestException(`${f.fieldName} doesn't exists in request files tree.`);
351
+ }
352
+ args[f.index] =
353
+ f.fieldName == "all"
354
+ ? fileInfo
355
+ : fileInfo.filter((x) => x.fieldname == f.fieldName);
356
+ }
357
+ }
358
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
359
+ finally {
360
+ try {
361
+ if (!_l && !_d && (_e = _m.return)) await _e.call(_m);
362
+ }
363
+ finally { if (e_3) throw e_3.error; }
364
+ }
365
+ }
317
366
  cache.set(cacheKey, args);
318
367
  return args;
319
368
  }
@@ -366,6 +415,9 @@ class AvleonApplication {
366
415
  if ((0, container_1.isApiController)(controller)) {
367
416
  this.buildController(controller);
368
417
  }
418
+ else {
419
+ throw new system_exception_1.SystemUseError("Not a api controller.");
420
+ }
369
421
  }
370
422
  }
371
423
  }
@@ -519,16 +571,23 @@ class AvleonApplication {
519
571
  await this.app.listen({ port });
520
572
  console.log(`Application running on http://127.0.0.1:${port}`);
521
573
  }
522
- async getTestApp(buildOptions) {
574
+ getTestApp(buildOptions) {
523
575
  try {
524
576
  if (buildOptions && buildOptions.addDataSource) {
525
- const typeorm = await Promise.resolve().then(() => __importStar(require("typeorm")));
577
+ const typeorm = Promise.resolve().then(() => __importStar(require("typeorm")));
526
578
  if (!typeorm) {
527
579
  throw new system_exception_1.SystemUseError("TypeOrm not installed");
528
580
  }
529
- const datasource = new typeorm.DataSource(buildOptions.addDataSource);
530
- typedi_1.default.set("idatasource", datasource);
531
- await datasource.initialize();
581
+ typeorm.then(async (t) => {
582
+ try {
583
+ const datasource = new t.DataSource(buildOptions.addDataSource);
584
+ typedi_1.default.set("idatasource", datasource);
585
+ await datasource.initialize();
586
+ }
587
+ catch (error) {
588
+ console.error("Database can't initialized.", error);
589
+ }
590
+ });
532
591
  }
533
592
  this._mapControllers();
534
593
  this.rMap.forEach((value, key) => {
@@ -555,7 +614,15 @@ class AvleonApplication {
555
614
  }
556
615
  return res.status(handledErr.code).send(handledErr);
557
616
  });
558
- return this.app;
617
+ // return this.app as any;
618
+ return {
619
+ get: (url, options) => this.app.inject(Object.assign({ method: "GET", url }, options)),
620
+ post: (url, options) => this.app.inject(Object.assign({ method: "POST", url }, options)),
621
+ put: (url, options) => this.app.inject(Object.assign({ method: "PUT", url }, options)),
622
+ patch: (url, options) => this.app.inject(Object.assign({ method: "PATCH", url }, options)),
623
+ delete: (url, options) => this.app.inject(Object.assign({ method: "DELETE", url }, options)),
624
+ options: (url, options) => this.app.inject(Object.assign({ method: "OPTIONS", url }, options)),
625
+ };
559
626
  }
560
627
  catch (error) {
561
628
  throw new system_exception_1.SystemUseError("Can't get test appliction");
@@ -577,12 +644,12 @@ class TestBuilder {
577
644
  getService(service) {
578
645
  return typedi_1.default.get(service);
579
646
  }
580
- async getTestApplication(options) {
647
+ getTestApplication(options) {
581
648
  const app = AvleonApplication.getInternalApp({
582
- dataSourceOptions: this.dataSourceOptions
649
+ dataSourceOptions: this.dataSourceOptions,
583
650
  });
584
651
  app.mapControllers([...options.controllers]);
585
- const fa = await app.getTestApp();
652
+ const fa = app.getTestApp();
586
653
  return fa;
587
654
  }
588
655
  build(app) {
@@ -600,22 +667,12 @@ class Builder {
600
667
  this.testBuilder = false;
601
668
  this.appConfig = new config_1.AppConfig();
602
669
  }
603
- getTestApplication() {
604
- throw new Error("Method not implemented.");
605
- }
606
670
  static createAppBuilder() {
607
671
  if (!Builder.instance) {
608
672
  Builder.instance = new Builder();
609
673
  }
610
674
  return Builder.instance;
611
675
  }
612
- static creatTestAppBuilder() {
613
- if (!Builder.instance) {
614
- Builder.instance = new Builder();
615
- Builder.instance.testBuilder = true;
616
- }
617
- return Builder.instance;
618
- }
619
676
  async registerPlugin(plugin, options) {
620
677
  container_1.default.set(plugin, plugin.prototype);
621
678
  }
@@ -629,28 +686,6 @@ class Builder {
629
686
  this.dataSourceOptions = openApiConfig;
630
687
  }
631
688
  }
632
- createTestApplication(buildOptions) {
633
- return {
634
- addDataSource: (dataSourceOptions) => (this.dataSourceOptions = dataSourceOptions),
635
- getApp: async (options) => {
636
- const app = AvleonApplication.getInternalApp({
637
- database: this.database,
638
- dataSourceOptions: buildOptions.datSource,
639
- });
640
- app.mapControllers([...options.controllers]);
641
- const _tapp = await app.getTestApp();
642
- return {
643
- async get(url, options) {
644
- const res = await _tapp.inject(Object.assign({ url, method: "GET" }, options));
645
- return res;
646
- },
647
- };
648
- },
649
- getController(controller) {
650
- return typedi_1.default.get(controller);
651
- },
652
- };
653
- }
654
689
  build() {
655
690
  if (this.alreadyBuilt) {
656
691
  throw new Error("Already built");
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * @email xtrinsic96@gmail.com
5
5
  * @url https://github.com/xtareq
6
6
  */
7
+ import * as sw from "./swagger-schema";
7
8
  export * from "./icore";
8
9
  export { inject, validateRequestBody } from "./helpers";
9
10
  export * from "./decorators";
@@ -21,4 +22,6 @@ export * from "./queue";
21
22
  export * from "./security";
22
23
  export * from "./multipart";
23
24
  export * from "./file-storage";
25
+ export * from "./logger";
26
+ export declare const GetSchema: typeof sw.generateSwaggerSchema;
24
27
  export { default as Container } from "./container";
package/dist/index.js CHANGED
@@ -1,10 +1,4 @@
1
1
  "use strict";
2
- /**
3
- * @copyright 2024
4
- * @author Tareq Hossain
5
- * @email xtrinsic96@gmail.com
6
- * @url https://github.com/xtareq
7
- */
8
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
3
  if (k2 === undefined) k2 = k;
10
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -16,6 +10,28 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
16
10
  if (k2 === undefined) k2 = k;
17
11
  o[k2] = m[k];
18
12
  }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
19
35
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
36
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
37
  };
@@ -23,7 +39,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
23
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
24
40
  };
25
41
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.Container = exports.validateRequestBody = exports.inject = void 0;
42
+ exports.Container = exports.GetSchema = exports.validateRequestBody = exports.inject = void 0;
43
+ /**
44
+ * @copyright 2024
45
+ * @author Tareq Hossain
46
+ * @email xtrinsic96@gmail.com
47
+ * @url https://github.com/xtareq
48
+ */
49
+ const sw = __importStar(require("./swagger-schema"));
27
50
  __exportStar(require("./icore"), exports);
28
51
  var helpers_1 = require("./helpers");
29
52
  Object.defineProperty(exports, "inject", { enumerable: true, get: function () { return helpers_1.inject; } });
@@ -43,5 +66,7 @@ __exportStar(require("./queue"), exports);
43
66
  __exportStar(require("./security"), exports);
44
67
  __exportStar(require("./multipart"), exports);
45
68
  __exportStar(require("./file-storage"), exports);
69
+ __exportStar(require("./logger"), exports);
70
+ exports.GetSchema = sw.generateSwaggerSchema;
46
71
  var container_1 = require("./container");
47
72
  Object.defineProperty(exports, "Container", { enumerable: true, get: function () { return __importDefault(container_1).default; } });
@@ -0,0 +1,12 @@
1
+ import pino from "pino";
2
+ export declare class LoggerService {
3
+ private logger;
4
+ constructor();
5
+ getLogger(): pino.Logger;
6
+ info(message: string, obj?: any): void;
7
+ error(message: string, obj?: any): void;
8
+ warn(message: string, obj?: any): void;
9
+ debug(message: string, obj?: any): void;
10
+ fatal(message: string, obj?: any): void;
11
+ trace(message: string, obj?: any): void;
12
+ }
package/dist/logger.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.LoggerService = void 0;
16
+ const pino_1 = __importDefault(require("pino"));
17
+ const decorators_1 = require("./decorators");
18
+ let LoggerService = class LoggerService {
19
+ constructor() {
20
+ this.logger = (0, pino_1.default)({
21
+ level: process.env.LOG_LEVEL || "info",
22
+ transport: {
23
+ target: "pino-pretty",
24
+ options: {
25
+ translateTime: "SYS:standard",
26
+ ignore: "pid,hostname",
27
+ },
28
+ },
29
+ });
30
+ }
31
+ getLogger() {
32
+ return this.logger;
33
+ }
34
+ info(message, obj) {
35
+ if (obj) {
36
+ this.logger.info(obj, message);
37
+ }
38
+ else {
39
+ this.logger.info(message);
40
+ }
41
+ }
42
+ error(message, obj) {
43
+ if (obj) {
44
+ this.logger.error(obj, message);
45
+ }
46
+ else {
47
+ this.logger.error(message);
48
+ }
49
+ }
50
+ warn(message, obj) {
51
+ if (obj) {
52
+ this.logger.warn(obj, message);
53
+ }
54
+ else {
55
+ this.logger.warn(message);
56
+ }
57
+ }
58
+ debug(message, obj) {
59
+ if (obj) {
60
+ this.logger.debug(obj, message);
61
+ }
62
+ else {
63
+ this.logger.debug(message);
64
+ }
65
+ }
66
+ fatal(message, obj) {
67
+ if (obj) {
68
+ this.logger.fatal(obj, message);
69
+ }
70
+ else {
71
+ this.logger.fatal(message);
72
+ }
73
+ }
74
+ trace(message, obj) {
75
+ if (obj) {
76
+ this.logger.trace(obj, message);
77
+ }
78
+ else {
79
+ this.logger.trace(message);
80
+ }
81
+ }
82
+ };
83
+ exports.LoggerService = LoggerService;
84
+ exports.LoggerService = LoggerService = __decorate([
85
+ decorators_1.AppService,
86
+ __metadata("design:paramtypes", [])
87
+ ], LoggerService);
@@ -4,14 +4,14 @@
4
4
  * @email xtrinsic96@gmail.com
5
5
  * @url https://github.com/xtareq
6
6
  */
7
- import { MultipartFile as FsM } from "@fastify/multipart";
7
+ import { MultipartFile as FsM, SavedMultipartFile } from "@fastify/multipart";
8
8
  import { IRequest } from "./icore";
9
9
  export declare function UploadFile(fieldName: string): (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
10
- export declare function UploadFiles(fieldName: string): (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
10
+ export declare function UploadFiles(fieldName?: string): (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
11
11
  type Foptions = {
12
12
  saveAs?: string;
13
13
  dest?: true;
14
14
  };
15
- export type MultipartFile = FsM;
15
+ export type MultipartFile = FsM | SavedMultipartFile;
16
16
  export declare function UploadFileFromRequest(req: IRequest, options?: Foptions): Promise<FsM | undefined>;
17
17
  export {};
package/dist/multipart.js CHANGED
@@ -33,7 +33,10 @@ function UploadFiles(fieldName) {
33
33
  Reflect.defineMetadata(container_1.REQUEST_BODY_FILES_KEY, [], target, propertyKey);
34
34
  }
35
35
  const existingMetadata = Reflect.getMetadata(container_1.REQUEST_BODY_FILES_KEY, target, propertyKey);
36
- existingMetadata.push({ fieldName, index: parameterIndex });
36
+ existingMetadata.push({
37
+ fieldName: fieldName ? fieldName : "all",
38
+ index: parameterIndex,
39
+ });
37
40
  Reflect.defineMetadata(container_1.REQUEST_BODY_FILES_KEY, existingMetadata, target, propertyKey);
38
41
  };
39
42
  }
@@ -43,7 +46,9 @@ function UploadFileFromRequest(req, options) {
43
46
  let fname = f.filename;
44
47
  if (options) {
45
48
  if (options.dest) {
46
- fname = options.saveAs ? options.dest + '/' + options.saveAs : options.dest + '/' + f.filename;
49
+ fname = options.saveAs
50
+ ? options.dest + "/" + options.saveAs
51
+ : options.dest + "/" + f.filename;
47
52
  }
48
53
  else {
49
54
  fname = path_1.default.join(process.cwd(), `public/${options.saveAs ? options.saveAs : f.filename}`);
package/dist/params.js CHANGED
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.AuthUser = exports.Header = exports.Body = exports.Query = exports.Param = void 0;
10
10
  const container_1 = require("./container");
11
11
  const helpers_1 = require("./helpers");
12
+ const swagger_schema_1 = require("./swagger-schema");
12
13
  function createParamDecorator(type) {
13
14
  return function (key, options = {}) {
14
15
  return function (target, propertyKey, parameterIndex) {
@@ -27,6 +28,9 @@ function createParamDecorator(type) {
27
28
  validate: options.validate || true,
28
29
  dataType: (0, helpers_1.getDataType)(paramDataType),
29
30
  validatorClass: (0, helpers_1.isClassValidatorClass)(paramDataType),
31
+ schema: (0, helpers_1.isClassValidatorClass)(paramDataType)
32
+ ? (0, swagger_schema_1.generateSwaggerSchema)(paramDataType)
33
+ : null,
30
34
  type,
31
35
  });
32
36
  switch (type) {
@@ -4,13 +4,23 @@
4
4
  * @email xtrinsic96@gmail.com
5
5
  * @url https://github.com/xtareq
6
6
  */
7
- import "reflect-metadata";
8
7
  import { ClassConstructor } from "class-transformer";
9
8
  export interface IHttpResponse<T extends any> {
10
9
  message: string;
11
10
  data: T | null;
12
11
  }
13
12
  export declare class HttpResponse {
14
- static Ok<T>(obj: any, s?: ClassConstructor<T>): any;
15
- static NoContent(): void;
13
+ static Ok<T>(obj: any, s?: ClassConstructor<T>): IHttpResponse<T>;
14
+ static Created<T>(obj: any, s?: ClassConstructor<T>): IHttpResponse<T>;
15
+ static NoContent(): IHttpResponse<null>;
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>;
16
26
  }
package/dist/response.js CHANGED
@@ -1,13 +1,12 @@
1
1
  "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpExceptions = exports.HttpResponse = void 0;
2
4
  /**
3
5
  * @copyright 2024
4
6
  * @author Tareq Hossain
5
7
  * @email xtrinsic96@gmail.com
6
8
  * @url https://github.com/xtareq
7
9
  */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.HttpResponse = void 0;
10
- require("reflect-metadata");
11
10
  const class_transformer_1 = require("class-transformer");
12
11
  function isClassTransformerClass(target) {
13
12
  const prototype = target.prototype;
@@ -22,16 +21,59 @@ class HttpResponse {
22
21
  static Ok(obj, s) {
23
22
  if (s) {
24
23
  const isPaginated = obj === null || obj === void 0 ? void 0 : obj.hasOwnProperty("total");
25
- // Ensure transformation applies only allowed properties
26
- const transformedData = (0, class_transformer_1.plainToInstance)(s, isPaginated ? obj.data : obj, {
24
+ const dataToTransform = isPaginated ? obj.data : obj;
25
+ const transformedData = (0, class_transformer_1.plainToInstance)(s, dataToTransform, {
27
26
  enableImplicitConversion: true,
28
- excludeExtraneousValues: true, // Ensures only @Expose() properties are included
27
+ excludeExtraneousValues: true,
29
28
  });
30
- return Object.assign({ message: "success" }, (isPaginated
31
- ? Object.assign(Object.assign({}, obj), { data: (0, class_transformer_1.instanceToPlain)(transformedData) }) : { data: (0, class_transformer_1.instanceToPlain)(transformedData) }));
29
+ const transformedResult = isPaginated
30
+ ? Object.assign(Object.assign({}, obj), { data: (0, class_transformer_1.instanceToPlain)(transformedData) }) : { data: (0, class_transformer_1.instanceToPlain)(transformedData) };
31
+ return Object.assign({ message: "success" }, transformedResult);
32
32
  }
33
33
  return { message: "success", data: obj };
34
34
  }
35
- static NoContent() { }
35
+ static Created(obj, s) {
36
+ if (s) {
37
+ const transformedData = (0, class_transformer_1.plainToInstance)(s, obj, {
38
+ enableImplicitConversion: true,
39
+ excludeExtraneousValues: true,
40
+ });
41
+ return {
42
+ message: "created",
43
+ data: (0, class_transformer_1.instanceToPlain)(transformedData),
44
+ };
45
+ }
46
+ return { message: "created", data: obj };
47
+ }
48
+ static NoContent() {
49
+ return { message: "no content", data: null };
50
+ }
36
51
  }
37
52
  exports.HttpResponse = HttpResponse;
53
+ class HttpExceptions {
54
+ static BadRequest(message, data = null) {
55
+ return { message: message, data: data };
56
+ }
57
+ static Unauthorized(message, data = null) {
58
+ return { message: message, data: data };
59
+ }
60
+ static Forbidden(message, data = null) {
61
+ return { message: message, data: data };
62
+ }
63
+ static NotFound(message, data = null) {
64
+ return { message: message, data: data };
65
+ }
66
+ static InternalServerError(message = "Internal server error", data = null) {
67
+ return { message: message, data: data };
68
+ }
69
+ static Conflict(message, data = null) {
70
+ return { message: message, data: data };
71
+ }
72
+ static UnprocessableEntity(message, data = null) {
73
+ return { message: message, data: data };
74
+ }
75
+ static TooManyRequests(message, data = null) {
76
+ return { message: message, data: data };
77
+ }
78
+ }
79
+ exports.HttpExceptions = HttpExceptions;
@@ -1,7 +1 @@
1
- /**
2
- * @copyright 2024
3
- * @author Tareq Hossain
4
- * @email xtrinsic96@gmail.com
5
- * @url https://github.com/xtareq
6
- */
7
1
  export declare function generateSwaggerSchema(classType: any): any;