@akanjs/nest 0.0.46 → 0.0.47
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/index.js +2 -1268
- package/package.json +1 -1
- package/src/authGuards.js +146 -0
- package/src/authentication.js +111 -0
- package/src/authorization.js +74 -0
- package/src/cacheClient.js +41 -0
- package/src/databaseClient.js +47 -0
- package/src/decorators.js +163 -0
- package/src/exceptions.js +74 -0
- package/src/exporter.js +105 -0
- package/src/generateSecrets.js +128 -0
- package/src/index.js +52 -0
- package/src/interceptors.js +182 -0
- package/src/mongoose.js +89 -0
- package/src/pipes.js +135 -0
- package/src/redis-io.adapter.js +80 -0
- package/src/searchClient.js +63 -0
- package/src/sso.js +182 -0
- package/src/verifyPayment.js +46 -0
package/index.js
CHANGED
|
@@ -1,13 +1,7 @@
|
|
|
1
|
-
var __create = Object.create;
|
|
2
1
|
var __defProp = Object.defineProperty;
|
|
3
2
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
3
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
6
4
|
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
5
|
var __copyProps = (to, from, except, desc) => {
|
|
12
6
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
7
|
for (let key of __getOwnPropNames(from))
|
|
@@ -16,1268 +10,8 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
10
|
}
|
|
17
11
|
return to;
|
|
18
12
|
};
|
|
19
|
-
var
|
|
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
|
-
));
|
|
13
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
27
14
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
28
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
29
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
30
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
31
|
-
if (decorator = decorators[i])
|
|
32
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
33
|
-
if (kind && result)
|
|
34
|
-
__defProp(target, key, result);
|
|
35
|
-
return result;
|
|
36
|
-
};
|
|
37
|
-
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
38
|
-
var __accessCheck = (obj, member, msg) => {
|
|
39
|
-
if (!member.has(obj))
|
|
40
|
-
throw TypeError("Cannot " + msg);
|
|
41
|
-
};
|
|
42
|
-
var __privateGet = (obj, member, getter) => {
|
|
43
|
-
__accessCheck(obj, member, "read from private field");
|
|
44
|
-
return getter ? getter.call(obj) : member.get(obj);
|
|
45
|
-
};
|
|
46
|
-
var __privateAdd = (obj, member, value) => {
|
|
47
|
-
if (member.has(obj))
|
|
48
|
-
throw TypeError("Cannot add the same private member more than once");
|
|
49
|
-
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
50
|
-
};
|
|
51
|
-
var __privateMethod = (obj, member, method) => {
|
|
52
|
-
__accessCheck(obj, member, "access private method");
|
|
53
|
-
return method;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
// pkgs/@akanjs/nest/index.ts
|
|
57
15
|
var nest_exports = {};
|
|
58
|
-
__export(nest_exports, {
|
|
59
|
-
Access: () => Access,
|
|
60
|
-
Account: () => Account2,
|
|
61
|
-
Admin: () => Admin,
|
|
62
|
-
AllExceptionsFilter: () => AllExceptionsFilter,
|
|
63
|
-
ArrayifyPipe: () => ArrayifyPipe,
|
|
64
|
-
BooleanPipe: () => BooleanPipe,
|
|
65
|
-
Cache: () => Cache,
|
|
66
|
-
CacheClient: () => CacheClient,
|
|
67
|
-
CacheInterceptor: () => CacheInterceptor,
|
|
68
|
-
Cron: () => Cron,
|
|
69
|
-
DatabaseClient: () => DatabaseClient,
|
|
70
|
-
DayjsPipe: () => DayjsPipe,
|
|
71
|
-
Every: () => Every,
|
|
72
|
-
Exporter: () => exporter_exports,
|
|
73
|
-
FileSystem: () => FileSystem,
|
|
74
|
-
FloatPipe: () => FloatPipe,
|
|
75
|
-
IntPipe: () => IntPipe,
|
|
76
|
-
Interval: () => Interval,
|
|
77
|
-
JSONPipe: () => JSONPipe,
|
|
78
|
-
LoggingInterceptor: () => LoggingInterceptor,
|
|
79
|
-
Me: () => Me,
|
|
80
|
-
MulterToUploadPipe: () => MulterToUploadPipe,
|
|
81
|
-
None: () => None,
|
|
82
|
-
Owner: () => Owner,
|
|
83
|
-
Public: () => Public,
|
|
84
|
-
RedisIoAdapter: () => RedisIoAdapter,
|
|
85
|
-
Req: () => Req,
|
|
86
|
-
Res: () => Res,
|
|
87
|
-
SALT_ROUNDS: () => SALT_ROUNDS,
|
|
88
|
-
SearchClient: () => SearchClient,
|
|
89
|
-
Self: () => Self,
|
|
90
|
-
SuperAdmin: () => SuperAdmin,
|
|
91
|
-
TimeoutInterceptor: () => TimeoutInterceptor,
|
|
92
|
-
Transaction: () => Transaction,
|
|
93
|
-
Try: () => Try,
|
|
94
|
-
User: () => User,
|
|
95
|
-
UserIp: () => UserIp,
|
|
96
|
-
Ws: () => Ws,
|
|
97
|
-
allow: () => allow,
|
|
98
|
-
exportToCsv: () => exportToCsv,
|
|
99
|
-
exportToJson: () => exportToJson,
|
|
100
|
-
generateAeskey: () => generateAeskey,
|
|
101
|
-
generateHost: () => generateHost,
|
|
102
|
-
generateJwtSecret: () => generateJwtSecret,
|
|
103
|
-
generateMeiliKey: () => generateMeiliKey,
|
|
104
|
-
generateMeiliUri: () => generateMeiliUri,
|
|
105
|
-
generateMongoUri: () => generateMongoUri,
|
|
106
|
-
generateRedisUri: () => generateRedisUri,
|
|
107
|
-
getArgs: () => getArgs,
|
|
108
|
-
getBodyPipes: () => getBodyPipes,
|
|
109
|
-
getQueryPipes: () => getQueryPipes,
|
|
110
|
-
getRequest: () => getRequest,
|
|
111
|
-
getResponse: () => getResponse,
|
|
112
|
-
getSocket: () => getSocket,
|
|
113
|
-
getSsoProviders: () => getSsoProviders,
|
|
114
|
-
guards: () => authGuards_exports,
|
|
115
|
-
initMongoDB: () => initMongoDB,
|
|
116
|
-
objPath: () => objPath,
|
|
117
|
-
readJson: () => readJson,
|
|
118
|
-
verifyAppleUser: () => verifyAppleUser,
|
|
119
|
-
verifyPayment: () => verifyPayment,
|
|
120
|
-
verifyToken: () => verifyToken
|
|
121
|
-
});
|
|
122
16
|
module.exports = __toCommonJS(nest_exports);
|
|
123
|
-
|
|
124
|
-
// pkgs/@akanjs/nest/src/authorization.ts
|
|
125
|
-
var import_base = require("@akanjs/base");
|
|
126
|
-
var import_signal = require("@akanjs/signal");
|
|
127
|
-
var import_apollo = require("@nestjs/apollo");
|
|
128
|
-
var jwt = __toESM(require("jsonwebtoken"));
|
|
129
|
-
var verifyToken = (secret, authorization) => {
|
|
130
|
-
const [type, token] = authorization?.split(" ") ?? [void 0, void 0];
|
|
131
|
-
if (!token || type !== "Bearer")
|
|
132
|
-
return import_signal.defaultAccount;
|
|
133
|
-
try {
|
|
134
|
-
const account = jwt.verify(token, secret);
|
|
135
|
-
if (account.appName !== import_base.baseEnv.appName || account.environment !== import_base.baseEnv.environment)
|
|
136
|
-
return import_signal.defaultAccount;
|
|
137
|
-
return {
|
|
138
|
-
__InternalArg__: "Account",
|
|
139
|
-
self: account.self && !account.self.removedAt ? account.self : void 0,
|
|
140
|
-
me: account.me && !account.me.removedAt ? account.me : void 0,
|
|
141
|
-
appName: account.appName,
|
|
142
|
-
environment: account.environment
|
|
143
|
-
};
|
|
144
|
-
} catch (e) {
|
|
145
|
-
return import_signal.defaultAccount;
|
|
146
|
-
}
|
|
147
|
-
};
|
|
148
|
-
var allow = (account, roles, userId) => {
|
|
149
|
-
if (!account)
|
|
150
|
-
throw new import_apollo.AuthenticationError("No Authentication Account");
|
|
151
|
-
for (const role of roles) {
|
|
152
|
-
if (role === "user" && account.self?.roles.includes("user"))
|
|
153
|
-
return true;
|
|
154
|
-
else if (role === "admin" && account.me?.roles.includes("admin"))
|
|
155
|
-
return true;
|
|
156
|
-
else if (role === "superAdmin" && account.me?.roles.includes("superAdmin"))
|
|
157
|
-
return true;
|
|
158
|
-
}
|
|
159
|
-
throw new import_apollo.AuthenticationError(
|
|
160
|
-
`No Authentication With Roles: ${roles.join(", ")}, Your roles are ${[
|
|
161
|
-
...account.self?.roles ?? [],
|
|
162
|
-
...account.me?.roles ?? []
|
|
163
|
-
].join(", ")}${!account.self?.roles.length && !account.me?.roles.length ? " (No Roles)" : ""}`
|
|
164
|
-
);
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
// pkgs/@akanjs/nest/src/authGuards.ts
|
|
168
|
-
var authGuards_exports = {};
|
|
169
|
-
__export(authGuards_exports, {
|
|
170
|
-
Admin: () => Admin,
|
|
171
|
-
Every: () => Every,
|
|
172
|
-
None: () => None,
|
|
173
|
-
Owner: () => Owner,
|
|
174
|
-
Public: () => Public,
|
|
175
|
-
SuperAdmin: () => SuperAdmin,
|
|
176
|
-
User: () => User,
|
|
177
|
-
getArgs: () => getArgs,
|
|
178
|
-
getRequest: () => getRequest,
|
|
179
|
-
getResponse: () => getResponse,
|
|
180
|
-
getSocket: () => getSocket
|
|
181
|
-
});
|
|
182
|
-
var import_common = require("@nestjs/common");
|
|
183
|
-
var import_graphql = require("@nestjs/graphql");
|
|
184
|
-
var getRequest = (context) => {
|
|
185
|
-
const type = context.getType();
|
|
186
|
-
if (type === "ws")
|
|
187
|
-
throw new Error("Getting Request in Websocket is not allowed");
|
|
188
|
-
return type === "http" ? context.switchToHttp().getRequest() : import_graphql.GqlExecutionContext.create(context).getContext().req;
|
|
189
|
-
};
|
|
190
|
-
var getResponse = (context) => {
|
|
191
|
-
const type = context.getType();
|
|
192
|
-
if (type === "ws")
|
|
193
|
-
throw new Error("Getting Response in Websocket is not allowed");
|
|
194
|
-
return type === "http" ? context.switchToHttp().getResponse() : import_graphql.GqlExecutionContext.create(context).getContext().req.res;
|
|
195
|
-
};
|
|
196
|
-
var getArgs = (context) => {
|
|
197
|
-
const type = context.getType();
|
|
198
|
-
if (type === "ws")
|
|
199
|
-
throw new Error("Getting Args in Websocket is not allowed");
|
|
200
|
-
if (type === "graphql")
|
|
201
|
-
return import_graphql.GqlExecutionContext.create(context).getArgs();
|
|
202
|
-
else if (type === "http") {
|
|
203
|
-
const { params, query, body } = context.switchToHttp().getRequest();
|
|
204
|
-
return { ...params, ...query, ...body };
|
|
205
|
-
} else
|
|
206
|
-
throw new Error("Getting Args in Unknown context is not allowed");
|
|
207
|
-
};
|
|
208
|
-
var getSocket = (context) => {
|
|
209
|
-
const type = context.getType();
|
|
210
|
-
if (type !== "ws")
|
|
211
|
-
throw new Error("Getting Socket in Http or GraphQL is not allowed");
|
|
212
|
-
const socket = context.getArgByIndex(0);
|
|
213
|
-
return socket;
|
|
214
|
-
};
|
|
215
|
-
var Public = class {
|
|
216
|
-
canActivate(context) {
|
|
217
|
-
return true;
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
Public = __decorateClass([
|
|
221
|
-
(0, import_common.Injectable)()
|
|
222
|
-
], Public);
|
|
223
|
-
var None = class {
|
|
224
|
-
canActivate() {
|
|
225
|
-
return false;
|
|
226
|
-
}
|
|
227
|
-
};
|
|
228
|
-
None = __decorateClass([
|
|
229
|
-
(0, import_common.Injectable)()
|
|
230
|
-
], None);
|
|
231
|
-
var Every = class {
|
|
232
|
-
canActivate(context) {
|
|
233
|
-
const { account } = getRequest(context);
|
|
234
|
-
return allow(account, ["user", "admin", "superAdmin"]);
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
Every = __decorateClass([
|
|
238
|
-
(0, import_common.Injectable)()
|
|
239
|
-
], Every);
|
|
240
|
-
var Owner = class {
|
|
241
|
-
canActivate(context) {
|
|
242
|
-
const { account } = getRequest(context);
|
|
243
|
-
return allow(account, ["user", "admin", "superAdmin"]);
|
|
244
|
-
}
|
|
245
|
-
};
|
|
246
|
-
Owner = __decorateClass([
|
|
247
|
-
(0, import_common.Injectable)()
|
|
248
|
-
], Owner);
|
|
249
|
-
var Admin = class {
|
|
250
|
-
canActivate(context) {
|
|
251
|
-
const { account } = getRequest(context);
|
|
252
|
-
return allow(account, ["admin", "superAdmin"]);
|
|
253
|
-
}
|
|
254
|
-
};
|
|
255
|
-
Admin = __decorateClass([
|
|
256
|
-
(0, import_common.Injectable)()
|
|
257
|
-
], Admin);
|
|
258
|
-
var SuperAdmin = class {
|
|
259
|
-
canActivate(context) {
|
|
260
|
-
const { account } = getRequest(context);
|
|
261
|
-
return allow(account, ["superAdmin"]);
|
|
262
|
-
}
|
|
263
|
-
};
|
|
264
|
-
SuperAdmin = __decorateClass([
|
|
265
|
-
(0, import_common.Injectable)()
|
|
266
|
-
], SuperAdmin);
|
|
267
|
-
var User = class {
|
|
268
|
-
canActivate(context) {
|
|
269
|
-
const { account } = getRequest(context);
|
|
270
|
-
return allow(account, ["user"]);
|
|
271
|
-
}
|
|
272
|
-
};
|
|
273
|
-
User = __decorateClass([
|
|
274
|
-
(0, import_common.Injectable)()
|
|
275
|
-
], User);
|
|
276
|
-
|
|
277
|
-
// pkgs/@akanjs/nest/src/authentication.ts
|
|
278
|
-
var import_base2 = require("@akanjs/base");
|
|
279
|
-
var import_common2 = require("@nestjs/common");
|
|
280
|
-
var import_ua_parser_js = __toESM(require("ua-parser-js"));
|
|
281
|
-
var Account2 = (0, import_common2.createParamDecorator)((option, context) => {
|
|
282
|
-
const { account } = getRequest(context);
|
|
283
|
-
return account;
|
|
284
|
-
});
|
|
285
|
-
var Self = (0, import_common2.createParamDecorator)((option, context) => {
|
|
286
|
-
const { account } = getRequest(context);
|
|
287
|
-
const self = account.self;
|
|
288
|
-
if (!self && !option.nullable)
|
|
289
|
-
throw new import_common2.UnauthorizedException("No or Invalid Account in Self (User)");
|
|
290
|
-
return self;
|
|
291
|
-
});
|
|
292
|
-
var Me = (0, import_common2.createParamDecorator)((option, context) => {
|
|
293
|
-
const { account } = getRequest(context);
|
|
294
|
-
const me = account.me;
|
|
295
|
-
if (!me && !option.nullable)
|
|
296
|
-
throw new import_common2.UnauthorizedException("No or Invalid Account in Me (Admin)");
|
|
297
|
-
return me;
|
|
298
|
-
});
|
|
299
|
-
var UserIp = (0, import_common2.createParamDecorator)((option, context) => {
|
|
300
|
-
const req = getRequest(context);
|
|
301
|
-
const ip = req.ip;
|
|
302
|
-
if (!ip && !option.nullable)
|
|
303
|
-
throw new import_common2.UnauthorizedException("Invalid IP");
|
|
304
|
-
return { ip };
|
|
305
|
-
});
|
|
306
|
-
var Access = (0, import_common2.createParamDecorator)((option, context) => {
|
|
307
|
-
const req = getRequest(context);
|
|
308
|
-
const res = new import_ua_parser_js.default(req.userAgent).getResult();
|
|
309
|
-
if (!req.userAgent && !option.nullable)
|
|
310
|
-
throw new import_common2.UnauthorizedException("Invalid UserAgent");
|
|
311
|
-
return {
|
|
312
|
-
...req.geolocation ? JSON.parse(req.geolocation) : {},
|
|
313
|
-
osName: res.os.name,
|
|
314
|
-
osVersion: res.os.version,
|
|
315
|
-
browserName: res.browser.name,
|
|
316
|
-
browserVersion: res.browser.version,
|
|
317
|
-
mobileModel: res.device.model,
|
|
318
|
-
mobileVendor: res.device.vendor,
|
|
319
|
-
deviceType: res.device.type ?? "desktop",
|
|
320
|
-
at: (0, import_base2.dayjs)(),
|
|
321
|
-
period: 0
|
|
322
|
-
};
|
|
323
|
-
});
|
|
324
|
-
var Req = (0, import_common2.createParamDecorator)((option, context) => {
|
|
325
|
-
return getRequest(context);
|
|
326
|
-
});
|
|
327
|
-
var Res = (0, import_common2.createParamDecorator)((option, context) => {
|
|
328
|
-
return getResponse(context);
|
|
329
|
-
});
|
|
330
|
-
var Ws = (0, import_common2.createParamDecorator)((option, context) => {
|
|
331
|
-
const socket = context.getArgByIndex(0);
|
|
332
|
-
const { __subscribe__ } = context.getArgByIndex(1);
|
|
333
|
-
return {
|
|
334
|
-
socket,
|
|
335
|
-
subscribe: __subscribe__,
|
|
336
|
-
onDisconnect: (handler) => {
|
|
337
|
-
socket.on("disconnect", handler);
|
|
338
|
-
},
|
|
339
|
-
onSubscribe: (handler) => {
|
|
340
|
-
if (__subscribe__)
|
|
341
|
-
handler();
|
|
342
|
-
},
|
|
343
|
-
onUnsubscribe: (handler) => {
|
|
344
|
-
if (!__subscribe__)
|
|
345
|
-
handler();
|
|
346
|
-
}
|
|
347
|
-
};
|
|
348
|
-
});
|
|
349
|
-
|
|
350
|
-
// pkgs/@akanjs/nest/src/interceptors.ts
|
|
351
|
-
var import_common3 = require("@akanjs/common");
|
|
352
|
-
var import_signal2 = require("@akanjs/signal");
|
|
353
|
-
var import_common4 = require("@nestjs/common");
|
|
354
|
-
var import_graphql2 = require("@nestjs/graphql");
|
|
355
|
-
var import_rxjs = require("rxjs");
|
|
356
|
-
var import_operators = require("rxjs/operators");
|
|
357
|
-
var _logger, _CACHE_PREFIX, _generateCacheKey, generateCacheKey_fn, _getCache, getCache_fn, _setCache, setCache_fn;
|
|
358
|
-
var CacheInterceptor = class {
|
|
359
|
-
constructor(redis) {
|
|
360
|
-
this.redis = redis;
|
|
361
|
-
__privateAdd(this, _generateCacheKey);
|
|
362
|
-
__privateAdd(this, _getCache);
|
|
363
|
-
__privateAdd(this, _setCache);
|
|
364
|
-
__privateAdd(this, _logger, new import_common3.Logger("CacheInterceptor"));
|
|
365
|
-
__privateAdd(this, _CACHE_PREFIX, "signal:");
|
|
366
|
-
}
|
|
367
|
-
async intercept(context, next) {
|
|
368
|
-
const handler = context.getHandler();
|
|
369
|
-
const signalKey = handler.name;
|
|
370
|
-
const gqlMeta = (0, import_signal2.getGqlMeta)(context.getClass(), signalKey);
|
|
371
|
-
if (gqlMeta.type !== "Query" || !gqlMeta.signalOption.cache) {
|
|
372
|
-
if (gqlMeta.signalOption.cache)
|
|
373
|
-
__privateGet(this, _logger).warn(`CacheInterceptor: ${signalKey} is not Query endpoint or cache is not set`);
|
|
374
|
-
return next.handle();
|
|
375
|
-
}
|
|
376
|
-
const args = getArgs(context);
|
|
377
|
-
const cacheKey = __privateMethod(this, _generateCacheKey, generateCacheKey_fn).call(this, signalKey, args);
|
|
378
|
-
const cachedData = await __privateMethod(this, _getCache, getCache_fn).call(this, cacheKey);
|
|
379
|
-
if (cachedData) {
|
|
380
|
-
__privateGet(this, _logger).debug(`Cache hit for key: ${cacheKey}`);
|
|
381
|
-
return next.handle().pipe(
|
|
382
|
-
(0, import_operators.map)(() => cachedData),
|
|
383
|
-
(0, import_operators.catchError)((error) => {
|
|
384
|
-
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
385
|
-
__privateGet(this, _logger).error(`Error in cache interceptor for ${cacheKey}: ${errorMessage}`);
|
|
386
|
-
return (0, import_rxjs.throwError)(() => error);
|
|
387
|
-
})
|
|
388
|
-
);
|
|
389
|
-
}
|
|
390
|
-
return next.handle().pipe(
|
|
391
|
-
(0, import_operators.map)((data) => {
|
|
392
|
-
const cacheDuration = gqlMeta.signalOption.cache;
|
|
393
|
-
if (typeof cacheDuration === "number") {
|
|
394
|
-
void __privateMethod(this, _setCache, setCache_fn).call(this, cacheKey, data, cacheDuration);
|
|
395
|
-
__privateGet(this, _logger).debug(`Cache set for key: ${cacheKey}`);
|
|
396
|
-
}
|
|
397
|
-
return data;
|
|
398
|
-
}),
|
|
399
|
-
(0, import_operators.catchError)((error) => {
|
|
400
|
-
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
401
|
-
__privateGet(this, _logger).error(`Error in cache interceptor for ${cacheKey}: ${errorMessage}`);
|
|
402
|
-
return (0, import_rxjs.throwError)(() => error);
|
|
403
|
-
})
|
|
404
|
-
);
|
|
405
|
-
}
|
|
406
|
-
};
|
|
407
|
-
_logger = new WeakMap();
|
|
408
|
-
_CACHE_PREFIX = new WeakMap();
|
|
409
|
-
_generateCacheKey = new WeakSet();
|
|
410
|
-
generateCacheKey_fn = function(signalKey, args) {
|
|
411
|
-
return `${__privateGet(this, _CACHE_PREFIX)}${signalKey}:${JSON.stringify(args)}`;
|
|
412
|
-
};
|
|
413
|
-
_getCache = new WeakSet();
|
|
414
|
-
getCache_fn = async function(key) {
|
|
415
|
-
try {
|
|
416
|
-
const cached = await this.redis.get(key);
|
|
417
|
-
if (!cached)
|
|
418
|
-
return null;
|
|
419
|
-
const { data } = JSON.parse(cached);
|
|
420
|
-
return data;
|
|
421
|
-
} catch (error) {
|
|
422
|
-
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
423
|
-
__privateGet(this, _logger).error(`Error retrieving cache for key ${key}: ${errorMessage}`);
|
|
424
|
-
return null;
|
|
425
|
-
}
|
|
426
|
-
};
|
|
427
|
-
_setCache = new WeakSet();
|
|
428
|
-
setCache_fn = async function(key, data, ttlMs) {
|
|
429
|
-
try {
|
|
430
|
-
const cacheData = { data, timestamp: Date.now() };
|
|
431
|
-
await this.redis.set(key, JSON.stringify(cacheData), { PX: ttlMs });
|
|
432
|
-
} catch (error) {
|
|
433
|
-
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
434
|
-
__privateGet(this, _logger).error(`Error setting cache for key ${key}: ${errorMessage}`);
|
|
435
|
-
}
|
|
436
|
-
};
|
|
437
|
-
CacheInterceptor = __decorateClass([
|
|
438
|
-
(0, import_common4.Injectable)(),
|
|
439
|
-
__decorateParam(0, (0, import_common4.Inject)("REDIS_CLIENT"))
|
|
440
|
-
], CacheInterceptor);
|
|
441
|
-
var TimeoutInterceptor = class {
|
|
442
|
-
intercept(context, next) {
|
|
443
|
-
const gqlMeta = (0, import_signal2.getGqlMeta)(context.getClass(), context.getHandler().name);
|
|
444
|
-
const timeoutMs = gqlMeta.signalOption.timeout ?? 3e4;
|
|
445
|
-
if (timeoutMs === 0)
|
|
446
|
-
return next.handle();
|
|
447
|
-
return next.handle().pipe(
|
|
448
|
-
(0, import_operators.timeout)(timeoutMs),
|
|
449
|
-
(0, import_operators.catchError)((err) => {
|
|
450
|
-
if (err instanceof import_rxjs.TimeoutError)
|
|
451
|
-
return (0, import_rxjs.throwError)(() => new import_common4.RequestTimeoutException());
|
|
452
|
-
return (0, import_rxjs.throwError)(() => err);
|
|
453
|
-
})
|
|
454
|
-
);
|
|
455
|
-
}
|
|
456
|
-
};
|
|
457
|
-
TimeoutInterceptor = __decorateClass([
|
|
458
|
-
(0, import_common4.Injectable)()
|
|
459
|
-
], TimeoutInterceptor);
|
|
460
|
-
var LoggingInterceptor = class {
|
|
461
|
-
logger = new import_common3.Logger("IO");
|
|
462
|
-
intercept(context, next) {
|
|
463
|
-
const gqlReq = context.getArgByIndex(3);
|
|
464
|
-
const req = getRequest(context);
|
|
465
|
-
const reqType = gqlReq?.parentType?.name ?? req.method;
|
|
466
|
-
const reqName = gqlReq?.fieldName ?? req.url;
|
|
467
|
-
const before = Date.now();
|
|
468
|
-
const ip = import_graphql2.GqlExecutionContext.create(context).getContext().req.ip;
|
|
469
|
-
this.logger.debug(`Before ${reqType}-${reqName} / ${ip} / ${before}`);
|
|
470
|
-
return next.handle().pipe(
|
|
471
|
-
(0, import_operators.tap)(() => {
|
|
472
|
-
const after = Date.now();
|
|
473
|
-
this.logger.debug(`After ${reqType}-${reqName} / ${ip} / ${after} (${after - before}ms)`);
|
|
474
|
-
})
|
|
475
|
-
);
|
|
476
|
-
}
|
|
477
|
-
};
|
|
478
|
-
LoggingInterceptor = __decorateClass([
|
|
479
|
-
(0, import_common4.Injectable)()
|
|
480
|
-
], LoggingInterceptor);
|
|
481
|
-
|
|
482
|
-
// pkgs/@akanjs/nest/src/redis-io.adapter.ts
|
|
483
|
-
var import_common5 = require("@akanjs/common");
|
|
484
|
-
var import_platform_socket = require("@nestjs/platform-socket.io");
|
|
485
|
-
var import_redis_adapter = require("@socket.io/redis-adapter");
|
|
486
|
-
var import_redis = require("redis");
|
|
487
|
-
var RedisIoAdapter = class extends import_platform_socket.IoAdapter {
|
|
488
|
-
adapterConstructor;
|
|
489
|
-
logger = new import_common5.Logger("RedisIoAdapter");
|
|
490
|
-
server;
|
|
491
|
-
pubClient;
|
|
492
|
-
subClient;
|
|
493
|
-
option;
|
|
494
|
-
constructor(appOrHttpServer, option) {
|
|
495
|
-
super(appOrHttpServer);
|
|
496
|
-
this.option = option;
|
|
497
|
-
}
|
|
498
|
-
async connectToRedis(url) {
|
|
499
|
-
this.pubClient = (0, import_redis.createClient)({ url });
|
|
500
|
-
this.subClient = this.pubClient.duplicate();
|
|
501
|
-
this.pubClient.on("disconnect", (err) => {
|
|
502
|
-
this.logger.error(`Redis pub database is disconnected. Error: ${err}`);
|
|
503
|
-
void this.pubClient.connect();
|
|
504
|
-
});
|
|
505
|
-
this.subClient.on("disconnect", (err) => {
|
|
506
|
-
this.logger.error(`Redis sub database is disconnected. Error: ${err}`);
|
|
507
|
-
void this.subClient.connect();
|
|
508
|
-
});
|
|
509
|
-
this.pubClient.on("error", (err) => {
|
|
510
|
-
this.logger.error(`Redis pub database is errored. Error: ${err}`);
|
|
511
|
-
const reconnect = async () => {
|
|
512
|
-
await this.pubClient.quit();
|
|
513
|
-
await (0, import_common5.sleep)(1e3);
|
|
514
|
-
await this.pubClient.connect();
|
|
515
|
-
};
|
|
516
|
-
void reconnect();
|
|
517
|
-
});
|
|
518
|
-
this.subClient.on("error", (err) => {
|
|
519
|
-
this.logger.error(`Redis sub database is errored. Error: ${err}`);
|
|
520
|
-
const reconnect = async () => {
|
|
521
|
-
await this.subClient.quit();
|
|
522
|
-
await (0, import_common5.sleep)(1e3);
|
|
523
|
-
await this.subClient.connect();
|
|
524
|
-
};
|
|
525
|
-
void reconnect();
|
|
526
|
-
});
|
|
527
|
-
await Promise.all([this.pubClient.connect(), this.subClient.connect()]);
|
|
528
|
-
this.adapterConstructor = (0, import_redis_adapter.createAdapter)(this.pubClient, this.subClient);
|
|
529
|
-
}
|
|
530
|
-
createIOServer(port, options) {
|
|
531
|
-
this.server = super.createIOServer(port, options);
|
|
532
|
-
this.server.adapter(this.adapterConstructor);
|
|
533
|
-
return this.server;
|
|
534
|
-
}
|
|
535
|
-
async destroy() {
|
|
536
|
-
await Promise.all([this.pubClient.quit(), this.subClient.quit()]);
|
|
537
|
-
await this.close(this.server);
|
|
538
|
-
this.logger.log("RedisIoAdapter is closed");
|
|
539
|
-
}
|
|
540
|
-
};
|
|
541
|
-
|
|
542
|
-
// pkgs/@akanjs/nest/src/pipes.ts
|
|
543
|
-
var import_base3 = require("@akanjs/base");
|
|
544
|
-
var import_signal3 = require("@akanjs/signal");
|
|
545
|
-
var import_common6 = require("@nestjs/common");
|
|
546
|
-
var import_stream = require("stream");
|
|
547
|
-
var ArrayifyPipe = class {
|
|
548
|
-
transform(value, metadata) {
|
|
549
|
-
return Array.isArray(value) ? value : value.split(",");
|
|
550
|
-
}
|
|
551
|
-
};
|
|
552
|
-
ArrayifyPipe = __decorateClass([
|
|
553
|
-
(0, import_common6.Injectable)()
|
|
554
|
-
], ArrayifyPipe);
|
|
555
|
-
var IntPipe = class {
|
|
556
|
-
transform(value, metadata) {
|
|
557
|
-
return Array.isArray(value) ? value.map(parseInt) : [parseInt(value)];
|
|
558
|
-
}
|
|
559
|
-
};
|
|
560
|
-
IntPipe = __decorateClass([
|
|
561
|
-
(0, import_common6.Injectable)()
|
|
562
|
-
], IntPipe);
|
|
563
|
-
var FloatPipe = class {
|
|
564
|
-
transform(value, metadata) {
|
|
565
|
-
return Array.isArray(value) ? value.map(parseFloat) : [parseFloat(value)];
|
|
566
|
-
}
|
|
567
|
-
};
|
|
568
|
-
FloatPipe = __decorateClass([
|
|
569
|
-
(0, import_common6.Injectable)()
|
|
570
|
-
], FloatPipe);
|
|
571
|
-
var BooleanPipe = class {
|
|
572
|
-
transform(value, metadata) {
|
|
573
|
-
return Array.isArray(value) ? value.map((v) => Boolean(v)) : [Boolean(value)];
|
|
574
|
-
}
|
|
575
|
-
};
|
|
576
|
-
BooleanPipe = __decorateClass([
|
|
577
|
-
(0, import_common6.Injectable)()
|
|
578
|
-
], BooleanPipe);
|
|
579
|
-
var DayjsPipe = class {
|
|
580
|
-
transform(value, metadata) {
|
|
581
|
-
return Array.isArray(value) ? value.map(import_base3.dayjs) : [(0, import_base3.dayjs)(value)];
|
|
582
|
-
}
|
|
583
|
-
};
|
|
584
|
-
DayjsPipe = __decorateClass([
|
|
585
|
-
(0, import_common6.Injectable)()
|
|
586
|
-
], DayjsPipe);
|
|
587
|
-
var JSONPipe = class {
|
|
588
|
-
transform(value, metadata) {
|
|
589
|
-
const transformable = typeof value === "string" && value.length;
|
|
590
|
-
const obj = transformable ? JSON.parse(atob(value)) : value;
|
|
591
|
-
return obj;
|
|
592
|
-
}
|
|
593
|
-
};
|
|
594
|
-
JSONPipe = __decorateClass([
|
|
595
|
-
(0, import_common6.Injectable)()
|
|
596
|
-
], JSONPipe);
|
|
597
|
-
var convertToFileStream = (value) => ({
|
|
598
|
-
filename: value.originalname,
|
|
599
|
-
mimetype: value.mimetype,
|
|
600
|
-
encoding: value.encoding,
|
|
601
|
-
createReadStream: () => import_stream.Readable.from(value.buffer)
|
|
602
|
-
});
|
|
603
|
-
var MulterToUploadPipe = class {
|
|
604
|
-
transform(value, metadata) {
|
|
605
|
-
return Array.isArray(value) ? value.map(convertToFileStream) : convertToFileStream(value);
|
|
606
|
-
}
|
|
607
|
-
};
|
|
608
|
-
MulterToUploadPipe = __decorateClass([
|
|
609
|
-
(0, import_common6.Injectable)()
|
|
610
|
-
], MulterToUploadPipe);
|
|
611
|
-
var gqlScalarPipeMap = /* @__PURE__ */ new Map([
|
|
612
|
-
[import_base3.Int, IntPipe],
|
|
613
|
-
[import_base3.Float, FloatPipe],
|
|
614
|
-
[Boolean, BooleanPipe],
|
|
615
|
-
[Date, DayjsPipe],
|
|
616
|
-
[import_base3.JSON, JSONPipe]
|
|
617
|
-
]);
|
|
618
|
-
var getQueryPipes = (modelRef, arrDepth) => {
|
|
619
|
-
const pipes = arrDepth ? [ArrayifyPipe] : [];
|
|
620
|
-
const scalarPipe = gqlScalarPipeMap.get(modelRef);
|
|
621
|
-
if (scalarPipe)
|
|
622
|
-
pipes.push(scalarPipe);
|
|
623
|
-
return pipes;
|
|
624
|
-
};
|
|
625
|
-
var getBodyPipes = (argMeta) => {
|
|
626
|
-
const [returnRef] = (0, import_base3.getNonArrayModel)(argMeta.returns());
|
|
627
|
-
if (returnRef.prototype !== Date.prototype && !(0, import_base3.isGqlScalar)(returnRef))
|
|
628
|
-
return [];
|
|
629
|
-
let BodyPipe = class {
|
|
630
|
-
transform(value, metadata) {
|
|
631
|
-
return (0, import_signal3.deserializeArg)(argMeta, value);
|
|
632
|
-
}
|
|
633
|
-
};
|
|
634
|
-
BodyPipe = __decorateClass([
|
|
635
|
-
(0, import_common6.Injectable)()
|
|
636
|
-
], BodyPipe);
|
|
637
|
-
return [BodyPipe];
|
|
638
|
-
};
|
|
639
|
-
|
|
640
|
-
// pkgs/@akanjs/nest/src/exporter.ts
|
|
641
|
-
var exporter_exports = {};
|
|
642
|
-
__export(exporter_exports, {
|
|
643
|
-
FileSystem: () => FileSystem,
|
|
644
|
-
exportToCsv: () => exportToCsv,
|
|
645
|
-
exportToJson: () => exportToJson,
|
|
646
|
-
objPath: () => objPath,
|
|
647
|
-
readJson: () => readJson
|
|
648
|
-
});
|
|
649
|
-
var fs = __toESM(require("fs"));
|
|
650
|
-
var objPath = (o, p) => p.split(".").reduce((a, v) => a[v], o);
|
|
651
|
-
var FileSystem = class {
|
|
652
|
-
filename = "";
|
|
653
|
-
dirname = "./";
|
|
654
|
-
writeStream;
|
|
655
|
-
constructor(dirname = "./", filename = "") {
|
|
656
|
-
this.dirname = dirname;
|
|
657
|
-
this.filename = filename;
|
|
658
|
-
}
|
|
659
|
-
async init() {
|
|
660
|
-
return new Promise((resolve, reject) => {
|
|
661
|
-
fs.mkdirSync(this.dirname, { recursive: true });
|
|
662
|
-
const writeStream = fs.createWriteStream(`${this.dirname}/${this.filename}.csv`);
|
|
663
|
-
if (!writeStream) {
|
|
664
|
-
reject(new Error("No WriteStream"));
|
|
665
|
-
return;
|
|
666
|
-
}
|
|
667
|
-
writeStream.once(`open`, () => {
|
|
668
|
-
this.writeStream = writeStream;
|
|
669
|
-
resolve(writeStream);
|
|
670
|
-
});
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
write(body) {
|
|
674
|
-
if (!this.writeStream)
|
|
675
|
-
throw new Error("no write stream");
|
|
676
|
-
return this.writeStream.write(`${body.replace(/\n/g, "")}
|
|
677
|
-
`);
|
|
678
|
-
}
|
|
679
|
-
// async finish() {}
|
|
680
|
-
};
|
|
681
|
-
var exportToCsv = async ({ items, path, fields, delimiter, options }) => {
|
|
682
|
-
return new Promise((resolve, reject) => {
|
|
683
|
-
const dirs = path.split("/");
|
|
684
|
-
if (dirs.length > 1) {
|
|
685
|
-
const dirname = dirs.slice(-1).join("/");
|
|
686
|
-
if (!fs.existsSync(dirname))
|
|
687
|
-
fs.mkdirSync(dirname, { recursive: true });
|
|
688
|
-
}
|
|
689
|
-
if (!fields)
|
|
690
|
-
throw new Error("Fields Required");
|
|
691
|
-
const writeStream = !options?.append && fs.createWriteStream(path);
|
|
692
|
-
const header = fields.reduce((acc, cur) => acc + (delimiter ?? `,`) + cur) + `
|
|
693
|
-
`;
|
|
694
|
-
if (!writeStream) {
|
|
695
|
-
reject(new Error("No WriteStream"));
|
|
696
|
-
return;
|
|
697
|
-
}
|
|
698
|
-
writeStream.once(`open`, () => {
|
|
699
|
-
writeStream.write(header);
|
|
700
|
-
for (const item of items) {
|
|
701
|
-
const data = fields.map((field) => objPath(item, field) ?? null).map((field) => String(field).replace(/\n/g, "").replace(/,/g, ""));
|
|
702
|
-
const body = data.reduce((acc, cur) => acc + (delimiter ?? `,`) + cur) + `
|
|
703
|
-
`;
|
|
704
|
-
if (options?.append)
|
|
705
|
-
fs.appendFileSync(path, body);
|
|
706
|
-
}
|
|
707
|
-
resolve();
|
|
708
|
-
});
|
|
709
|
-
});
|
|
710
|
-
};
|
|
711
|
-
var exportToJson = (items, localPath) => {
|
|
712
|
-
const dirname = localPath.split("/").slice(0, -1).join("/");
|
|
713
|
-
if (!fs.existsSync(dirname))
|
|
714
|
-
fs.mkdirSync(dirname, { recursive: true });
|
|
715
|
-
fs.writeFileSync(localPath, JSON.stringify(items));
|
|
716
|
-
};
|
|
717
|
-
var readJson = (localPath) => JSON.parse(fs.readFileSync(localPath).toString("utf-8"));
|
|
718
|
-
|
|
719
|
-
// pkgs/@akanjs/nest/src/verifyPayment.ts
|
|
720
|
-
var import_iap = __toESM(require("iap"));
|
|
721
|
-
var verifyPayment = async (payment) => {
|
|
722
|
-
return new Promise(
|
|
723
|
-
(resolve, reject) => (
|
|
724
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
725
|
-
import_iap.default.verifyPayment(payment.platform, { ...payment }, (error, response) => {
|
|
726
|
-
if (error)
|
|
727
|
-
reject(`App Purchase Verify Failed. ${response}`);
|
|
728
|
-
else
|
|
729
|
-
resolve(response);
|
|
730
|
-
})
|
|
731
|
-
)
|
|
732
|
-
);
|
|
733
|
-
};
|
|
734
|
-
|
|
735
|
-
// pkgs/@akanjs/nest/src/sso.ts
|
|
736
|
-
var import_common7 = require("@nestjs/common");
|
|
737
|
-
var import_passport = require("@nestjs/passport");
|
|
738
|
-
var appleSignin = __toESM(require("apple-signin"));
|
|
739
|
-
var jwt2 = __toESM(require("jsonwebtoken"));
|
|
740
|
-
var import_passport_apple = require("passport-apple");
|
|
741
|
-
var import_passport_facebook = require("passport-facebook");
|
|
742
|
-
var import_passport_github = require("passport-github");
|
|
743
|
-
var import_passport_google_oauth20 = require("passport-google-oauth20");
|
|
744
|
-
var import_passport_kakao = require("passport-kakao");
|
|
745
|
-
var import_passport_naver = require("passport-naver");
|
|
746
|
-
var getSsoProviders = (host, ssoOptions) => {
|
|
747
|
-
const origin = host === "localhost" ? "http://localhost:8080/backend" : `https://${host}/backend`;
|
|
748
|
-
const providers = [];
|
|
749
|
-
if (ssoOptions.kakao) {
|
|
750
|
-
let KakaoOauthStrategy = class extends (0, import_passport.PassportStrategy)(import_passport_kakao.Strategy, "kakao") {
|
|
751
|
-
constructor() {
|
|
752
|
-
super({
|
|
753
|
-
...ssoOptions.kakao,
|
|
754
|
-
callbackURL: `${origin}/user/kakao/callback`,
|
|
755
|
-
scope: ["account_email", "profile_nickname"]
|
|
756
|
-
});
|
|
757
|
-
}
|
|
758
|
-
validate(jwt3, refreshToken, profile) {
|
|
759
|
-
return {
|
|
760
|
-
name: profile.displayName,
|
|
761
|
-
email: profile._json.kakao_account.email,
|
|
762
|
-
password: profile.id
|
|
763
|
-
};
|
|
764
|
-
}
|
|
765
|
-
};
|
|
766
|
-
KakaoOauthStrategy = __decorateClass([
|
|
767
|
-
(0, import_common7.Injectable)()
|
|
768
|
-
], KakaoOauthStrategy);
|
|
769
|
-
providers.push(KakaoOauthStrategy);
|
|
770
|
-
}
|
|
771
|
-
if (ssoOptions.naver) {
|
|
772
|
-
let NaverOauthStrategy = class extends (0, import_passport.PassportStrategy)(import_passport_naver.Strategy, "naver") {
|
|
773
|
-
constructor() {
|
|
774
|
-
super({ ...ssoOptions.naver, callbackURL: `${origin}/user/naver/callback` });
|
|
775
|
-
}
|
|
776
|
-
validate(jwt3, refreshToken, profile) {
|
|
777
|
-
return {
|
|
778
|
-
name: profile.displayName,
|
|
779
|
-
email: profile._json.email,
|
|
780
|
-
password: profile.id
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
};
|
|
784
|
-
NaverOauthStrategy = __decorateClass([
|
|
785
|
-
(0, import_common7.Injectable)()
|
|
786
|
-
], NaverOauthStrategy);
|
|
787
|
-
providers.push(NaverOauthStrategy);
|
|
788
|
-
}
|
|
789
|
-
if (ssoOptions.github) {
|
|
790
|
-
let GithubOauthStrategy = class extends (0, import_passport.PassportStrategy)(import_passport_github.Strategy, "github") {
|
|
791
|
-
constructor() {
|
|
792
|
-
super({ ...ssoOptions.github, callbackURL: `${origin}/user/github/callback`, scope: ["user"] });
|
|
793
|
-
}
|
|
794
|
-
validate(accessToken, _refreshToken, profile) {
|
|
795
|
-
return profile;
|
|
796
|
-
}
|
|
797
|
-
};
|
|
798
|
-
GithubOauthStrategy = __decorateClass([
|
|
799
|
-
(0, import_common7.Injectable)()
|
|
800
|
-
], GithubOauthStrategy);
|
|
801
|
-
providers.push(GithubOauthStrategy);
|
|
802
|
-
}
|
|
803
|
-
if (ssoOptions.google) {
|
|
804
|
-
let GoogleOauthStrategy = class extends (0, import_passport.PassportStrategy)(import_passport_google_oauth20.Strategy, "google") {
|
|
805
|
-
constructor() {
|
|
806
|
-
super({ ...ssoOptions.google, callbackURL: `${origin}/user/google/callback`, scope: ["email", "profile"] });
|
|
807
|
-
}
|
|
808
|
-
validate(_accessToken, _refreshToken, profile) {
|
|
809
|
-
return profile;
|
|
810
|
-
}
|
|
811
|
-
};
|
|
812
|
-
GoogleOauthStrategy = __decorateClass([
|
|
813
|
-
(0, import_common7.Injectable)()
|
|
814
|
-
], GoogleOauthStrategy);
|
|
815
|
-
providers.push(GoogleOauthStrategy);
|
|
816
|
-
}
|
|
817
|
-
if (ssoOptions.facebook) {
|
|
818
|
-
let FacebookOauthStrategy = class extends (0, import_passport.PassportStrategy)(import_passport_facebook.Strategy, "facebook") {
|
|
819
|
-
constructor() {
|
|
820
|
-
super({
|
|
821
|
-
...ssoOptions.facebook,
|
|
822
|
-
callbackURL: `${origin}/user/facebook/callback`,
|
|
823
|
-
scope: ["email"],
|
|
824
|
-
profileFields: ["emails", "name"]
|
|
825
|
-
});
|
|
826
|
-
}
|
|
827
|
-
validate(_accessToken, _refreshToken, profile) {
|
|
828
|
-
return profile;
|
|
829
|
-
}
|
|
830
|
-
};
|
|
831
|
-
FacebookOauthStrategy = __decorateClass([
|
|
832
|
-
(0, import_common7.Injectable)()
|
|
833
|
-
], FacebookOauthStrategy);
|
|
834
|
-
providers.push(FacebookOauthStrategy);
|
|
835
|
-
}
|
|
836
|
-
if (ssoOptions.apple) {
|
|
837
|
-
let AppleOauthStrategy = class extends (0, import_passport.PassportStrategy)(import_passport_apple.Strategy, "apple") {
|
|
838
|
-
constructor() {
|
|
839
|
-
super({
|
|
840
|
-
...ssoOptions.apple,
|
|
841
|
-
callbackURL: `${origin}/user/apple/callback`,
|
|
842
|
-
passReqToCallback: true,
|
|
843
|
-
scope: ["name", "email"]
|
|
844
|
-
});
|
|
845
|
-
}
|
|
846
|
-
validate(req, accessToken, refreshToken, idToken, profile, cb) {
|
|
847
|
-
cb(null, idToken);
|
|
848
|
-
}
|
|
849
|
-
};
|
|
850
|
-
AppleOauthStrategy = __decorateClass([
|
|
851
|
-
(0, import_common7.Injectable)()
|
|
852
|
-
], AppleOauthStrategy);
|
|
853
|
-
providers.push(AppleOauthStrategy);
|
|
854
|
-
}
|
|
855
|
-
return providers;
|
|
856
|
-
};
|
|
857
|
-
var verifyAppleUser = async (payload, origin, sso) => {
|
|
858
|
-
const signinAgent = appleSignin;
|
|
859
|
-
const clientSecret = signinAgent.getClientSecret({
|
|
860
|
-
clientID: sso.clientID,
|
|
861
|
-
teamId: sso.teamID,
|
|
862
|
-
keyIdentifier: sso.keyID,
|
|
863
|
-
privateKeyPath: sso.keyFilePath
|
|
864
|
-
});
|
|
865
|
-
const tokens = await signinAgent.getAuthorizationToken(payload.code, {
|
|
866
|
-
clientID: sso.clientID,
|
|
867
|
-
clientSecret,
|
|
868
|
-
redirectUri: `${origin}/user/apple/callback`
|
|
869
|
-
});
|
|
870
|
-
if (!tokens.id_token) {
|
|
871
|
-
throw new Error("No id_token found in Apple's response");
|
|
872
|
-
}
|
|
873
|
-
const data = jwt2.decode(tokens.id_token);
|
|
874
|
-
return { tokens, data };
|
|
875
|
-
};
|
|
876
|
-
|
|
877
|
-
// pkgs/@akanjs/nest/src/exceptions.ts
|
|
878
|
-
var import_common8 = require("@akanjs/common");
|
|
879
|
-
var import_common9 = require("@nestjs/common");
|
|
880
|
-
var AllExceptionsFilter = class {
|
|
881
|
-
logger = new import_common8.Logger("Exception Filter");
|
|
882
|
-
catch(exception, host) {
|
|
883
|
-
if (host.getType() !== "http") {
|
|
884
|
-
const gqlArgs = host.getArgByIndex(1);
|
|
885
|
-
const gqlReq = host.getArgByIndex(3);
|
|
886
|
-
const reqType2 = gqlReq?.parentType?.name ?? "unknown";
|
|
887
|
-
const reqName2 = gqlReq?.fieldName ?? "unknown";
|
|
888
|
-
this.logger.error(
|
|
889
|
-
`GraphQL Error
|
|
890
|
-
Request: ${reqType2}-${reqName2}
|
|
891
|
-
Args: ${JSON.stringify(gqlArgs, null, 2)}
|
|
892
|
-
${exception.stack}`
|
|
893
|
-
);
|
|
894
|
-
throw exception;
|
|
895
|
-
}
|
|
896
|
-
const ctx = host.switchToHttp();
|
|
897
|
-
const res = ctx.getResponse();
|
|
898
|
-
const req = ctx.getRequest();
|
|
899
|
-
const reqType = req.method;
|
|
900
|
-
const reqName = req.url;
|
|
901
|
-
const status = exception instanceof import_common9.HttpException ? exception.getStatus() : null;
|
|
902
|
-
if (status) {
|
|
903
|
-
res.status(status).json({
|
|
904
|
-
statusCode: status,
|
|
905
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
906
|
-
path: req.url,
|
|
907
|
-
message: exception instanceof import_common9.HttpException ? exception.getResponse() : exception.message
|
|
908
|
-
});
|
|
909
|
-
this.logger.error(
|
|
910
|
-
`Http Error: ${status}
|
|
911
|
-
Request: ${reqType}-${reqName}
|
|
912
|
-
Body: ${JSON.stringify(req.body, null, 2)}
|
|
913
|
-
${exception.stack}`
|
|
914
|
-
);
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
};
|
|
918
|
-
AllExceptionsFilter = __decorateClass([
|
|
919
|
-
(0, import_common9.Catch)()
|
|
920
|
-
], AllExceptionsFilter);
|
|
921
|
-
|
|
922
|
-
// pkgs/@akanjs/nest/src/generateSecrets.ts
|
|
923
|
-
var import_base4 = require("@akanjs/base");
|
|
924
|
-
var import_crypto = require("crypto");
|
|
925
|
-
var import_tunnel_ssh = require("tunnel-ssh");
|
|
926
|
-
var generateHexStringFromSeed = (seed, length = 256) => {
|
|
927
|
-
let hexString = "";
|
|
928
|
-
let currentSeed = seed;
|
|
929
|
-
while (hexString.length < length * 2) {
|
|
930
|
-
const hash = (0, import_crypto.createHash)("sha256").update(currentSeed).digest("hex");
|
|
931
|
-
hexString += hash;
|
|
932
|
-
currentSeed = hash;
|
|
933
|
-
}
|
|
934
|
-
return hexString.substring(0, length * 2);
|
|
935
|
-
};
|
|
936
|
-
var generateJwtSecret = (appName, environment) => {
|
|
937
|
-
const seed = `${appName}-${environment}-jwt-secret`;
|
|
938
|
-
return generateHexStringFromSeed(seed);
|
|
939
|
-
};
|
|
940
|
-
var generateAeskey = (appName, environment) => {
|
|
941
|
-
const seed = `${appName}-${environment}-aes-key`;
|
|
942
|
-
return (0, import_crypto.createHash)("sha256").update(seed).digest("hex");
|
|
943
|
-
};
|
|
944
|
-
var DEFAULT_CLOUD_PORT = 3e4;
|
|
945
|
-
var getEnvironmentPort = (environment) => environment === "main" ? 2e3 : environment === "develop" ? 1e3 : environment === "debug" ? 0 : 0;
|
|
946
|
-
var getServicePort = (appCode, service) => (service === "redis" ? 300 : service === "mongo" ? 400 : 500) + appCode % 10 * 10 + (appCode >= 10 ? 5 : 0);
|
|
947
|
-
var createDatabaseTunnel = async ({
|
|
948
|
-
appName,
|
|
949
|
-
environment,
|
|
950
|
-
type,
|
|
951
|
-
port,
|
|
952
|
-
sshOptions = {
|
|
953
|
-
host: `${appName}-${environment}.${import_base4.baseEnv.serveDomain}`,
|
|
954
|
-
port: 32767,
|
|
955
|
-
username: import_base4.baseEnv.tunnelUsername,
|
|
956
|
-
password: import_base4.baseEnv.tunnelPassword
|
|
957
|
-
}
|
|
958
|
-
}) => {
|
|
959
|
-
const tunnelOptions = { autoClose: true, reconnectOnError: false };
|
|
960
|
-
const serverOptions = { port };
|
|
961
|
-
const forwardOptions = {
|
|
962
|
-
srcAddr: "0.0.0.0",
|
|
963
|
-
srcPort: port,
|
|
964
|
-
dstAddr: `${type}-0.${type}-svc.${appName}-${environment}`,
|
|
965
|
-
dstPort: type === "mongo" ? 27017 : type === "redis" ? 6379 : 7700
|
|
966
|
-
};
|
|
967
|
-
const [server, client] = await (0, import_tunnel_ssh.createTunnel)(tunnelOptions, serverOptions, sshOptions, forwardOptions);
|
|
968
|
-
return `localhost:${port}`;
|
|
969
|
-
};
|
|
970
|
-
var generateRedisUri = async ({ appName, appCode, environment, operationMode, sshOptions }) => {
|
|
971
|
-
if (process.env.REDIS_URI)
|
|
972
|
-
return process.env.REDIS_URI;
|
|
973
|
-
const port = operationMode === "local" ? DEFAULT_CLOUD_PORT + getEnvironmentPort(environment) + getServicePort(appCode, "redis") : 6379;
|
|
974
|
-
const url = operationMode === "cloud" ? `redis-svc.${appName}-${environment}.svc.cluster.local` : operationMode === "local" ? await createDatabaseTunnel({ appName, environment, type: "redis", port, sshOptions }) : "localhost:6379";
|
|
975
|
-
const uri = `redis://${url}`;
|
|
976
|
-
return uri;
|
|
977
|
-
};
|
|
978
|
-
var generateMongoUri = async ({
|
|
979
|
-
appName,
|
|
980
|
-
appCode,
|
|
981
|
-
environment,
|
|
982
|
-
operationMode,
|
|
983
|
-
username = `${appName}-${environment}-mongo-user`,
|
|
984
|
-
password,
|
|
985
|
-
sshOptions
|
|
986
|
-
}) => {
|
|
987
|
-
if (process.env.MONGO_URI)
|
|
988
|
-
return process.env.MONGO_URI;
|
|
989
|
-
const record = operationMode === "cloud" ? "mongodb+srv" : "mongodb";
|
|
990
|
-
const port = operationMode === "local" ? DEFAULT_CLOUD_PORT + getEnvironmentPort(environment) + getServicePort(appCode, "mongo") : 27017;
|
|
991
|
-
const url = operationMode === "cloud" ? `mongo-svc.${appName}-${environment}.svc.cluster.local` : operationMode === "local" ? await createDatabaseTunnel({ appName, environment, type: "mongo", port, sshOptions }) : "localhost:27017";
|
|
992
|
-
const usernameEncoded = password ? encodeURIComponent(username) : null;
|
|
993
|
-
const passwordEncoded = password ? encodeURIComponent(password) : null;
|
|
994
|
-
const dbName = `${appName}-${environment}`;
|
|
995
|
-
const directConnection = operationMode === "cloud" ? false : true;
|
|
996
|
-
const authInfo = usernameEncoded ? `${usernameEncoded}:${passwordEncoded}@` : "";
|
|
997
|
-
const uri = `${record}://${authInfo}${url}/${dbName}?authSource=${dbName}&readPreference=primary&ssl=false&retryWrites=true&directConnection=${directConnection}`;
|
|
998
|
-
return uri;
|
|
999
|
-
};
|
|
1000
|
-
var generateMeiliUri = ({ appName, appCode, environment, operationMode }) => {
|
|
1001
|
-
if (process.env.MEILI_URI)
|
|
1002
|
-
return process.env.MEILI_URI;
|
|
1003
|
-
const protocol = operationMode === "local" ? "https" : "http";
|
|
1004
|
-
const url = operationMode === "cloud" ? `meili-0.meili-svc.${appName}-${environment}.svc.cluster.local:7700` : operationMode === "local" ? `${appName}-${environment}.${import_base4.baseEnv.serveDomain}/search` : "localhost:7700";
|
|
1005
|
-
const uri = `${protocol}://${url}`;
|
|
1006
|
-
return uri;
|
|
1007
|
-
};
|
|
1008
|
-
var SALT_ROUNDS = 11;
|
|
1009
|
-
var generateHost = (env) => {
|
|
1010
|
-
if (process.env.HOST_NAME)
|
|
1011
|
-
return process.env.HOST_NAME;
|
|
1012
|
-
else if (env.hostname)
|
|
1013
|
-
return env.hostname;
|
|
1014
|
-
else if (env.operationMode === "local")
|
|
1015
|
-
return "localhost";
|
|
1016
|
-
else
|
|
1017
|
-
return `${env.appName}-${env.environment}.${import_base4.baseEnv.serveDomain}`;
|
|
1018
|
-
};
|
|
1019
|
-
var generateMeiliKey = ({ appName, environment }) => {
|
|
1020
|
-
return `meilisearch-key-${appName}-${environment}`;
|
|
1021
|
-
};
|
|
1022
|
-
|
|
1023
|
-
// pkgs/@akanjs/nest/src/mongoose.ts
|
|
1024
|
-
var import_common10 = require("@akanjs/common");
|
|
1025
|
-
var import_mongoose = __toESM(require("mongoose"));
|
|
1026
|
-
var initMongoDB = ({
|
|
1027
|
-
logging,
|
|
1028
|
-
threshold = 5e3,
|
|
1029
|
-
sendReport = false
|
|
1030
|
-
}) => {
|
|
1031
|
-
const mongoDBLogger = new import_common10.Logger("MongoDB");
|
|
1032
|
-
if (logging)
|
|
1033
|
-
import_mongoose.default.set("debug", function(collection, method, ...methodArgs) {
|
|
1034
|
-
mongoDBLogger.verbose(
|
|
1035
|
-
`${collection}.${method}(${methodArgs.slice(0, -1).map((arg) => JSON.stringify(arg)).join(", ")})`
|
|
1036
|
-
);
|
|
1037
|
-
});
|
|
1038
|
-
const originalExec = import_mongoose.default.Query.prototype.exec;
|
|
1039
|
-
const getQueryInfo = (queryAgent) => {
|
|
1040
|
-
const model = queryAgent.model;
|
|
1041
|
-
const collectionName = model.collection.collectionName;
|
|
1042
|
-
const dbName = model.db.name;
|
|
1043
|
-
const query = queryAgent.getQuery();
|
|
1044
|
-
const queryOptions = queryAgent.getOptions();
|
|
1045
|
-
return { dbName, collectionName, query, queryOptions };
|
|
1046
|
-
};
|
|
1047
|
-
import_mongoose.default.Query.prototype.exec = function(...args) {
|
|
1048
|
-
const start = Date.now();
|
|
1049
|
-
return originalExec.apply(this, args).then((result) => {
|
|
1050
|
-
const duration = Date.now() - start;
|
|
1051
|
-
const { dbName, collectionName, query, queryOptions } = getQueryInfo(this);
|
|
1052
|
-
if (logging)
|
|
1053
|
-
mongoDBLogger.verbose(
|
|
1054
|
-
`Queried ${dbName}.${collectionName}.query(${JSON.stringify(query)}, ${JSON.stringify(
|
|
1055
|
-
queryOptions
|
|
1056
|
-
)}) - ${duration}ms`
|
|
1057
|
-
);
|
|
1058
|
-
return result;
|
|
1059
|
-
});
|
|
1060
|
-
};
|
|
1061
|
-
const originalAggregate = import_mongoose.default.Model.aggregate;
|
|
1062
|
-
const getAggregateInfo = (aggregateModel) => {
|
|
1063
|
-
const dbName = aggregateModel.db.db?.databaseName ?? "unknown";
|
|
1064
|
-
const collectionName = aggregateModel.collection.collectionName;
|
|
1065
|
-
return { dbName, collectionName };
|
|
1066
|
-
};
|
|
1067
|
-
import_mongoose.default.Model.aggregate = function(...args) {
|
|
1068
|
-
const startTime = Date.now();
|
|
1069
|
-
return originalAggregate.apply(this, args).then((result) => {
|
|
1070
|
-
const duration = Date.now() - startTime;
|
|
1071
|
-
const { dbName, collectionName } = getAggregateInfo(this);
|
|
1072
|
-
if (logging)
|
|
1073
|
-
mongoDBLogger.verbose(
|
|
1074
|
-
`Aggregated ${dbName}.${collectionName}.aggregate(${args.map((arg) => JSON.stringify(arg)).join(", ")}) - ${duration}ms`
|
|
1075
|
-
);
|
|
1076
|
-
return result;
|
|
1077
|
-
});
|
|
1078
|
-
};
|
|
1079
|
-
import_mongoose.default.set("transactionAsyncLocalStorage", true);
|
|
1080
|
-
};
|
|
1081
|
-
|
|
1082
|
-
// pkgs/@akanjs/nest/src/searchClient.ts
|
|
1083
|
-
var import_constant = require("@akanjs/constant");
|
|
1084
|
-
var import_common11 = require("@nestjs/common");
|
|
1085
|
-
var SearchClient = class {
|
|
1086
|
-
meili;
|
|
1087
|
-
async getIndexNames() {
|
|
1088
|
-
const { results } = await this.meili.getIndexes({ limit: 1e3 });
|
|
1089
|
-
return results.map((index) => index.uid);
|
|
1090
|
-
}
|
|
1091
|
-
async getSearchResult(indexName, option) {
|
|
1092
|
-
const { skip = 0, limit = import_constant.DEFAULT_PAGE_SIZE, sort = "", searchString } = option;
|
|
1093
|
-
if (!searchString) {
|
|
1094
|
-
const { results, total } = await this.meili.index(indexName).getDocuments({ offset: skip, limit });
|
|
1095
|
-
return { docs: results, skip, limit, sort, total };
|
|
1096
|
-
}
|
|
1097
|
-
const { hits, estimatedTotalHits } = await this.meili.index(indexName).search(searchString, { offset: skip, limit });
|
|
1098
|
-
return { docs: hits, skip, limit, sort, total: estimatedTotalHits, query: searchString };
|
|
1099
|
-
}
|
|
1100
|
-
async upsertDocuments(indexName, documents) {
|
|
1101
|
-
const task = await this.meili.index(indexName).addDocuments(documents);
|
|
1102
|
-
return task;
|
|
1103
|
-
}
|
|
1104
|
-
async dropIndex(indexName) {
|
|
1105
|
-
const task = await this.meili.index(indexName).delete();
|
|
1106
|
-
return task;
|
|
1107
|
-
}
|
|
1108
|
-
};
|
|
1109
|
-
__decorateClass([
|
|
1110
|
-
(0, import_common11.Inject)("MEILI_CLIENT")
|
|
1111
|
-
], SearchClient.prototype, "meili", 2);
|
|
1112
|
-
SearchClient = __decorateClass([
|
|
1113
|
-
(0, import_common11.Injectable)()
|
|
1114
|
-
], SearchClient);
|
|
1115
|
-
|
|
1116
|
-
// pkgs/@akanjs/nest/src/cacheClient.ts
|
|
1117
|
-
var import_common12 = require("@nestjs/common");
|
|
1118
|
-
var CacheClient = class {
|
|
1119
|
-
redis;
|
|
1120
|
-
};
|
|
1121
|
-
__decorateClass([
|
|
1122
|
-
(0, import_common12.Inject)("REDIS_CLIENT")
|
|
1123
|
-
], CacheClient.prototype, "redis", 2);
|
|
1124
|
-
CacheClient = __decorateClass([
|
|
1125
|
-
(0, import_common12.Injectable)()
|
|
1126
|
-
], CacheClient);
|
|
1127
|
-
|
|
1128
|
-
// pkgs/@akanjs/nest/src/databaseClient.ts
|
|
1129
|
-
var import_common13 = require("@akanjs/common");
|
|
1130
|
-
var import_common14 = require("@nestjs/common");
|
|
1131
|
-
var import_mongoose2 = require("@nestjs/mongoose");
|
|
1132
|
-
var DatabaseClient = class {
|
|
1133
|
-
connection;
|
|
1134
|
-
getModel(modelName) {
|
|
1135
|
-
const model = this.connection.models[(0, import_common13.capitalize)(modelName)];
|
|
1136
|
-
return model;
|
|
1137
|
-
}
|
|
1138
|
-
};
|
|
1139
|
-
__decorateClass([
|
|
1140
|
-
(0, import_mongoose2.InjectConnection)()
|
|
1141
|
-
], DatabaseClient.prototype, "connection", 2);
|
|
1142
|
-
DatabaseClient = __decorateClass([
|
|
1143
|
-
(0, import_common14.Injectable)()
|
|
1144
|
-
], DatabaseClient);
|
|
1145
|
-
|
|
1146
|
-
// pkgs/@akanjs/nest/src/decorators.ts
|
|
1147
|
-
var import_reflect_metadata = require("reflect-metadata");
|
|
1148
|
-
var import_schedule = require("@nestjs/schedule");
|
|
1149
|
-
var Try = () => {
|
|
1150
|
-
return function(target, key, descriptor) {
|
|
1151
|
-
const originMethod = descriptor.value;
|
|
1152
|
-
descriptor.value = async function(...args) {
|
|
1153
|
-
try {
|
|
1154
|
-
const result = await originMethod.apply(this, args);
|
|
1155
|
-
return result;
|
|
1156
|
-
} catch (e) {
|
|
1157
|
-
this.logger?.warn(`${key} action error return: ${e}`);
|
|
1158
|
-
}
|
|
1159
|
-
};
|
|
1160
|
-
};
|
|
1161
|
-
};
|
|
1162
|
-
var Cron = (cronTime, { lock = true, serverMode, enabled = true } = {}) => {
|
|
1163
|
-
return function(target, key, descriptor) {
|
|
1164
|
-
const originMethod = descriptor.value;
|
|
1165
|
-
let isRunning = false;
|
|
1166
|
-
descriptor.value = async function(...args) {
|
|
1167
|
-
if (lock && isRunning)
|
|
1168
|
-
return this.logger?.warn(`Cronjob-${key} is already running, skipped`);
|
|
1169
|
-
try {
|
|
1170
|
-
isRunning = true;
|
|
1171
|
-
this.logger?.verbose(`Cron Job-${key} started`);
|
|
1172
|
-
const res = await originMethod.apply(this, args);
|
|
1173
|
-
this.logger?.verbose(`Cron Job-${key} finished`);
|
|
1174
|
-
isRunning = false;
|
|
1175
|
-
return res;
|
|
1176
|
-
} catch (e) {
|
|
1177
|
-
this.logger?.error(`Cron Job-${key} error return: ${e}`);
|
|
1178
|
-
isRunning = false;
|
|
1179
|
-
}
|
|
1180
|
-
};
|
|
1181
|
-
if (!enabled)
|
|
1182
|
-
return;
|
|
1183
|
-
if (!serverMode || process.env.SERVER_MODE === "all" || serverMode === process.env.SERVER_MODE)
|
|
1184
|
-
(0, import_schedule.Cron)(cronTime)(target, key, descriptor);
|
|
1185
|
-
};
|
|
1186
|
-
};
|
|
1187
|
-
var getIntervalMetaMap = (prototype) => {
|
|
1188
|
-
return Reflect.getMetadata("serviceInterval", prototype) ?? /* @__PURE__ */ new Map();
|
|
1189
|
-
};
|
|
1190
|
-
var setIntervalMetaMap = (prototype, intervalMetaMap) => {
|
|
1191
|
-
Reflect.defineMetadata("serviceInterval", intervalMetaMap, prototype);
|
|
1192
|
-
};
|
|
1193
|
-
var Interval = (ms, { lock = true, serverMode, enabled = true } = {}) => {
|
|
1194
|
-
return function(target, key, descriptor) {
|
|
1195
|
-
const intervalMetaMap = getIntervalMetaMap(target);
|
|
1196
|
-
if (intervalMetaMap.has(key))
|
|
1197
|
-
return descriptor;
|
|
1198
|
-
intervalMetaMap.set(key, descriptor.value);
|
|
1199
|
-
setIntervalMetaMap(target, intervalMetaMap);
|
|
1200
|
-
const originMethod = descriptor.value;
|
|
1201
|
-
let isRunning = false;
|
|
1202
|
-
descriptor.value = async function(...args) {
|
|
1203
|
-
if (lock && isRunning)
|
|
1204
|
-
return this.logger?.warn(`Cronjob-${key} is already running, skipped`);
|
|
1205
|
-
try {
|
|
1206
|
-
isRunning = true;
|
|
1207
|
-
this.logger?.verbose(`Interval Job-${key} started`);
|
|
1208
|
-
const res = await originMethod.apply(this, args);
|
|
1209
|
-
this.logger?.verbose(`Interval Job-${key} finished`);
|
|
1210
|
-
isRunning = false;
|
|
1211
|
-
return res;
|
|
1212
|
-
} catch (e) {
|
|
1213
|
-
this.logger?.error(`Cronjob-${key} error return: ${e}`);
|
|
1214
|
-
isRunning = false;
|
|
1215
|
-
}
|
|
1216
|
-
};
|
|
1217
|
-
if (!enabled)
|
|
1218
|
-
return;
|
|
1219
|
-
if (!serverMode || process.env.SERVER_MODE === "all" || serverMode === process.env.SERVER_MODE)
|
|
1220
|
-
(0, import_schedule.Interval)(ms)(target, key, descriptor);
|
|
1221
|
-
};
|
|
1222
|
-
};
|
|
1223
|
-
var Transaction = () => {
|
|
1224
|
-
return function(target, key, descriptor) {
|
|
1225
|
-
const originMethod = descriptor.value;
|
|
1226
|
-
descriptor.value = function(...args) {
|
|
1227
|
-
if (!this.connection)
|
|
1228
|
-
throw new Error(`No Connection in function ${key}`);
|
|
1229
|
-
return new Promise((resolve, reject) => {
|
|
1230
|
-
this.connection.transaction(async () => {
|
|
1231
|
-
const res = await originMethod.apply(this, args);
|
|
1232
|
-
resolve(res);
|
|
1233
|
-
}).catch(reject);
|
|
1234
|
-
});
|
|
1235
|
-
};
|
|
1236
|
-
return descriptor;
|
|
1237
|
-
};
|
|
1238
|
-
};
|
|
1239
|
-
var Cache = (timeout2 = 1e3, getCacheKey) => {
|
|
1240
|
-
return function(target, key, descriptor) {
|
|
1241
|
-
const originMethod = descriptor.value;
|
|
1242
|
-
const cacheMap = /* @__PURE__ */ new Map();
|
|
1243
|
-
const timerMap = /* @__PURE__ */ new Map();
|
|
1244
|
-
descriptor.value = async function(...args) {
|
|
1245
|
-
const classType = this.__model ? "doc" : this.__databaseModel ? "service" : "class";
|
|
1246
|
-
const model = this.__model ?? this.__databaseModel?.__model;
|
|
1247
|
-
const cache = this.__cache ?? this.__databaseModel?.__cache;
|
|
1248
|
-
const getCacheKeyFn = getCacheKey ?? JSON.stringify;
|
|
1249
|
-
const cacheKey = `${classType}:${model.modelName}:${key}:${getCacheKeyFn(...args)}`;
|
|
1250
|
-
const getCache = async (cacheKey2) => {
|
|
1251
|
-
if (classType === "class")
|
|
1252
|
-
return cacheMap.get(cacheKey2);
|
|
1253
|
-
const cached = await cache.get(cacheKey2);
|
|
1254
|
-
if (cached)
|
|
1255
|
-
return JSON.parse(cached);
|
|
1256
|
-
return null;
|
|
1257
|
-
};
|
|
1258
|
-
const setCache = async (cacheKey2, value) => {
|
|
1259
|
-
if (classType === "class") {
|
|
1260
|
-
const existingTimer = timerMap.get(cacheKey2);
|
|
1261
|
-
if (existingTimer)
|
|
1262
|
-
clearTimeout(existingTimer);
|
|
1263
|
-
cacheMap.set(cacheKey2, value);
|
|
1264
|
-
const timer = setTimeout(() => {
|
|
1265
|
-
cacheMap.delete(cacheKey2);
|
|
1266
|
-
timerMap.delete(cacheKey2);
|
|
1267
|
-
}, timeout2);
|
|
1268
|
-
timerMap.set(cacheKey2, timer);
|
|
1269
|
-
} else
|
|
1270
|
-
await cache.set(cacheKey2, JSON.stringify(value), { PX: timeout2 });
|
|
1271
|
-
};
|
|
1272
|
-
const cachedData = await getCache(cacheKey);
|
|
1273
|
-
if (cachedData) {
|
|
1274
|
-
this.logger?.trace(`${model.modelName} cache hit: ${cacheKey}`);
|
|
1275
|
-
return cachedData;
|
|
1276
|
-
}
|
|
1277
|
-
const result = await originMethod.apply(this, args);
|
|
1278
|
-
await setCache(cacheKey, result);
|
|
1279
|
-
this.logger?.trace(`${model.modelName} cache set: ${cacheKey}`);
|
|
1280
|
-
return result;
|
|
1281
|
-
};
|
|
1282
|
-
};
|
|
1283
|
-
};
|
|
17
|
+
__reExport(nest_exports, require("./src"), module.exports);
|