@avleon/core 0.0.7 → 0.0.10

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 (46) hide show
  1. package/dist/authentication.d.ts +6 -0
  2. package/dist/authentication.js +7 -2
  3. package/dist/collection.js +7 -0
  4. package/dist/config.d.ts +14 -27
  5. package/dist/config.js +21 -9
  6. package/dist/container.d.ts +8 -0
  7. package/dist/container.js +9 -1
  8. package/dist/controller.js +6 -0
  9. package/dist/decorators.d.ts +6 -0
  10. package/dist/decorators.js +6 -0
  11. package/dist/environment-variables.d.ts +12 -3
  12. package/dist/environment-variables.js +46 -23
  13. package/dist/exceptions/http-exceptions.d.ts +6 -0
  14. package/dist/exceptions/http-exceptions.js +6 -0
  15. package/dist/exceptions/system-exception.d.ts +9 -0
  16. package/dist/exceptions/system-exception.js +7 -1
  17. package/dist/file-storage.d.ts +17 -0
  18. package/dist/file-storage.js +153 -0
  19. package/dist/helpers.js +7 -1
  20. package/dist/icore.d.ts +108 -8
  21. package/dist/icore.js +208 -46
  22. package/dist/index.d.ts +9 -0
  23. package/dist/index.js +9 -1
  24. package/dist/map-types.d.ts +6 -1
  25. package/dist/map-types.js +6 -1
  26. package/dist/middleware.js +6 -0
  27. package/dist/multipart.d.ts +17 -0
  28. package/dist/multipart.js +62 -0
  29. package/dist/openapi.d.ts +6 -0
  30. package/dist/params.js +6 -0
  31. package/dist/queue.d.ts +6 -0
  32. package/dist/queue.js +6 -0
  33. package/dist/response.d.ts +6 -0
  34. package/dist/response.js +8 -1
  35. package/dist/security.d.ts +4 -0
  36. package/dist/security.js +15 -0
  37. package/dist/swagger-schema.d.ts +6 -0
  38. package/dist/swagger-schema.js +6 -0
  39. package/dist/types/app-builder.interface.d.ts +6 -0
  40. package/dist/types/app-builder.interface.js +6 -0
  41. package/dist/types/application.interface.d.ts +6 -0
  42. package/dist/validation.d.ts +6 -0
  43. package/dist/validation.js +6 -0
  44. package/dist/validator-extend.d.ts +6 -0
  45. package/dist/validator-extend.js +6 -0
  46. package/package.json +15 -8
@@ -1,3 +1,9 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
1
7
  export type CurrentUser = {};
2
8
  export declare abstract class BaseAuthetication {
3
9
  abstract authenticate(): Promise<Boolean>;
@@ -1,4 +1,10 @@
1
1
  "use strict";
2
+ /**
3
+ * @copyright 2024
4
+ * @author Tareq Hossain
5
+ * @email xtrinsic96@gmail.com
6
+ * @url https://github.com/xtareq
7
+ */
2
8
  Object.defineProperty(exports, "__esModule", { value: true });
3
9
  exports.BaseAuthetication = void 0;
4
10
  exports.Authorized = Authorized;
@@ -6,6 +12,5 @@ exports.CurrentUser = CurrentUser;
6
12
  class BaseAuthetication {
7
13
  }
8
14
  exports.BaseAuthetication = BaseAuthetication;
9
- function Authorized() {
10
- }
15
+ function Authorized() { }
11
16
  function CurrentUser() { }
@@ -4,6 +4,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Collection = exports.Repository = void 0;
7
+ /**
8
+ * @copyright 2024
9
+ * @author Tareq Hossain
10
+ * @email xtrinsic96@gmail.com
11
+ * @url https://github.com/xtareq
12
+ */
7
13
  const typedi_1 = __importDefault(require("typedi"));
8
14
  const exceptions_1 = require("./exceptions");
9
15
  const typeorm_1 = require("typeorm");
@@ -134,6 +140,7 @@ class AsynchronousCollection {
134
140
  total,
135
141
  totalPage: Math.ceil(total / take),
136
142
  next: skip + take < total ? skip + take : null,
143
+ prev: skip + take < total ? skip + take : null,
137
144
  data,
138
145
  };
139
146
  }
package/dist/config.d.ts CHANGED
@@ -1,29 +1,16 @@
1
- export interface IDBConfig {
2
- type: string;
3
- host: string;
4
- port: number | string;
5
- username: string;
6
- password: string;
7
- database: string;
8
- synchronize: boolean;
9
- logging: boolean;
10
- entities: any[];
11
- migrations?: string[];
12
- subscribers?: string[];
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ import { Constructable } from "typedi";
8
+ import { Environment } from "./environment-variables";
9
+ export interface IConfig<T = any> {
10
+ config(env: Environment): T;
13
11
  }
14
- export interface Environment extends NodeJS.ProcessEnv {
15
- [key: string]: string | undefined;
12
+ export declare function Config<T extends IConfig>(target: Constructable<T>): void;
13
+ export declare class AppConfig {
14
+ get<T extends IConfig<R>, R>(configClass: Constructable<T>): R;
16
15
  }
17
- export interface IAppConfig {
18
- apiKey: string;
19
- timezone: string;
20
- }
21
- export interface IConfig {
22
- config(env: Environment): object;
23
- }
24
- export declare function Config<T extends IConfig>(target: {
25
- new (): T;
26
- }): void;
27
- export declare function GetConfig<T extends IConfig>(ConfigClass: {
28
- new (): T;
29
- }): ReturnType<T["config"]>;
16
+ export declare function GetConfig<T extends IConfig<R>, R = ReturnType<InstanceType<Constructable<T>>["config"]>>(ConfigClass: Constructable<T>): R;
package/dist/config.js CHANGED
@@ -1,21 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppConfig = void 0;
3
4
  exports.Config = Config;
4
5
  exports.GetConfig = GetConfig;
5
- const CONFIG_METADATA_KEY = Symbol("config");
6
- const configInstances = new Map();
6
+ /**
7
+ * @copyright 2024
8
+ * @author Tareq Hossain
9
+ * @email xtrinsic96@gmail.com
10
+ * @url https://github.com/xtareq
11
+ */
12
+ const typedi_1 = require("typedi");
13
+ const environment_variables_1 = require("./environment-variables");
7
14
  function Config(target) {
8
- if (typeof target.prototype.config !== "function") {
9
- throw new Error(`Class "${target.name}" must implement a "config" method.`);
15
+ typedi_1.Container.set({ id: target, type: target });
16
+ }
17
+ class AppConfig {
18
+ get(configClass) {
19
+ const instance = typedi_1.Container.get(configClass);
20
+ if (!instance) {
21
+ throw new Error(`Configuration for ${configClass.name} not found.`);
22
+ }
23
+ return instance.config(new environment_variables_1.Environment());
10
24
  }
11
- Reflect.defineMetadata(CONFIG_METADATA_KEY, target, target);
12
- // Auto-instantiate and store the config instance
13
- configInstances.set(target.name, new target());
14
25
  }
26
+ exports.AppConfig = AppConfig;
15
27
  function GetConfig(ConfigClass) {
16
- const instance = configInstances.get(ConfigClass.name);
28
+ const instance = typedi_1.Container.get(ConfigClass);
17
29
  if (!instance) {
18
30
  throw new Error(`Class "${ConfigClass.name}" is not registered as a config.`);
19
31
  }
20
- return instance.config(process.env);
32
+ return instance.config(new environment_variables_1.Environment());
21
33
  }
@@ -1,9 +1,17 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
1
7
  import TypediContainer from "typedi";
2
8
  export declare const ROUTE_META_KEY: unique symbol;
3
9
  export declare const CONTROLLER_META_KEY: unique symbol;
4
10
  export declare const PARAM_META_KEY: unique symbol;
5
11
  export declare const QUERY_META_KEY: unique symbol;
6
12
  export declare const REQUEST_BODY_META_KEY: unique symbol;
13
+ export declare const REQUEST_BODY_FILE_KEY: unique symbol;
14
+ export declare const REQUEST_BODY_FILES_KEY: unique symbol;
7
15
  export declare const REQUEST_USER_META_KEY: unique symbol;
8
16
  export declare const REQUEST_HEADER_META_KEY: unique symbol;
9
17
  export declare const DATASOURCE_META_KEY: unique symbol;
package/dist/container.js CHANGED
@@ -3,19 +3,27 @@ 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.AUTHORIZATION_META_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;
6
+ exports.API_CONTROLLER_METADATA_KEY = exports.AUTHORIZATION_META_KEY = exports.DATASOURCE_META_KEY = exports.REQUEST_HEADER_META_KEY = exports.REQUEST_USER_META_KEY = exports.REQUEST_BODY_FILES_KEY = exports.REQUEST_BODY_FILE_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
12
  exports.registerDataSource = registerDataSource;
13
+ /**
14
+ * @copyright 2024
15
+ * @author Tareq Hossain
16
+ * @email xtrinsic96@gmail.com
17
+ * @url https://github.com/xtareq
18
+ */
13
19
  const typedi_1 = __importDefault(require("typedi"));
14
20
  exports.ROUTE_META_KEY = Symbol("iroute:options");
15
21
  exports.CONTROLLER_META_KEY = Symbol("icontroller:options");
16
22
  exports.PARAM_META_KEY = Symbol("iparam:options");
17
23
  exports.QUERY_META_KEY = Symbol("iparam:options");
18
24
  exports.REQUEST_BODY_META_KEY = Symbol("iparam:options");
25
+ exports.REQUEST_BODY_FILE_KEY = Symbol("iparam:options");
26
+ exports.REQUEST_BODY_FILES_KEY = Symbol("iparam:options");
19
27
  exports.REQUEST_USER_META_KEY = Symbol("iparam:options");
20
28
  exports.REQUEST_HEADER_META_KEY = Symbol("iheader:options");
21
29
  exports.DATASOURCE_META_KEY = Symbol("idatasource:options");
@@ -1,4 +1,10 @@
1
1
  "use strict";
2
+ /**
3
+ * @copyright 2024
4
+ * @author Tareq Hossain
5
+ * @email xtrinsic96@gmail.com
6
+ * @url https://github.com/xtareq
7
+ */
2
8
  Object.defineProperty(exports, "__esModule", { value: true });
3
9
  exports.createControllerDecorator = createControllerDecorator;
4
10
  exports.ApiController = ApiController;
@@ -1,3 +1,9 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
1
7
  import { Service as _service } from "typedi";
2
8
  export declare function AppService(target: any): void;
3
9
  export declare function AppService(): any;
@@ -1,4 +1,10 @@
1
1
  "use strict";
2
+ /**
3
+ * @copyright 2024
4
+ * @author Tareq Hossain
5
+ * @email xtrinsic96@gmail.com
6
+ * @url https://github.com/xtareq
7
+ */
2
8
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
9
  if (k2 === undefined) k2 = k;
4
10
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -1,3 +1,12 @@
1
- export declare const e: Record<string, string>;
2
- export type Env = typeof e;
3
- export declare const env: Env;
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
7
+ export declare class Environment {
8
+ private parseEnvFile;
9
+ get<T = any>(key: string): T;
10
+ getOrThrow<T = any>(key: string): T;
11
+ getAll<T = any>(): T;
12
+ }
@@ -1,33 +1,56 @@
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
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
9
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
10
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
11
+ 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;
12
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
13
+ };
2
14
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
15
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
16
  };
5
17
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.env = exports.e = void 0;
18
+ exports.Environment = void 0;
7
19
  const dotenv_1 = __importDefault(require("dotenv"));
8
20
  const path_1 = __importDefault(require("path"));
9
21
  const fs_1 = __importDefault(require("fs"));
10
- // Load environment variables
22
+ const typedi_1 = require("typedi");
23
+ const system_exception_1 = require("./exceptions/system-exception");
11
24
  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;
25
+ let Environment = class Environment {
26
+ parseEnvFile(filePath) {
27
+ try {
28
+ const fileContent = fs_1.default.readFileSync(filePath, 'utf8');
29
+ const parsedEnv = dotenv_1.default.parse(fileContent);
30
+ return Object.assign(Object.assign({}, parsedEnv), process.env);
31
+ }
32
+ catch (error) {
33
+ console.error(`Error parsing .env file: ${error}`);
34
+ return {};
35
+ }
36
+ }
37
+ get(key) {
38
+ const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), '.env'));
39
+ return parsedEnv[key];
40
+ }
41
+ getOrThrow(key) {
42
+ const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), '.env'));
43
+ if (!Object(parsedEnv).hasOwnProperty(key)) {
44
+ throw new system_exception_1.EnvironmentVariableNotFound(key);
45
+ }
46
+ return parsedEnv[key];
47
+ }
48
+ getAll() {
49
+ const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), '.env'));
50
+ return parsedEnv;
51
+ }
31
52
  };
32
- exports.e = parsedEnv;
33
- exports.env = exports.e;
53
+ exports.Environment = Environment;
54
+ exports.Environment = Environment = __decorate([
55
+ (0, typedi_1.Service)()
56
+ ], Environment);
@@ -1,3 +1,9 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
1
7
  export declare abstract class BaseHttpException extends Error {
2
8
  code: number;
3
9
  name: string;
@@ -1,6 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.httpExcepitoins = exports.ForbiddenException = exports.UnauthorizedException = exports.NotFoundException = exports.InternalErrorException = exports.ValidationErrorException = exports.BadRequestException = exports.BaseHttpException = void 0;
4
+ /**
5
+ * @copyright 2024
6
+ * @author Tareq Hossain
7
+ * @email xtrinsic96@gmail.com
8
+ * @url https://github.com/xtareq
9
+ */
4
10
  class BaseHttpException extends Error {
5
11
  constructor(message) {
6
12
  super(JSON.stringify(message));
@@ -1,3 +1,9 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ */
1
7
  export interface IRouteDuplicateErr {
2
8
  path: string;
3
9
  mpath: string;
@@ -11,3 +17,6 @@ export declare class SystemUseError extends Error {
11
17
  export declare class DuplicateRouteException extends Error {
12
18
  constructor(params: IRouteDuplicateErr);
13
19
  }
20
+ export declare class EnvironmentVariableNotFound extends Error {
21
+ constructor(key: string);
22
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DuplicateRouteException = exports.SystemUseError = void 0;
3
+ exports.EnvironmentVariableNotFound = exports.DuplicateRouteException = exports.SystemUseError = void 0;
4
4
  class SystemUseError extends Error {
5
5
  constructor(message) {
6
6
  super(message);
@@ -16,3 +16,9 @@ class DuplicateRouteException extends Error {
16
16
  }
17
17
  }
18
18
  exports.DuplicateRouteException = DuplicateRouteException;
19
+ class EnvironmentVariableNotFound extends Error {
20
+ constructor(key) {
21
+ super(`${key} not found in environment variables.`);
22
+ }
23
+ }
24
+ exports.EnvironmentVariableNotFound = EnvironmentVariableNotFound;
@@ -0,0 +1,17 @@
1
+ import { MultipartFile } from './multipart';
2
+ interface TransformOptions {
3
+ resize?: {
4
+ width: number;
5
+ height: number;
6
+ };
7
+ format?: 'jpeg' | 'png' | 'webp' | 'avif';
8
+ quality?: number;
9
+ }
10
+ export declare class FileStorage {
11
+ private transformOptions;
12
+ transform(options: TransformOptions): this;
13
+ save(f: MultipartFile, options: any): Promise<import("@fastify/multipart").MultipartFile | undefined>;
14
+ saveAs(f: MultipartFile, filename: string, options: any): Promise<import("@fastify/multipart").MultipartFile | undefined>;
15
+ private processImage;
16
+ }
17
+ export {};
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ 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;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __importDefault = (this && this.__importDefault) || function (mod) {
42
+ return (mod && mod.__esModule) ? mod : { "default": mod };
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.FileStorage = void 0;
46
+ const fs_1 = __importDefault(require("fs"));
47
+ const path_1 = __importDefault(require("path"));
48
+ const promises_1 = require("stream/promises");
49
+ const http_exceptions_1 = require("./exceptions/http-exceptions");
50
+ const decorators_1 = require("./decorators");
51
+ const os_1 = __importDefault(require("os"));
52
+ let FileStorage = class FileStorage {
53
+ constructor() {
54
+ this.transformOptions = null;
55
+ }
56
+ transform(options) {
57
+ this.transformOptions = options;
58
+ return this;
59
+ }
60
+ async save(f, options) {
61
+ if (f && f.file) {
62
+ let fname = f.filename;
63
+ if (options) {
64
+ if (options.dest) {
65
+ fname = options.saveAs ? options.dest + '/' + options.saveAs : options.dest + '/' + f.filename;
66
+ }
67
+ else {
68
+ fname = path_1.default.join(process.cwd(), `public/${options.saveAs ? options.saveAs : f.filename}`);
69
+ }
70
+ }
71
+ else {
72
+ fname = path_1.default.join(process.cwd(), `public/${f.filename}`);
73
+ }
74
+ if (fs_1.default.existsSync(fname) && !options.overwrite) {
75
+ throw new http_exceptions_1.InternalErrorException("File already exists.");
76
+ }
77
+ if (this.transformOptions) {
78
+ const tempFilePath = path_1.default.join(os_1.default.tmpdir(), `temp-${Date.now()}-${f.filename}`);
79
+ await (0, promises_1.pipeline)(f.file, fs_1.default.createWriteStream(tempFilePath));
80
+ await this.processImage(fs_1.default.createReadStream(tempFilePath), fname);
81
+ fs_1.default.unlinkSync(tempFilePath);
82
+ }
83
+ else {
84
+ await (0, promises_1.pipeline)(f.file, fs_1.default.createWriteStream(fname));
85
+ }
86
+ return Object.assign(Object.assign({}, f), { filename: (options === null || options === void 0 ? void 0 : options.saveAs) ? options.saveAs : f.filename });
87
+ }
88
+ }
89
+ async saveAs(f, filename, options) {
90
+ if (f && f.file) {
91
+ let fname = filename;
92
+ if (options && options.dest) {
93
+ fname = options.dest + '/' + filename;
94
+ }
95
+ else {
96
+ fname = path_1.default.join(process.cwd(), `public/${filename}`);
97
+ }
98
+ if (fs_1.default.existsSync(fname) && !options.overwrite) {
99
+ throw new http_exceptions_1.InternalErrorException("File already exists.");
100
+ }
101
+ if (this.transformOptions) {
102
+ await this.processImage(f.file, fname);
103
+ }
104
+ else {
105
+ await (0, promises_1.pipeline)(f.file, fs_1.default.createWriteStream(fname));
106
+ }
107
+ return Object.assign(Object.assign({}, f), { filename: filename });
108
+ }
109
+ }
110
+ async processImage(fileStream, outputPath) {
111
+ var _a, _b;
112
+ try {
113
+ const sharp = await Promise.resolve().then(() => __importStar(require('sharp'))); // Lazy import sharp
114
+ let sharpPipeline = sharp.default();
115
+ if ((_a = this.transformOptions) === null || _a === void 0 ? void 0 : _a.resize) {
116
+ sharpPipeline = sharpPipeline.resize(this.transformOptions.resize.width, this.transformOptions.resize.height);
117
+ }
118
+ if ((_b = this.transformOptions) === null || _b === void 0 ? void 0 : _b.format) {
119
+ switch (this.transformOptions.format) {
120
+ case 'jpeg':
121
+ sharpPipeline = sharpPipeline.jpeg({ quality: this.transformOptions.quality || 80 });
122
+ break;
123
+ case 'png':
124
+ sharpPipeline = sharpPipeline.png({ quality: this.transformOptions.quality || 80 });
125
+ break;
126
+ case 'webp':
127
+ sharpPipeline = sharpPipeline.webp({ quality: this.transformOptions.quality || 80 });
128
+ break;
129
+ case 'avif':
130
+ sharpPipeline = sharpPipeline.avif({ quality: this.transformOptions.quality || 80 });
131
+ break;
132
+ default:
133
+ break;
134
+ }
135
+ }
136
+ await (0, promises_1.pipeline)(fileStream, sharpPipeline, fs_1.default.createWriteStream(outputPath));
137
+ }
138
+ catch (error) {
139
+ if (error.code === 'MODULE_NOT_FOUND' && error.message.includes('sharp')) {
140
+ throw new http_exceptions_1.InternalErrorException('sharp module not found. Please install sharp to use image transformations.');
141
+ }
142
+ console.error('Image processing failed:', error);
143
+ throw new http_exceptions_1.InternalErrorException('Image processing failed.');
144
+ }
145
+ finally {
146
+ this.transformOptions = null; // Reset transform options after processing
147
+ }
148
+ }
149
+ };
150
+ exports.FileStorage = FileStorage;
151
+ exports.FileStorage = FileStorage = __decorate([
152
+ decorators_1.AppService
153
+ ], FileStorage);
package/dist/helpers.js CHANGED
@@ -19,6 +19,12 @@ exports.jsonToInstance = jsonToInstance;
19
19
  exports.transformObjectByInstanceToObject = transformObjectByInstanceToObject;
20
20
  exports.validateObjectByInstance = validateObjectByInstance;
21
21
  exports.validateRequestBody = validateRequestBody;
22
+ /**
23
+ * @copyright 2024
24
+ * @author Tareq Hossain
25
+ * @email xtrinsic96@gmail.com
26
+ * @url https://github.com/xtareq
27
+ */
22
28
  const class_transformer_1 = require("class-transformer");
23
29
  const exceptions_1 = require("./exceptions");
24
30
  const fs_1 = __importDefault(require("fs"));
@@ -32,7 +38,7 @@ function inject(cls) {
32
38
  return container_1.default.get(cls);
33
39
  }
34
40
  catch (error) {
35
- throw new system_exception_1.SystemUseError(`Not a project class. Maybe you wanna register it first.`);
41
+ throw new system_exception_1.SystemUseError(`Not a project class. Maybe you wanna register it first.`);
36
42
  }
37
43
  }
38
44
  function isConstructor(func) {