@jsnw/srv-utils 1.0.0

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 (27) hide show
  1. package/dist/config/config-loader.js +61 -0
  2. package/dist/config/config-loader.types.js +2 -0
  3. package/dist/config/index.js +7 -0
  4. package/dist/config/predefined-schemas/connection.schema.js +10 -0
  5. package/dist/config/predefined-schemas/index.js +15 -0
  6. package/dist/config/predefined-schemas/mongodb-connection.schema.js +15 -0
  7. package/dist/config/predefined-schemas/mysql-connection.schema.js +8 -0
  8. package/dist/config/predefined-schemas/redis-connection.schema.js +9 -0
  9. package/dist/config/predefined-schemas/timestring.schema.js +14 -0
  10. package/dist/getRootPackageDirname.js +27 -0
  11. package/dist/index.js +12 -0
  12. package/dist/types/config/config-loader.d.ts +14 -0
  13. package/dist/types/config/config-loader.types.d.ts +4 -0
  14. package/dist/types/config/index.d.ts +3 -0
  15. package/dist/types/config/predefined-schemas/connection.schema.d.ts +7 -0
  16. package/dist/types/config/predefined-schemas/index.d.ts +50 -0
  17. package/dist/types/config/predefined-schemas/mongodb-connection.schema.d.ts +27 -0
  18. package/dist/types/config/predefined-schemas/mysql-connection.schema.d.ts +8 -0
  19. package/dist/types/config/predefined-schemas/redis-connection.schema.d.ts +9 -0
  20. package/dist/types/config/predefined-schemas/timestring.schema.d.ts +2 -0
  21. package/dist/types/getRootPackageDirname.d.ts +4 -0
  22. package/dist/types/index.d.ts +4 -0
  23. package/dist/types/useTsconfigPaths.d.ts +5 -0
  24. package/dist/types/withNest.d.ts +20 -0
  25. package/dist/useTsconfigPaths.js +26 -0
  26. package/dist/withNest.js +84 -0
  27. package/package.json +65 -0
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConfigLoader = void 0;
4
+ const node_path_1 = require("node:path");
5
+ const node_fs_1 = require("node:fs");
6
+ const zod_1 = require("zod");
7
+ const yaml_1 = require("yaml");
8
+ const getRootPackageDirname_1 = require("../getRootPackageDirname");
9
+ const PKG_ROOT_REGEX = /^%pkgroot[\/\\]/i;
10
+ class ConfigLoader {
11
+ /**
12
+ * @template {z.ZodObject} S
13
+ * @template {object} P
14
+ * @param {string} path You can use %pkgroot prefix for automatic project root resolution by AppConfigLoader.
15
+ * Example: %pkgroot/config.yml
16
+ * @param {S} schema
17
+ * @param {P} addProps
18
+ * @returns {ResolvedConfig<S>}
19
+ */
20
+ static loadAndValidate(path, schema, addProps) {
21
+ if (PKG_ROOT_REGEX.test(path))
22
+ path = path.replace(PKG_ROOT_REGEX, (0, getRootPackageDirname_1.getRootPackageDirnameSync)() + node_path_1.sep);
23
+ let data = undefined;
24
+ let parsedYaml = undefined;
25
+ try {
26
+ data = (0, node_fs_1.readFileSync)(path, 'utf-8');
27
+ }
28
+ catch (e) {
29
+ console.error(`Failed to read config file at path: ${path}\nError: ${e?.message ?? '-'}; syscall: ${e?.syscall ?? '-'}`);
30
+ process.exit(1);
31
+ }
32
+ try {
33
+ parsedYaml = (0, yaml_1.parse)(data, { prettyErrors: true });
34
+ }
35
+ catch (e) {
36
+ console.error(`Failed to parse YAML file at path: ${path}\nError: ${e?.message ?? '-'}`);
37
+ process.exit(1);
38
+ }
39
+ const extendedSchema = schema.transform(v => ({
40
+ isDev: (process?.env?.APP_CONTEXT
41
+ ?? process?.env?.APPLICATION_CONTEXT
42
+ ?? process?.env?.NODE_ENV
43
+ ?? '').toLowerCase() !== 'production',
44
+ ...v
45
+ }));
46
+ const { data: config, error, success } = extendedSchema.safeParse(parsedYaml);
47
+ if (!success) {
48
+ if (error && error instanceof zod_1.ZodError) {
49
+ console.error(`Failed to validate config file at path ${path}. Error: ${zod_1.z.prettifyError(error)}`);
50
+ process.exit(1);
51
+ }
52
+ console.error(`Failed to parse config file at path ${path}`);
53
+ process.exit(1);
54
+ }
55
+ return {
56
+ ...config,
57
+ ...(addProps ? {} : addProps)
58
+ };
59
+ }
60
+ }
61
+ exports.ConfigLoader = ConfigLoader;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.configSchemas = exports.ConfigLoader = void 0;
4
+ var config_loader_1 = require("./config-loader");
5
+ Object.defineProperty(exports, "ConfigLoader", { enumerable: true, get: function () { return config_loader_1.ConfigLoader; } });
6
+ var predefined_schemas_1 = require("./predefined-schemas");
7
+ Object.defineProperty(exports, "configSchemas", { enumerable: true, get: function () { return predefined_schemas_1.configSchemas; } });
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectionSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.connectionSchema = zod_1.z.object({
6
+ host: zod_1.z.string().nonempty(),
7
+ port: zod_1.z.number().min(1).max(65535),
8
+ user: zod_1.z.string(),
9
+ pass: zod_1.z.string()
10
+ });
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.configSchemas = void 0;
4
+ const timestring_schema_1 = require("./timestring.schema");
5
+ const connection_schema_1 = require("./connection.schema");
6
+ const mongodb_connection_schema_1 = require("./mongodb-connection.schema");
7
+ const mysql_connection_schema_1 = require("./mysql-connection.schema");
8
+ const redis_connection_schema_1 = require("./redis-connection.schema");
9
+ exports.configSchemas = {
10
+ timeString: timestring_schema_1.timeStringSchema,
11
+ connection: connection_schema_1.connectionSchema,
12
+ mongodbConnection: mongodb_connection_schema_1.mongodbConnectionSchema,
13
+ mysqlConnection: mysql_connection_schema_1.mysqlConnectionSchema,
14
+ redisConnection: redis_connection_schema_1.redisConnectionSchema
15
+ };
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mongodbConnectionSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const connection_schema_1 = require("./connection.schema");
6
+ const timestring_schema_1 = require("./timestring.schema");
7
+ exports.mongodbConnectionSchema = connection_schema_1.connectionSchema.extend({
8
+ db: zod_1.z.string().nonempty(),
9
+ authDb: zod_1.z.string().optional(),
10
+ connectTimeout: timestring_schema_1.timeStringSchema.default(5_000)
11
+ }).transform(v => ({
12
+ ...v,
13
+ authDb: v.authDb || v.db,
14
+ dsn: `mongodb://${v.host}:${v.port}/${v.db}`
15
+ }));
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mysqlConnectionSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const connection_schema_1 = require("./connection.schema");
6
+ exports.mysqlConnectionSchema = connection_schema_1.connectionSchema.extend({
7
+ dbname: zod_1.z.string().nonempty()
8
+ });
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.redisConnectionSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const connection_schema_1 = require("./connection.schema");
6
+ exports.redisConnectionSchema = connection_schema_1.connectionSchema.extend({
7
+ db: zod_1.z.number().min(0).default(0),
8
+ keyPrefix: zod_1.z.string().default('')
9
+ });
@@ -0,0 +1,14 @@
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.timeStringSchema = void 0;
7
+ const zod_1 = require("zod");
8
+ const ms_1 = __importDefault(require("ms"));
9
+ const TIMESTRING_UNIT = ['Years', 'Year', 'Yrs', 'Yr', 'Y', 'Weeks', 'Week', 'W', 'Days', 'Day', 'D', 'Hours', 'Hour', 'Hrs', 'Hr', 'H', 'Minutes', 'Minute', 'Mins', 'Min', 'M', 'Seconds', 'Second', 'Secs', 'Sec', 's', 'Milliseconds', 'Millisecond', 'Msecs', 'Msec', 'Ms'];
10
+ const TIMESTRING_REGEX = new RegExp(`\\d+\\s*(?:${TIMESTRING_UNIT.map(unit => unit.toLowerCase()).join('|')})`, 'i');
11
+ exports.timeStringSchema = zod_1.z.string()
12
+ .nonempty()
13
+ .regex(TIMESTRING_REGEX)
14
+ .transform(v => (0, ms_1.default)(v));
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getRootPackageDirnameSync = getRootPackageDirnameSync;
4
+ const node_path_1 = require("node:path");
5
+ const node_fs_1 = require("node:fs");
6
+ let cachedRootPackageDirname = null;
7
+ /**
8
+ * @returns {string}
9
+ */
10
+ function getRootPackageDirnameSync() {
11
+ if (cachedRootPackageDirname !== null)
12
+ return cachedRootPackageDirname;
13
+ let path = (0, node_path_1.resolve)(__dirname, '..'), lastValidPath = path;
14
+ while (true) {
15
+ const packageJsonPath = (0, node_path_1.resolve)(path, 'package.json');
16
+ try {
17
+ (0, node_fs_1.accessSync)(packageJsonPath, node_fs_1.constants.F_OK | node_fs_1.constants.R_OK);
18
+ }
19
+ catch (e) {
20
+ break;
21
+ }
22
+ lastValidPath = path;
23
+ path = (0, node_path_1.resolve)(path, '..');
24
+ }
25
+ cachedRootPackageDirname = lastValidPath;
26
+ return lastValidPath;
27
+ }
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withNest = exports.configSchemas = exports.ConfigLoader = exports.getRootPackageDirnameSync = exports.useTsconfigPaths = void 0;
4
+ var useTsconfigPaths_1 = require("./useTsconfigPaths");
5
+ Object.defineProperty(exports, "useTsconfigPaths", { enumerable: true, get: function () { return useTsconfigPaths_1.useTsconfigPaths; } });
6
+ var getRootPackageDirname_1 = require("./getRootPackageDirname");
7
+ Object.defineProperty(exports, "getRootPackageDirnameSync", { enumerable: true, get: function () { return getRootPackageDirname_1.getRootPackageDirnameSync; } });
8
+ var config_1 = require("./config");
9
+ Object.defineProperty(exports, "ConfigLoader", { enumerable: true, get: function () { return config_1.ConfigLoader; } });
10
+ Object.defineProperty(exports, "configSchemas", { enumerable: true, get: function () { return config_1.configSchemas; } });
11
+ var withNest_1 = require("./withNest");
12
+ Object.defineProperty(exports, "withNest", { enumerable: true, get: function () { return withNest_1.withNest; } });
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+ import { ResolvedConfig } from './config-loader.types';
3
+ export declare abstract class ConfigLoader {
4
+ /**
5
+ * @template {z.ZodObject} S
6
+ * @template {object} P
7
+ * @param {string} path You can use %pkgroot prefix for automatic project root resolution by AppConfigLoader.
8
+ * Example: %pkgroot/config.yml
9
+ * @param {S} schema
10
+ * @param {P} addProps
11
+ * @returns {ResolvedConfig<S>}
12
+ */
13
+ static loadAndValidate<S extends z.ZodObject, P extends object | undefined = undefined>(path: string, schema: S, addProps?: P): ResolvedConfig<S, P>;
14
+ }
@@ -0,0 +1,4 @@
1
+ import { z } from 'zod';
2
+ export type ResolvedConfig<T extends z.ZodObject, P extends object | undefined = undefined> = z.output<T> & {
3
+ isDev: boolean;
4
+ } & (P extends undefined ? {} : P);
@@ -0,0 +1,3 @@
1
+ export { ConfigLoader } from './config-loader';
2
+ export type { ResolvedConfig } from './config-loader.types';
3
+ export { configSchemas } from './predefined-schemas';
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+ export declare const connectionSchema: z.ZodObject<{
3
+ host: z.ZodString;
4
+ port: z.ZodNumber;
5
+ user: z.ZodString;
6
+ pass: z.ZodString;
7
+ }, z.core.$strip>;
@@ -0,0 +1,50 @@
1
+ export declare const configSchemas: {
2
+ timeString: import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodTransform<number, string>>;
3
+ connection: import("zod").ZodObject<{
4
+ host: import("zod").ZodString;
5
+ port: import("zod").ZodNumber;
6
+ user: import("zod").ZodString;
7
+ pass: import("zod").ZodString;
8
+ }, import("zod/v4/core").$strip>;
9
+ mongodbConnection: import("zod").ZodPipe<import("zod").ZodObject<{
10
+ host: import("zod").ZodString;
11
+ port: import("zod").ZodNumber;
12
+ user: import("zod").ZodString;
13
+ pass: import("zod").ZodString;
14
+ db: import("zod").ZodString;
15
+ authDb: import("zod").ZodOptional<import("zod").ZodString>;
16
+ connectTimeout: import("zod").ZodDefault<import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodTransform<number, string>>>;
17
+ }, import("zod/v4/core").$strip>, import("zod").ZodTransform<{
18
+ authDb: string;
19
+ dsn: string;
20
+ host: string;
21
+ port: number;
22
+ user: string;
23
+ pass: string;
24
+ db: string;
25
+ connectTimeout: number;
26
+ }, {
27
+ host: string;
28
+ port: number;
29
+ user: string;
30
+ pass: string;
31
+ db: string;
32
+ connectTimeout: number;
33
+ authDb?: string;
34
+ }>>;
35
+ mysqlConnection: import("zod").ZodObject<{
36
+ host: import("zod").ZodString;
37
+ port: import("zod").ZodNumber;
38
+ user: import("zod").ZodString;
39
+ pass: import("zod").ZodString;
40
+ dbname: import("zod").ZodString;
41
+ }, import("zod/v4/core").$strip>;
42
+ redisConnection: import("zod").ZodObject<{
43
+ host: import("zod").ZodString;
44
+ port: import("zod").ZodNumber;
45
+ user: import("zod").ZodString;
46
+ pass: import("zod").ZodString;
47
+ db: import("zod").ZodDefault<import("zod").ZodNumber>;
48
+ keyPrefix: import("zod").ZodDefault<import("zod").ZodString>;
49
+ }, import("zod/v4/core").$strip>;
50
+ };
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ export declare const mongodbConnectionSchema: z.ZodPipe<z.ZodObject<{
3
+ host: z.ZodString;
4
+ port: z.ZodNumber;
5
+ user: z.ZodString;
6
+ pass: z.ZodString;
7
+ db: z.ZodString;
8
+ authDb: z.ZodOptional<z.ZodString>;
9
+ connectTimeout: z.ZodDefault<z.ZodPipe<z.ZodString, z.ZodTransform<number, string>>>;
10
+ }, z.core.$strip>, z.ZodTransform<{
11
+ authDb: string;
12
+ dsn: string;
13
+ host: string;
14
+ port: number;
15
+ user: string;
16
+ pass: string;
17
+ db: string;
18
+ connectTimeout: number;
19
+ }, {
20
+ host: string;
21
+ port: number;
22
+ user: string;
23
+ pass: string;
24
+ db: string;
25
+ connectTimeout: number;
26
+ authDb?: string;
27
+ }>>;
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+ export declare const mysqlConnectionSchema: z.ZodObject<{
3
+ host: z.ZodString;
4
+ port: z.ZodNumber;
5
+ user: z.ZodString;
6
+ pass: z.ZodString;
7
+ dbname: z.ZodString;
8
+ }, z.core.$strip>;
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ export declare const redisConnectionSchema: z.ZodObject<{
3
+ host: z.ZodString;
4
+ port: z.ZodNumber;
5
+ user: z.ZodString;
6
+ pass: z.ZodString;
7
+ db: z.ZodDefault<z.ZodNumber>;
8
+ keyPrefix: z.ZodDefault<z.ZodString>;
9
+ }, z.core.$strip>;
@@ -0,0 +1,2 @@
1
+ import { z } from 'zod';
2
+ export declare const timeStringSchema: z.ZodPipe<z.ZodString, z.ZodTransform<number, string>>;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @returns {string}
3
+ */
4
+ export declare function getRootPackageDirnameSync(): string;
@@ -0,0 +1,4 @@
1
+ export { useTsconfigPaths } from './useTsconfigPaths';
2
+ export { getRootPackageDirnameSync } from './getRootPackageDirname';
3
+ export { ConfigLoader, configSchemas, type ResolvedConfig } from './config';
4
+ export { withNest } from './withNest';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @param {string} fromPath
3
+ * @param {string} tsconfigPath
4
+ */
5
+ export declare function useTsconfigPaths(fromPath: string, tsconfigPath: string): void;
@@ -0,0 +1,20 @@
1
+ import type { INestApplicationContext } from '@nestjs/common';
2
+ type WithNestFn = (app: INestApplicationContext, preventClosing: () => void) => Promise<void>;
3
+ /**
4
+ * Executes a given function within the context of a NestJS application.
5
+ *
6
+ * This asynchronous function initializes a NestJS application context using the specified
7
+ * module class and then executes the provided function `fn` with the application instance.
8
+ * The application context is automatically closed upon completion of the function execution,
9
+ * unless the function execution requests otherwise by invoking a callback.
10
+ *
11
+ * @param {any} moduleCls - The module class to be used for creating the NestJS application context.
12
+ * @param {WithNestFn} fn - The function to be executed with the NestJS application context.
13
+ * It receives the application instance and a callback to prevent
14
+ * automatic application context closure.
15
+ * @returns {Promise<void>} A promise that resolves when the function execution is complete.
16
+ * @throws - Will throw an error if the `@nestjs/core` and/or `@nestjs/common` library is not found.
17
+ * @throws - Will propagate any error thrown by the executed function `fn`.
18
+ */
19
+ export declare function withNest(moduleCls: any, fn: WithNestFn): Promise<void>;
20
+ export {};
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useTsconfigPaths = useTsconfigPaths;
4
+ const node_path_1 = require("node:path");
5
+ /**
6
+ * @param {string} fromPath
7
+ * @param {string} tsconfigPath
8
+ */
9
+ function useTsconfigPaths(fromPath, tsconfigPath) {
10
+ let moduleAlias = null;
11
+ try {
12
+ require('module-alias/register');
13
+ moduleAlias = require('module-alias');
14
+ }
15
+ catch (e) {
16
+ throw new Error('module-alias package should be installed to use the function');
17
+ }
18
+ const tsconfig = require(tsconfigPath), tsconfigDirPathname = (0, node_path_1.dirname)(tsconfigPath), paths = {};
19
+ Object.entries((tsconfig?.compilerOptions?.paths ?? {}))
20
+ .forEach(([moduleName, pathArray]) => {
21
+ if (pathArray.length === 0)
22
+ return;
23
+ paths[moduleName] = (0, node_path_1.resolve)(tsconfigDirPathname, (0, node_path_1.relative)(tsconfigDirPathname, fromPath), pathArray[0]);
24
+ });
25
+ moduleAlias.addAliases(paths);
26
+ }
@@ -0,0 +1,84 @@
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 __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
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.withNest = withNest;
37
+ /**
38
+ * Executes a given function within the context of a NestJS application.
39
+ *
40
+ * This asynchronous function initializes a NestJS application context using the specified
41
+ * module class and then executes the provided function `fn` with the application instance.
42
+ * The application context is automatically closed upon completion of the function execution,
43
+ * unless the function execution requests otherwise by invoking a callback.
44
+ *
45
+ * @param {any} moduleCls - The module class to be used for creating the NestJS application context.
46
+ * @param {WithNestFn} fn - The function to be executed with the NestJS application context.
47
+ * It receives the application instance and a callback to prevent
48
+ * automatic application context closure.
49
+ * @returns {Promise<void>} A promise that resolves when the function execution is complete.
50
+ * @throws - Will throw an error if the `@nestjs/core` and/or `@nestjs/common` library is not found.
51
+ * @throws - Will propagate any error thrown by the executed function `fn`.
52
+ */
53
+ async function withNest(moduleCls, fn) {
54
+ let nestFactory = null;
55
+ try {
56
+ nestFactory = (await Promise.resolve().then(() => __importStar(require('@nestjs/core'))))?.NestFactory;
57
+ if (!nestFactory)
58
+ throw new Error('NestFactory not found');
59
+ }
60
+ catch (e) {
61
+ throw new Error('@nestjs/core and @nestjs/common are required for this function to work');
62
+ }
63
+ const app = await nestFactory.createApplicationContext(moduleCls);
64
+ let closeApplication = true;
65
+ let _e = undefined;
66
+ try {
67
+ await fn(app, () => {
68
+ closeApplication = false;
69
+ });
70
+ }
71
+ catch (e) {
72
+ console.error('Error caught while executing the WithNestFn. Error:', e);
73
+ _e = e;
74
+ }
75
+ try {
76
+ if (closeApplication)
77
+ await app.close();
78
+ }
79
+ catch (e) {
80
+ console.error('Failed to close application. Error:', e);
81
+ }
82
+ if (_e)
83
+ throw _e;
84
+ }
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@jsnw/srv-utils",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/types/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./dist/index.js",
10
+ "types": "./dist/types/index.d.ts"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "clean": "rimraf ./dist",
15
+ "build": "npm run clean && tsc -p tsconfig.json",
16
+ "test": "jest --passWithNoTests",
17
+ "test:watch": "jest --watch",
18
+ "test:coverage": "jest --coverage",
19
+ "prepublishOnly": "npm run build"
20
+ },
21
+ "files": [
22
+ "./dist",
23
+ "README.md"
24
+ ],
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+ssh://git@github.com/pvbaliuk/jsn-srv-utils.git"
28
+ },
29
+ "keywords": [
30
+ "util",
31
+ "utils"
32
+ ],
33
+ "author": {
34
+ "name": "Pavlo Baliuk",
35
+ "email": "jsnow0177@gmail.com"
36
+ },
37
+ "license": "MIT",
38
+ "bugs": {
39
+ "url": "https://github.com/pvbaliuk/jsn-srv-utils/issues"
40
+ },
41
+ "homepage": "https://github.com/pvbaliuk/jsn-srv-utils#readme",
42
+ "dependencies": {
43
+ "ms": "^2.1.3",
44
+ "yaml": "^2.8.2",
45
+ "zod": "^4.3.6"
46
+ },
47
+ "optionalDependencies": {
48
+ "@nestjs/common": "^11.1.12",
49
+ "@nestjs/core": "^11.1.12",
50
+ "module-alias": "^2.3.3"
51
+ },
52
+ "devDependencies": {
53
+ "@nestjs/common": "^11.1.12",
54
+ "@nestjs/core": "^11.1.12",
55
+ "@types/jest": "^30.0.0",
56
+ "@types/module-alias": "^2.0.4",
57
+ "@types/ms": "^2.1.0",
58
+ "jest": "^30.2.0",
59
+ "module-alias": "^2.3.3",
60
+ "rimraf": "^6.1.2",
61
+ "ts-jest": "^29.4.6",
62
+ "tslib": "^2.8.1",
63
+ "typescript": "^5.9.3"
64
+ }
65
+ }