@akanjs/nest 0.0.4

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.
@@ -0,0 +1,113 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var exporter_exports = {};
29
+ __export(exporter_exports, {
30
+ FileSystem: () => FileSystem,
31
+ exportToCsv: () => exportToCsv,
32
+ exportToJson: () => exportToJson,
33
+ objPath: () => objPath,
34
+ readJson: () => readJson
35
+ });
36
+ module.exports = __toCommonJS(exporter_exports);
37
+ var fs = __toESM(require("fs"));
38
+ const objPath = (o, p) => p.split(".").reduce((a, v) => a[v], o);
39
+ class FileSystem {
40
+ filename = "";
41
+ dirname = "./";
42
+ writeStream;
43
+ constructor(dirname = "./", filename = "") {
44
+ this.dirname = dirname;
45
+ this.filename = filename;
46
+ }
47
+ async init() {
48
+ return new Promise((resolve, reject) => {
49
+ fs.mkdirSync(this.dirname, { recursive: true });
50
+ const writeStream = fs.createWriteStream(`${this.dirname}/${this.filename}.csv`);
51
+ if (!writeStream) {
52
+ reject(new Error("No WriteStream"));
53
+ return;
54
+ }
55
+ writeStream.once(`open`, () => {
56
+ this.writeStream = writeStream;
57
+ resolve(writeStream);
58
+ });
59
+ });
60
+ }
61
+ write(body) {
62
+ if (!this.writeStream)
63
+ throw new Error("no write stream");
64
+ return this.writeStream.write(`${body.replace(/\n/g, "")}
65
+ `);
66
+ }
67
+ // async finish() {}
68
+ }
69
+ const exportToCsv = async ({ items, path, fields, delimiter, options }) => {
70
+ return new Promise((resolve, reject) => {
71
+ const dirs = path.split("/");
72
+ if (dirs.length > 1) {
73
+ const dirname = dirs.slice(-1).join("/");
74
+ if (!fs.existsSync(dirname))
75
+ fs.mkdirSync(dirname, { recursive: true });
76
+ }
77
+ if (!fields)
78
+ throw new Error("Fields Required");
79
+ const writeStream = !options?.append && fs.createWriteStream(path);
80
+ const header = fields.reduce((acc, cur) => acc + (delimiter ?? `,`) + cur) + `
81
+ `;
82
+ if (!writeStream) {
83
+ reject(new Error("No WriteStream"));
84
+ return;
85
+ }
86
+ writeStream.once(`open`, () => {
87
+ writeStream.write(header);
88
+ for (const item of items) {
89
+ const data = fields.map((field) => objPath(item, field) || null).map((field) => String(field).replace(/\n/g, "").replace(/,/g, ""));
90
+ const body = data.reduce((acc, cur) => acc + (delimiter ?? `,`) + cur) + `
91
+ `;
92
+ if (options?.append)
93
+ fs.appendFileSync(path, body);
94
+ }
95
+ resolve();
96
+ });
97
+ });
98
+ };
99
+ const exportToJson = (items, localPath) => {
100
+ const dirname = localPath.split("/").slice(0, -1).join("/");
101
+ if (!fs.existsSync(dirname))
102
+ fs.mkdirSync(dirname, { recursive: true });
103
+ fs.writeFileSync(localPath, JSON.stringify(items));
104
+ };
105
+ const readJson = (localPath) => JSON.parse(fs.readFileSync(localPath).toString("utf-8"));
106
+ // Annotate the CommonJS export names for ESM import in node:
107
+ 0 && (module.exports = {
108
+ FileSystem,
109
+ exportToCsv,
110
+ exportToJson,
111
+ objPath,
112
+ readJson
113
+ });
@@ -0,0 +1,36 @@
1
+ import { BackendEnv, type BaseEnv } from "@akanjs/base";
2
+ import { SshOptions } from "tunnel-ssh";
3
+ export declare const generateJwtSecret: (appName: string, environment: "debug" | "develop" | "main" | "testing") => string;
4
+ export declare const generateAeskey: (appName: string, environment: "debug" | "develop" | "main" | "testing") => string;
5
+ interface RedisEnv {
6
+ appName: string;
7
+ appCode: number;
8
+ environment: BaseEnv["environment"];
9
+ operationMode: BaseEnv["operationMode"];
10
+ sshOptions?: SshOptions;
11
+ }
12
+ export declare const generateRedisUri: ({ appName, appCode, environment, operationMode, sshOptions }: RedisEnv) => Promise<string>;
13
+ interface MongoEnv {
14
+ appName: string;
15
+ appCode: number;
16
+ environment: BaseEnv["environment"];
17
+ operationMode: BaseEnv["operationMode"];
18
+ username?: string;
19
+ password?: string;
20
+ sshOptions?: SshOptions;
21
+ }
22
+ export declare const generateMongoUri: ({ appName, appCode, environment, operationMode, username, password, sshOptions, }: MongoEnv) => Promise<string>;
23
+ interface MeiliEnv {
24
+ appName: string;
25
+ appCode: number;
26
+ environment: BaseEnv["environment"];
27
+ operationMode: BaseEnv["operationMode"];
28
+ }
29
+ export declare const generateMeiliUri: ({ appName, appCode, environment, operationMode }: MeiliEnv) => string;
30
+ export declare const SALT_ROUNDS = 11;
31
+ export declare const generateHost: (env: BackendEnv) => string;
32
+ export declare const generateMeiliKey: ({ appName, environment }: {
33
+ appName: string;
34
+ environment: string;
35
+ }) => string;
36
+ export {};
@@ -0,0 +1,139 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var generateSecrets_exports = {};
19
+ __export(generateSecrets_exports, {
20
+ SALT_ROUNDS: () => SALT_ROUNDS,
21
+ generateAeskey: () => generateAeskey,
22
+ generateHost: () => generateHost,
23
+ generateJwtSecret: () => generateJwtSecret,
24
+ generateMeiliKey: () => generateMeiliKey,
25
+ generateMeiliUri: () => generateMeiliUri,
26
+ generateMongoUri: () => generateMongoUri,
27
+ generateRedisUri: () => generateRedisUri
28
+ });
29
+ module.exports = __toCommonJS(generateSecrets_exports);
30
+ var import_base = require("@akanjs/base");
31
+ var import_crypto = require("crypto");
32
+ var import_tunnel_ssh = require("tunnel-ssh");
33
+ const generateHexStringFromSeed = (seed, length = 256) => {
34
+ let hexString = "";
35
+ let currentSeed = seed;
36
+ while (hexString.length < length * 2) {
37
+ const hash = (0, import_crypto.createHash)("sha256").update(currentSeed).digest("hex");
38
+ hexString += hash;
39
+ currentSeed = hash;
40
+ }
41
+ return hexString.substring(0, length * 2);
42
+ };
43
+ const generateJwtSecret = (appName, environment) => {
44
+ const seed = `${appName}-${environment}-jwt-secret`;
45
+ return generateHexStringFromSeed(seed);
46
+ };
47
+ const generateAeskey = (appName, environment) => {
48
+ const seed = `${appName}-${environment}-aes-key`;
49
+ return (0, import_crypto.createHash)("sha256").update(seed).digest("hex");
50
+ };
51
+ const DEFAULT_CLOUD_PORT = 3e4;
52
+ const getEnvironmentPort = (environment) => environment === "main" ? 2e3 : environment === "develop" ? 1e3 : environment === "debug" ? 0 : 0;
53
+ const getServicePort = (appCode, service) => (service === "redis" ? 300 : service === "mongo" ? 400 : 500) + appCode % 10 * 10 + (appCode >= 10 ? 5 : 0);
54
+ const createDatabaseTunnel = async ({
55
+ appName,
56
+ environment,
57
+ type,
58
+ port,
59
+ sshOptions = {
60
+ host: `${appName}-${environment}.${import_base.baseEnv.serveDomain}`,
61
+ port: 32767,
62
+ username: "root",
63
+ password: import_base.baseEnv.repoName
64
+ }
65
+ }) => {
66
+ const tunnelOptions = { autoClose: true, reconnectOnError: false };
67
+ const serverOptions = { port };
68
+ const forwardOptions = {
69
+ srcAddr: "0.0.0.0",
70
+ srcPort: port,
71
+ dstAddr: `${type}-0.${type}-svc.${appName}-${environment}`,
72
+ dstPort: type === "mongo" ? 27017 : type === "redis" ? 6379 : 7700
73
+ };
74
+ const [server, client] = await (0, import_tunnel_ssh.createTunnel)(tunnelOptions, serverOptions, sshOptions, forwardOptions);
75
+ return `localhost:${port}`;
76
+ };
77
+ const generateRedisUri = async ({ appName, appCode, environment, operationMode, sshOptions }) => {
78
+ if (process.env.REDIS_URI)
79
+ return process.env.REDIS_URI;
80
+ const port = operationMode === "local" ? DEFAULT_CLOUD_PORT + getEnvironmentPort(environment) + getServicePort(appCode, "redis") : 6379;
81
+ const url = operationMode === "cloud" ? `redis-svc.${appName}-${environment}.svc.cluster.local` : operationMode === "local" ? await createDatabaseTunnel({ appName, environment, type: "redis", port, sshOptions }) : "localhost:6379";
82
+ const uri = `redis://${url}`;
83
+ return uri;
84
+ };
85
+ const generateMongoUri = async ({
86
+ appName,
87
+ appCode,
88
+ environment,
89
+ operationMode,
90
+ username = `${appName}-${environment}-mongo-user`,
91
+ password,
92
+ sshOptions
93
+ }) => {
94
+ if (process.env.MONGO_URI)
95
+ return process.env.MONGO_URI;
96
+ const record = operationMode === "cloud" ? "mongodb+srv" : "mongodb";
97
+ const port = operationMode === "local" ? DEFAULT_CLOUD_PORT + getEnvironmentPort(environment) + getServicePort(appCode, "mongo") : 27017;
98
+ const url = operationMode === "cloud" ? `mongo-svc.${appName}-${environment}.svc.cluster.local` : operationMode === "local" ? await createDatabaseTunnel({ appName, environment, type: "mongo", port, sshOptions }) : "localhost:27017";
99
+ const usernameEncoded = password ? encodeURIComponent(username) : null;
100
+ const passwordEncoded = password ? encodeURIComponent(password) : null;
101
+ const dbName = `${appName}-${environment}`;
102
+ const directConnection = operationMode === "cloud" ? false : true;
103
+ const authInfo = usernameEncoded ? `${usernameEncoded}:${passwordEncoded}@` : "";
104
+ const uri = `${record}://${authInfo}${url}/${dbName}?authSource=${dbName}&readPreference=primary&ssl=false&retryWrites=true&directConnection=${directConnection}`;
105
+ return uri;
106
+ };
107
+ const generateMeiliUri = ({ appName, appCode, environment, operationMode }) => {
108
+ if (process.env.MEILI_URI)
109
+ return process.env.MEILI_URI;
110
+ const protocol = operationMode === "local" ? "https" : "http";
111
+ const url = operationMode === "cloud" ? `meili-0.meili-svc.${appName}-${environment}.svc.cluster.local:7700` : operationMode === "local" ? `${appName}-${environment}.${import_base.baseEnv.serveDomain}/search` : "localhost:7700";
112
+ const uri = `${protocol}://${url}`;
113
+ return uri;
114
+ };
115
+ const SALT_ROUNDS = 11;
116
+ const generateHost = (env) => {
117
+ if (process.env.HOST_NAME)
118
+ return process.env.HOST_NAME;
119
+ else if (env.hostname)
120
+ return env.hostname;
121
+ else if (env.operationMode === "local")
122
+ return "localhost";
123
+ else
124
+ return `${env.appName}-${env.environment}.${import_base.baseEnv.serveDomain}`;
125
+ };
126
+ const generateMeiliKey = ({ appName, environment }) => {
127
+ return `meilisearch-key-${appName}-${environment}`;
128
+ };
129
+ // Annotate the CommonJS export names for ESM import in node:
130
+ 0 && (module.exports = {
131
+ SALT_ROUNDS,
132
+ generateAeskey,
133
+ generateHost,
134
+ generateJwtSecret,
135
+ generateMeiliKey,
136
+ generateMeiliUri,
137
+ generateMongoUri,
138
+ generateRedisUri
139
+ });
package/src/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export * from "./authorization";
2
+ export * from "./authGuards";
3
+ export * as guards from "./authGuards";
4
+ export * from "./authentication";
5
+ export * from "./interceptors";
6
+ export * as Inquirer from "./inquirer";
7
+ export * from "./redis-io.adapter";
8
+ export * from "./pipes";
9
+ export * as Exporter from "./exporter";
10
+ export * from "./exporter";
11
+ export * from "./verifyPayment";
12
+ export * from "./sso";
13
+ export * from "./exceptions";
14
+ export * from "./generateSecrets";
15
+ export * from "./mongoose";
package/src/index.js ADDED
@@ -0,0 +1,68 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var src_exports = {};
30
+ __export(src_exports, {
31
+ Exporter: () => Exporter,
32
+ Inquirer: () => Inquirer,
33
+ guards: () => guards
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+ __reExport(src_exports, require("./authorization"), module.exports);
37
+ __reExport(src_exports, require("./authGuards"), module.exports);
38
+ var guards = __toESM(require("./authGuards"));
39
+ __reExport(src_exports, require("./authentication"), module.exports);
40
+ __reExport(src_exports, require("./interceptors"), module.exports);
41
+ var Inquirer = __toESM(require("./inquirer"));
42
+ __reExport(src_exports, require("./redis-io.adapter"), module.exports);
43
+ __reExport(src_exports, require("./pipes"), module.exports);
44
+ var Exporter = __toESM(require("./exporter"));
45
+ __reExport(src_exports, require("./exporter"), module.exports);
46
+ __reExport(src_exports, require("./verifyPayment"), module.exports);
47
+ __reExport(src_exports, require("./sso"), module.exports);
48
+ __reExport(src_exports, require("./exceptions"), module.exports);
49
+ __reExport(src_exports, require("./generateSecrets"), module.exports);
50
+ __reExport(src_exports, require("./mongoose"), module.exports);
51
+ // Annotate the CommonJS export names for ESM import in node:
52
+ 0 && (module.exports = {
53
+ Exporter,
54
+ Inquirer,
55
+ guards,
56
+ ...require("./authorization"),
57
+ ...require("./authGuards"),
58
+ ...require("./authentication"),
59
+ ...require("./interceptors"),
60
+ ...require("./redis-io.adapter"),
61
+ ...require("./pipes"),
62
+ ...require("./exporter"),
63
+ ...require("./verifyPayment"),
64
+ ...require("./sso"),
65
+ ...require("./exceptions"),
66
+ ...require("./generateSecrets"),
67
+ ...require("./mongoose")
68
+ });
@@ -0,0 +1,20 @@
1
+ interface ChoiceType {
2
+ color?: string;
3
+ name: string;
4
+ value: string;
5
+ }
6
+ interface NumberChoiceType {
7
+ color?: string;
8
+ name: string;
9
+ value: string;
10
+ }
11
+ export declare const input: (message: string) => Promise<string>;
12
+ export declare const select: (message: string, choices: ChoiceType[]) => Promise<string>;
13
+ export declare const confirm: (message: string) => Promise<boolean>;
14
+ export declare const checkbox: (message: string, choices: ChoiceType[]) => Promise<string[]>;
15
+ export declare const editor: (message: string) => Promise<string>;
16
+ export declare const number: (message: string) => Promise<number | undefined>;
17
+ export declare const rawlist: (message: string, choices: NumberChoiceType[]) => Promise<string>;
18
+ export declare const password: (message: string) => Promise<string>;
19
+ export declare const expand: (message: string, choices: ChoiceType[]) => Promise<string>;
20
+ export {};
@@ -0,0 +1,114 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var inquirer_exports = {};
29
+ __export(inquirer_exports, {
30
+ checkbox: () => checkbox,
31
+ confirm: () => confirm,
32
+ editor: () => editor,
33
+ expand: () => expand,
34
+ input: () => input,
35
+ number: () => number,
36
+ password: () => password,
37
+ rawlist: () => rawlist,
38
+ select: () => select
39
+ });
40
+ module.exports = __toCommonJS(inquirer_exports);
41
+ var import_prompts = require("@inquirer/prompts");
42
+ var import_picocolors = __toESM(require("picocolors"));
43
+ const input = async (message) => {
44
+ return await (0, import_prompts.input)({ message });
45
+ };
46
+ const select = async (message, choices) => {
47
+ return await (0, import_prompts.select)({
48
+ message,
49
+ choices: choices.map((choice) => {
50
+ return {
51
+ name: choice.color ? import_picocolors.default.bgRed(import_picocolors.default.white(choice.name)) : choice.name,
52
+ value: choice.value
53
+ };
54
+ })
55
+ });
56
+ };
57
+ const confirm = async (message) => {
58
+ return await (0, import_prompts.confirm)({ message });
59
+ };
60
+ const checkbox = async (message, choices) => {
61
+ return await (0, import_prompts.checkbox)({
62
+ message,
63
+ choices: choices.map((choice) => {
64
+ return {
65
+ name: choice.color ? import_picocolors.default.bgRed(import_picocolors.default.white(choice.name)) : choice.name,
66
+ value: choice.value
67
+ };
68
+ })
69
+ });
70
+ };
71
+ const editor = async (message) => {
72
+ return await (0, import_prompts.editor)({ message });
73
+ };
74
+ const number = async (message) => {
75
+ return await (0, import_prompts.number)({ message });
76
+ };
77
+ const rawlist = async (message, choices) => {
78
+ return await (0, import_prompts.rawlist)({
79
+ message,
80
+ choices: choices.map((choice) => {
81
+ return {
82
+ name: choice.color ? import_picocolors.default.bgRed(import_picocolors.default.white(choice.name)) : choice.name,
83
+ value: choice.value
84
+ };
85
+ })
86
+ });
87
+ };
88
+ const password = async (message) => {
89
+ return await (0, import_prompts.password)({ message });
90
+ };
91
+ const expand = async (message, choices) => {
92
+ return await (0, import_prompts.expand)({
93
+ message,
94
+ choices: choices.map((choice) => {
95
+ return {
96
+ key: choice.value,
97
+ name: choice.color ? import_picocolors.default.bgRed(import_picocolors.default.white(choice.name)) : choice.name,
98
+ value: choice.value
99
+ };
100
+ })
101
+ });
102
+ };
103
+ // Annotate the CommonJS export names for ESM import in node:
104
+ 0 && (module.exports = {
105
+ checkbox,
106
+ confirm,
107
+ editor,
108
+ expand,
109
+ input,
110
+ number,
111
+ password,
112
+ rawlist,
113
+ select
114
+ });
@@ -0,0 +1,19 @@
1
+ import { Logger } from "@akanjs/common";
2
+ import { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
3
+ import type { RedisClientType } from "redis";
4
+ import { Observable } from "rxjs";
5
+ export declare class CacheInterceptor implements NestInterceptor {
6
+ private redis;
7
+ logger: Logger;
8
+ constructor(redis: RedisClientType);
9
+ setCache(key: string, value: any, expire: number): Promise<void>;
10
+ getCache<T = object>(key: string): Promise<T | null>;
11
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
12
+ }
13
+ export declare class TimeoutInterceptor implements NestInterceptor {
14
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
15
+ }
16
+ export declare class LoggingInterceptor implements NestInterceptor {
17
+ logger: Logger;
18
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
19
+ }
@@ -0,0 +1,132 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from2, except, desc) => {
10
+ if (from2 && typeof from2 === "object" || typeof from2 === "function") {
11
+ for (let key of __getOwnPropNames(from2))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var __decorateClass = (decorators, target, key, kind) => {
19
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
20
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
21
+ if (decorator = decorators[i])
22
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
23
+ if (kind && result)
24
+ __defProp(target, key, result);
25
+ return result;
26
+ };
27
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+ var interceptors_exports = {};
29
+ __export(interceptors_exports, {
30
+ CacheInterceptor: () => CacheInterceptor,
31
+ LoggingInterceptor: () => LoggingInterceptor,
32
+ TimeoutInterceptor: () => TimeoutInterceptor
33
+ });
34
+ module.exports = __toCommonJS(interceptors_exports);
35
+ var import_common = require("@akanjs/common");
36
+ var import_signal = require("@akanjs/signal");
37
+ var import_common2 = require("@nestjs/common");
38
+ var import_graphql = require("@nestjs/graphql");
39
+ var import_rxjs = require("rxjs");
40
+ var import_operators = require("rxjs/operators");
41
+ var import_authGuards = require("./authGuards");
42
+ let CacheInterceptor = class {
43
+ constructor(redis) {
44
+ this.redis = redis;
45
+ }
46
+ logger = new import_common.Logger("CacheInterceptor");
47
+ async setCache(key, value, expire) {
48
+ await this.redis.set(key, JSON.stringify(value), { PX: expire });
49
+ }
50
+ async getCache(key) {
51
+ const cached = await this.redis.get(key);
52
+ return cached ? JSON.parse(cached) : null;
53
+ }
54
+ intercept(context, next) {
55
+ const signalKey = context.getHandler().name;
56
+ const gqlMeta = (0, import_signal.getGqlMeta)(context.getClass(), signalKey);
57
+ const cacheExpireMs = gqlMeta.signalOption.cache;
58
+ if (gqlMeta.type !== "Query" || !cacheExpireMs) {
59
+ if (cacheExpireMs)
60
+ this.logger.warn(`CacheInterceptor: ${signalKey} is not Query endpoint or cache is not set`);
61
+ return next.handle();
62
+ }
63
+ const args = (0, import_authGuards.getArgs)(context);
64
+ const cacheKey = `signal:${signalKey}:${JSON.stringify(args)}`;
65
+ const cacheResult$ = (0, import_rxjs.from)(this.getCache(cacheKey));
66
+ return (0, import_rxjs.forkJoin)([cacheResult$]).pipe(
67
+ (0, import_rxjs.switchMap)(([cacheResult]) => {
68
+ if (cacheResult) {
69
+ this.logger.trace(`CacheHit-${cacheKey}`);
70
+ return (0, import_rxjs.of)(cacheResult);
71
+ } else
72
+ return next.handle().pipe(
73
+ (0, import_rxjs.map)((resData) => {
74
+ void this.setCache(cacheKey, resData, cacheExpireMs);
75
+ this.logger.trace(`CacheSet-${cacheKey}`);
76
+ return resData;
77
+ })
78
+ );
79
+ })
80
+ );
81
+ }
82
+ };
83
+ CacheInterceptor = __decorateClass([
84
+ (0, import_common2.Injectable)(),
85
+ __decorateParam(0, (0, import_common2.Inject)("REDIS_CLIENT"))
86
+ ], CacheInterceptor);
87
+ let TimeoutInterceptor = class {
88
+ intercept(context, next) {
89
+ const gqlMeta = (0, import_signal.getGqlMeta)(context.getClass(), context.getHandler().name);
90
+ const timeoutMs = gqlMeta.signalOption.timeout ?? 3e4;
91
+ if (timeoutMs === 0)
92
+ return next.handle();
93
+ return next.handle().pipe(
94
+ (0, import_operators.timeout)(timeoutMs),
95
+ (0, import_operators.catchError)((err) => {
96
+ if (err instanceof import_rxjs.TimeoutError)
97
+ return (0, import_rxjs.throwError)(() => new import_common2.RequestTimeoutException());
98
+ return (0, import_rxjs.throwError)(() => err);
99
+ })
100
+ );
101
+ }
102
+ };
103
+ TimeoutInterceptor = __decorateClass([
104
+ (0, import_common2.Injectable)()
105
+ ], TimeoutInterceptor);
106
+ let LoggingInterceptor = class {
107
+ logger = new import_common.Logger("IO");
108
+ intercept(context, next) {
109
+ const gqlReq = context.getArgByIndex(3);
110
+ const req = (0, import_authGuards.getRequest)(context);
111
+ const reqType = gqlReq?.parentType?.name ?? req.method;
112
+ const reqName = gqlReq?.fieldName ?? req.url;
113
+ const before = Date.now();
114
+ const ip = import_graphql.GqlExecutionContext.create(context).getContext().req.ip;
115
+ this.logger.debug(`Before ${reqType}-${reqName} / ${ip} / ${before}`);
116
+ return next.handle().pipe(
117
+ (0, import_operators.tap)(() => {
118
+ const after = Date.now();
119
+ this.logger.debug(`After ${reqType}-${reqName} / ${ip} / ${after} (${after - before}ms)`);
120
+ })
121
+ );
122
+ }
123
+ };
124
+ LoggingInterceptor = __decorateClass([
125
+ (0, import_common2.Injectable)()
126
+ ], LoggingInterceptor);
127
+ // Annotate the CommonJS export names for ESM import in node:
128
+ 0 && (module.exports = {
129
+ CacheInterceptor,
130
+ LoggingInterceptor,
131
+ TimeoutInterceptor
132
+ });
@@ -0,0 +1,5 @@
1
+ export declare const initMongoDB: ({ logging, threshold, sendReport, }: {
2
+ logging: boolean;
3
+ threshold?: number;
4
+ sendReport?: boolean;
5
+ }) => void;