@codisolutions23/node-utils 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,704 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+
38
+ // src/middleware/auth.middleware.ts
39
+ import jwt from "jsonwebtoken";
40
+
41
+ // src/utils/logger.ts
42
+ import * as winston from "winston";
43
+ var transports2 = [
44
+ new winston.transports.File({ filename: "error.log", level: "error" }),
45
+ new winston.transports.File({ filename: "combined.log" })
46
+ ];
47
+ var logger = winston.createLogger({
48
+ level: "info",
49
+ format: winston.format.combine(
50
+ winston.format.timestamp(),
51
+ winston.format.json()
52
+ ),
53
+ transports: transports2
54
+ });
55
+
56
+ // src/utils/http-error.ts
57
+ var HttpError = class extends Error {
58
+ constructor(message, statusCode, isOperational = true) {
59
+ super(message);
60
+ Object.setPrototypeOf(this, new.target.prototype);
61
+ this.statusCode = statusCode;
62
+ this.isOperational = isOperational;
63
+ if (Error.captureStackTrace) {
64
+ Error.captureStackTrace(this, this.constructor);
65
+ }
66
+ }
67
+ };
68
+ var BadRequestError = class extends HttpError {
69
+ constructor(message = "The request could not be processed. Please review your input and try again.") {
70
+ super(message, 400, true);
71
+ }
72
+ };
73
+ var UnauthorizedError = class extends HttpError {
74
+ constructor(message = "Authentication is required to access this resource.") {
75
+ super(message, 401, true);
76
+ }
77
+ };
78
+ var ForbiddenError = class extends HttpError {
79
+ constructor(message = "You do not have the necessary permissions to perform this action.") {
80
+ super(message, 403, true);
81
+ }
82
+ };
83
+ var NotFoundError = class extends HttpError {
84
+ constructor(message = "The requested resource could not be found.") {
85
+ super(message, 404, true);
86
+ }
87
+ };
88
+ var UnprocessableEntityError = class extends HttpError {
89
+ constructor(message = "The request could not be completed due to invalid or incomplete information.") {
90
+ super(message, 422, true);
91
+ }
92
+ };
93
+ var InternalServerError = class extends HttpError {
94
+ constructor(message = "An internal server error occurred. Please try again later.") {
95
+ super(message, 500, true);
96
+ }
97
+ };
98
+
99
+ // src/middleware/auth.middleware.ts
100
+ function authenticateJWT(secretKey = "") {
101
+ return (req, res, next) => {
102
+ const authHeader = req.headers.authorization;
103
+ const jwtToken = authHeader && authHeader.split(" ")[1];
104
+ if (!jwtToken) {
105
+ logger.error("No access token provided in the request.");
106
+ return next(
107
+ new UnauthorizedError("Access token is required to proceed.")
108
+ );
109
+ }
110
+ if (!secretKey) {
111
+ logger.error("JWT secret key is not set in the configuration.");
112
+ return next(
113
+ new UnauthorizedError(
114
+ "Authentication service is not properly configured."
115
+ )
116
+ );
117
+ }
118
+ jwt.verify(jwtToken, secretKey, (error, decodedUser) => {
119
+ if (error) {
120
+ logger.error("Failed to verify access token.", error);
121
+ return next(
122
+ new UnauthorizedError(
123
+ "Your session has expired or the token is invalid. Please log in again."
124
+ )
125
+ );
126
+ }
127
+ req.user = decodedUser;
128
+ next();
129
+ });
130
+ };
131
+ }
132
+
133
+ // src/middleware/error-handler.middleware.ts
134
+ var errorHandler = (error, req, res, next) => {
135
+ if (error.isOperational) {
136
+ res.status(error.statusCode).json({ status: "error", message: error.message });
137
+ } else {
138
+ logger.error({ message: error.message });
139
+ res.status(500).json({ status: "error", message: new InternalServerError().message });
140
+ }
141
+ return;
142
+ };
143
+
144
+ // src/utils/atlas.ts
145
+ import { MongoClient } from "mongodb";
146
+ var useAtlas = class {
147
+ static connect(config2) {
148
+ return __async(this, null, function* () {
149
+ if (this.mongoClient) {
150
+ logger.warn(
151
+ "[MongoDB][Connect] Client is already connected. Skipping new connection."
152
+ );
153
+ throw new BadRequestError("A MongoDB connection is already established.");
154
+ }
155
+ const { db, uri } = config2;
156
+ this.mongoClient = new MongoClient(uri, {
157
+ maxPoolSize: 10,
158
+ maxIdleTimeMS: 6e4,
159
+ connectTimeoutMS: 6e4
160
+ });
161
+ try {
162
+ yield this.mongoClient.connect();
163
+ this.mongoDb = this.mongoClient.db(db);
164
+ logger.info(
165
+ `[MongoDB][Connect] Connected to database "${this.mongoDb.databaseName}".`
166
+ );
167
+ } catch (error) {
168
+ this.mongoClient = null;
169
+ logger.error(
170
+ `[MongoDB][Connect] Failed to connect: ${error instanceof Error ? error.message : error}`
171
+ );
172
+ throw new InternalServerError(
173
+ "Failed to connect to the database. Please try again later."
174
+ );
175
+ }
176
+ });
177
+ }
178
+ static getClient() {
179
+ if (!this.mongoClient) {
180
+ logger.warn(`[MongoDB][GetClient] Client is not initialized.`);
181
+ throw new NotFoundError("MongoDB client is not initialized.");
182
+ }
183
+ return this.mongoClient;
184
+ }
185
+ static getDb() {
186
+ if (!this.mongoDb) {
187
+ logger.warn(`[MongoDB][GetDb] Database instance is not available.`);
188
+ throw new NotFoundError("MongoDB database instance is not available.");
189
+ }
190
+ return this.mongoDb;
191
+ }
192
+ static close() {
193
+ return __async(this, null, function* () {
194
+ if (this.mongoClient) {
195
+ try {
196
+ yield this.mongoClient.close();
197
+ logger.info(`[MongoDB][Close] Connection closed.`);
198
+ } catch (error) {
199
+ logger.error(
200
+ `[MongoDB][Close] Error closing connection: ${error instanceof Error ? error.message : error}`
201
+ );
202
+ throw new InternalServerError("Failed to close MongoDB connection.");
203
+ } finally {
204
+ this.mongoClient = null;
205
+ this.mongoDb = null;
206
+ }
207
+ } else {
208
+ logger.warn(`[MongoDB][Close] No client to disconnect.`);
209
+ throw new BadRequestError("No MongoDB connection exists to close.");
210
+ }
211
+ });
212
+ }
213
+ };
214
+ useAtlas.mongoClient = null;
215
+ useAtlas.mongoDb = null;
216
+
217
+ // src/utils/cache-key.ts
218
+ function buildCacheKey(prefix, values) {
219
+ const query = Object.entries(values).sort(([a], [b]) => a.localeCompare(b)).map(
220
+ ([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`
221
+ ).join("&");
222
+ return `${prefix}:${query}`;
223
+ }
224
+
225
+ // src/utils/ioredis.ts
226
+ import Redis from "ioredis";
227
+ var redisClient = null;
228
+ function useRedis() {
229
+ function initialize(options) {
230
+ var _a, _b, _c, _d;
231
+ if (redisClient) {
232
+ logger.info("[Redis][Init] Redis connection is already established.");
233
+ return redisClient;
234
+ }
235
+ options.host = (_a = options.host) != null ? _a : "localhost";
236
+ options.port = (_b = options.port) != null ? _b : 6379;
237
+ options.username = (_c = options.username) != null ? _c : "default";
238
+ options.password = (_d = options.password) != null ? _d : "";
239
+ redisClient = new Redis(__spreadValues(__spreadValues({
240
+ host: options.host,
241
+ port: options.port
242
+ }, options.username && { username: options.username }), options.password && { password: options.password }));
243
+ redisClient.on("connect", () => {
244
+ logger.info(
245
+ `[Redis][Connect] Redis client connected at ${options.host}:${options.port}.`
246
+ );
247
+ });
248
+ redisClient.on("error", (error) => {
249
+ logger.error(
250
+ `[Redis][Error] Failed to connect: ${error instanceof Error ? error.message : error}`
251
+ );
252
+ });
253
+ return redisClient;
254
+ }
255
+ function getClient() {
256
+ if (!redisClient) {
257
+ logger.error(
258
+ "[Redis][GetClient] Redis connection has not been initialized."
259
+ );
260
+ throw new BadRequestError(
261
+ "Redis connection is not initialized. Please call initialize() first."
262
+ );
263
+ }
264
+ return redisClient;
265
+ }
266
+ function disconnect() {
267
+ if (redisClient) {
268
+ redisClient.quit();
269
+ logger.info("[Redis][Disconnect] Redis connection has been closed.");
270
+ redisClient = null;
271
+ } else {
272
+ logger.warn("[Redis][Disconnect] No Redis client to disconnect.");
273
+ }
274
+ }
275
+ return {
276
+ initialize,
277
+ getClient,
278
+ disconnect
279
+ };
280
+ }
281
+
282
+ // src/utils/cache.ts
283
+ var DEFAULT_TTL = 300;
284
+ function useCache() {
285
+ const redisClient3 = useRedis().getClient();
286
+ function get(cacheKey) {
287
+ return __async(this, null, function* () {
288
+ try {
289
+ const value = yield redisClient3.get(cacheKey);
290
+ return value ? JSON.parse(value) : null;
291
+ } catch (error) {
292
+ logger.error(
293
+ `[Cache][Get] Failed to retrieve key "${cacheKey}": ${error instanceof Error ? error.message : error}`
294
+ );
295
+ return null;
296
+ }
297
+ });
298
+ }
299
+ function set(_0, _1) {
300
+ return __async(this, arguments, function* (cacheKey, data, ttl = DEFAULT_TTL, group) {
301
+ try {
302
+ yield redisClient3.set(cacheKey, JSON.stringify(data), "EX", ttl);
303
+ logger.info(`[Cache][Set] Stored key "${cacheKey}" with TTL ${ttl}s.`);
304
+ if (group) yield redisClient3.sadd(`cache:group:${group}`, cacheKey);
305
+ } catch (error) {
306
+ logger.error(
307
+ `[Cache][Set] Failed to store key "${cacheKey}": ${error instanceof Error ? error.message : error}`
308
+ );
309
+ }
310
+ });
311
+ }
312
+ function remove(cacheKey) {
313
+ return __async(this, null, function* () {
314
+ try {
315
+ yield redisClient3.del(cacheKey);
316
+ logger.info(`[Cache][Remove] Key "${cacheKey}" has been deleted.`);
317
+ } catch (error) {
318
+ logger.error(
319
+ `[Cache][Remove] Failed to delete key "${cacheKey}": ${error instanceof Error ? error.message : error}`
320
+ );
321
+ }
322
+ });
323
+ }
324
+ function clearGroup(group) {
325
+ return __async(this, null, function* () {
326
+ try {
327
+ const keys = yield redisClient3.smembers(`cache:group:${group}`);
328
+ if (keys.length) yield redisClient3.del(...keys);
329
+ yield redisClient3.del(`cache:group:${group}`);
330
+ logger.info(`[Cache][ClearGroup] Cleared group "${group}" and its keys.`);
331
+ } catch (error) {
332
+ logger.error(
333
+ `[Cache][ClearGroup] Failed to clear group "${group}": ${error instanceof Error ? error.message : error}`
334
+ );
335
+ }
336
+ });
337
+ }
338
+ return {
339
+ get,
340
+ set,
341
+ remove,
342
+ clearGroup
343
+ };
344
+ }
345
+
346
+ // src/utils/get-template-path.ts
347
+ import path from "path";
348
+ function getTemplatePath(directory, filePath) {
349
+ const ext = ".hbs";
350
+ const file = filePath.endsWith(ext) ? filePath : `${filePath}${ext}`;
351
+ return path.resolve(directory, file);
352
+ }
353
+
354
+ // src/utils/handlebars-compiler.ts
355
+ import Handlebars from "handlebars";
356
+ import { promises as fs } from "fs";
357
+ var handlebarsTemplateCache = /* @__PURE__ */ new Map();
358
+ function renderHandlebarsTemplate(_0) {
359
+ return __async(this, arguments, function* ({
360
+ context = {},
361
+ filePath
362
+ }) {
363
+ try {
364
+ let compiledTemplate = handlebarsTemplateCache.get(filePath);
365
+ if (!compiledTemplate) {
366
+ logger.info(
367
+ `[Template][Compile] Compiling and caching template from "${filePath}".`
368
+ );
369
+ const fileContent = yield fs.readFile(filePath, "utf8");
370
+ compiledTemplate = Handlebars.compile(fileContent);
371
+ handlebarsTemplateCache.set(filePath, compiledTemplate);
372
+ } else {
373
+ logger.info(`[Template][Cache] Using cached template for "${filePath}".`);
374
+ }
375
+ return compiledTemplate(context);
376
+ } catch (error) {
377
+ logger.error(
378
+ `[Template][Render] Failed to render template "${filePath}": ${error instanceof Error ? error.message : error}`
379
+ );
380
+ throw new InternalServerError("Failed to render Handlebars template.");
381
+ }
382
+ });
383
+ }
384
+
385
+ // src/utils/jwt.ts
386
+ import jwt2 from "jsonwebtoken";
387
+ function signJwtToken({
388
+ payload = {},
389
+ secretKey = "",
390
+ signOptions = {}
391
+ }) {
392
+ if (!secretKey) {
393
+ logger.error(`[JWT][Sign] Secret key is missing. Cannot sign token.`);
394
+ throw new BadRequestError("A JWT secret key must be provided.");
395
+ }
396
+ try {
397
+ logger.info(`[JWT][Sign] Signing JWT token.`);
398
+ return jwt2.sign(payload, secretKey, signOptions);
399
+ } catch (error) {
400
+ logger.error(
401
+ `[JWT][Sign] Failed to sign JWT token: ${error instanceof Error ? error.message : error}`
402
+ );
403
+ throw error;
404
+ }
405
+ }
406
+
407
+ // src/utils/mailer.ts
408
+ import { createTransport } from "nodemailer";
409
+ var useMailer = class {
410
+ constructor(config2) {
411
+ this.config = config2;
412
+ this.transporter = createTransport({
413
+ host: config2.host,
414
+ port: config2.port,
415
+ secure: config2.secure,
416
+ auth: { user: config2.email, pass: config2.password }
417
+ });
418
+ }
419
+ sendMail(_0) {
420
+ return __async(this, arguments, function* ({
421
+ sender,
422
+ to,
423
+ subject,
424
+ text,
425
+ html
426
+ }) {
427
+ const from = sender ? `${sender} <${this.config.email}>` : this.config.email;
428
+ const mailOptions = __spreadValues(__spreadValues({
429
+ from,
430
+ to,
431
+ subject
432
+ }, text && { text }), html && { html });
433
+ try {
434
+ yield this.transporter.sendMail(mailOptions);
435
+ logger.info(
436
+ `[Mailer][Send] Email sent to "${to}" with subject "${subject}".`
437
+ );
438
+ return "Mail sent successfully.";
439
+ } catch (error) {
440
+ logger.error(
441
+ `[Mailer][Send] Failed to send email to "${to}" with subject "${subject}": ${error instanceof Error ? error.message : error}`
442
+ );
443
+ throw new InternalServerError("Failed to send email.");
444
+ }
445
+ });
446
+ }
447
+ };
448
+
449
+ // src/utils/objectid-converter.ts
450
+ import { ObjectId } from "mongodb";
451
+ function toObjectId(id) {
452
+ if (!id) {
453
+ logger.error(
454
+ `[ObjectId][Convert] No value provided for MongoDB ObjectId conversion.`
455
+ );
456
+ throw new BadRequestError(
457
+ "A value must be provided for ObjectId conversion."
458
+ );
459
+ }
460
+ if (id instanceof ObjectId) return id;
461
+ if (!/^[0-9a-fA-F]{24}$/.test(id)) {
462
+ logger.error(
463
+ `[ObjectId][Convert] Provided value is not a valid 24-character hex string.`
464
+ );
465
+ throw new BadRequestError(
466
+ "Invalid ObjectId: must be a 24-character hexadecimal string."
467
+ );
468
+ }
469
+ try {
470
+ return new ObjectId(id);
471
+ } catch (err) {
472
+ logger.error(
473
+ `[ObjectId][Convert] Failed to convert value to ObjectId: ${err instanceof Error ? err.message : err}`
474
+ );
475
+ throw new BadRequestError("Failed to convert value into a valid ObjectId.");
476
+ }
477
+ }
478
+
479
+ // src/utils/paginate.ts
480
+ function paginate(items, page = 0, limit = 10, total) {
481
+ if (total === 0) {
482
+ return {
483
+ items: [],
484
+ pages: 0,
485
+ pageRange: "0-0 of 0"
486
+ };
487
+ }
488
+ const startIndex = page * limit + 1;
489
+ const endIndex = Math.min(startIndex + items.length - 1, total);
490
+ return {
491
+ items,
492
+ pages: Math.ceil(total / limit),
493
+ pageRange: `${startIndex}-${endIndex} of ${total}`
494
+ };
495
+ }
496
+
497
+ // src/utils/password.ts
498
+ import bcrypt from "bcrypt";
499
+ var DEFAULT_SALT_ROUNDS = 10;
500
+ function comparePasswords(password, hashed) {
501
+ return __async(this, null, function* () {
502
+ try {
503
+ return yield bcrypt.compare(password, hashed);
504
+ } catch (error) {
505
+ logger.error(
506
+ `[Password][Compare] Failed to compare passwords: ${error instanceof Error ? error.message : error}`
507
+ );
508
+ return false;
509
+ }
510
+ });
511
+ }
512
+ function hashPassword(_0) {
513
+ return __async(this, arguments, function* (password, saltRounds = DEFAULT_SALT_ROUNDS) {
514
+ try {
515
+ return yield bcrypt.hash(password, saltRounds);
516
+ } catch (error) {
517
+ logger.error(
518
+ `[Password][Hash] Failed to hash password: ${error instanceof Error ? error.message : error}`
519
+ );
520
+ throw new InternalServerError("Failed to hash password.");
521
+ }
522
+ });
523
+ }
524
+
525
+ // src/utils/redis.ts
526
+ import { createClient } from "redis";
527
+
528
+ // src/config.ts
529
+ import * as dotenv from "dotenv";
530
+ dotenv.config();
531
+ function getEnv(key, fallback) {
532
+ const value = process.env[key];
533
+ if (value !== void 0) return value;
534
+ if (fallback !== void 0) return fallback;
535
+ throw new Error(`Missing required environment variable: ${key}`);
536
+ }
537
+ function getEnvNumber(key, fallback) {
538
+ const value = process.env[key];
539
+ if (value !== void 0) return Number(value);
540
+ if (fallback !== void 0) return fallback;
541
+ throw new Error(`Missing required environment variable: ${key}`);
542
+ }
543
+ function getEnvBoolean(key, fallback) {
544
+ const value = process.env[key];
545
+ if (value !== void 0) return value === "true";
546
+ if (fallback !== void 0) return fallback;
547
+ throw new Error(`Missing required environment variable: ${key}`);
548
+ }
549
+ var isDev = process.env.NODE_ENV !== "production";
550
+ var PORT = getEnvNumber("PORT", 3001);
551
+ var MONGO_URI = getEnv("MONGO_URI", "mongodb://localhost:27017");
552
+ var MONGO_DB = getEnv("MONGO_DB", "default");
553
+ var MONGO_DB_DEV = getEnv("MONGO_DB_DEV", `${MONGO_DB}-dev`);
554
+ var REDIS_HOST = getEnv("REDIS_HOST");
555
+ var REDIS_PORT = getEnvNumber("REDIS_PORT", 6379);
556
+ var REDIS_PASSWORD = getEnv("REDIS_PASSWORD");
557
+ var REDIS_TLS = getEnvBoolean("REDIS_TLS", true);
558
+ var MAILER_TRANSPORT_HOST = getEnv("MAILER_TRANSPORT_HOST");
559
+ var MAILER_TRANSPORT_PORT = getEnvNumber("MAILER_TRANSPORT_PORT", 465);
560
+ var MAILER_TRANSPORT_SECURE = getEnvBoolean(
561
+ "MAILER_TRANSPORT_SECURE",
562
+ true
563
+ );
564
+ var MAILER_EMAIL = getEnv("MAILER_EMAIL");
565
+ var MAILER_PASSWORD = getEnv("MAILER_PASSWORD");
566
+ var SECRET_KEY = getEnv("SECRET_KEY");
567
+ var ACCESS_TOKEN_SECRET = getEnv("ACCESS_TOKEN_SECRET");
568
+ var REFRESH_TOKEN_SECRET = getEnv("REFRESH_TOKEN_SECRET");
569
+ var ACCESS_TOKEN_EXPIRY = getEnv("ACCESS_TOKEN_EXPIRY", "15s");
570
+ var REFRESH_TOKEN_EXPIRY = getEnv("REFRESH_TOKEN_EXPIRY", "30d");
571
+ var OTP_FORGET_PASSWORD_EXPIRY = getEnv(
572
+ "OTP_FORGET_PASSWORD_EXPIRY",
573
+ "10m"
574
+ );
575
+ var OTP_USER_INVITE_EXPIRY = getEnv("OTP_USER_INVITE_EXPIRY", "3d");
576
+ var APP_COUNT = getEnv("APP_ACCOUNT", "http:localhost:3000");
577
+
578
+ // src/utils/redis.ts
579
+ var redisClient2 = null;
580
+ function initRedisClient() {
581
+ return __async(this, null, function* () {
582
+ if (redisClient2) {
583
+ logger.info("[Redis][Init] Redis connection is already established.");
584
+ return redisClient2;
585
+ }
586
+ redisClient2 = createClient({
587
+ password: REDIS_PASSWORD,
588
+ socket: {
589
+ host: REDIS_HOST,
590
+ port: REDIS_PORT
591
+ }
592
+ });
593
+ });
594
+ }
595
+ function useRedisClient() {
596
+ if (!redisClient2) {
597
+ logger.error(
598
+ "[Redis][GetClient] Redis connection has not been initialized."
599
+ );
600
+ throw new Error(
601
+ "[Redis][GetClient] Redis connection is not initialized. Call initRedisClient() first."
602
+ );
603
+ }
604
+ return redisClient2;
605
+ }
606
+
607
+ // src/utils/s3.ts
608
+ import {
609
+ DeleteObjectCommand,
610
+ PutObjectCommand,
611
+ S3Client
612
+ } from "@aws-sdk/client-s3";
613
+ import { Readable } from "stream";
614
+ var useS3 = class {
615
+ constructor(config2) {
616
+ this.config = config2;
617
+ this.client = new S3Client({
618
+ endpoint: config2.endpoint,
619
+ region: config2.region,
620
+ credentials: {
621
+ accessKeyId: config2.accessKeyId,
622
+ secretAccessKey: config2.secretAccessKey
623
+ },
624
+ forcePathStyle: config2.forcePathStyle
625
+ });
626
+ }
627
+ uploadObject(_0) {
628
+ return __async(this, arguments, function* ({
629
+ key,
630
+ body,
631
+ metadata = {},
632
+ contentType
633
+ }) {
634
+ try {
635
+ yield this.client.send(
636
+ new PutObjectCommand({
637
+ Bucket: this.config.bucket,
638
+ Key: key,
639
+ Body: typeof body === "string" || Buffer.isBuffer(body) ? body : Readable.from(body),
640
+ ACL: "public-read",
641
+ Metadata: metadata,
642
+ ContentType: contentType,
643
+ ContentLength: typeof body === "string" ? Buffer.byteLength(body) : body.length
644
+ })
645
+ );
646
+ logger.info(
647
+ `[S3][Upload] Uploaded "${key}" to bucket "${this.config.bucket}".`
648
+ );
649
+ return "Successfully uploaded file.";
650
+ } catch (error) {
651
+ logger.error(
652
+ `[S3][Upload][Error] Failed to upload "${key}" to bucket "${this.config.bucket}": ${error instanceof Error ? error.message : error}`
653
+ );
654
+ throw error;
655
+ }
656
+ });
657
+ }
658
+ deleteObject(key) {
659
+ return __async(this, null, function* () {
660
+ try {
661
+ yield this.client.send(
662
+ new DeleteObjectCommand({ Key: key, Bucket: this.config.bucket })
663
+ );
664
+ logger.info(
665
+ `[S3][Delete] Deleted "${key}" from bucket "${this.config.bucket}".`
666
+ );
667
+ return "Successfully deleted file.";
668
+ } catch (error) {
669
+ logger.error(
670
+ `[S3][Delete][Error] Failed to delete "${key}" from bucket "${this.config.bucket}": ${error instanceof Error ? error.message : error}`
671
+ );
672
+ throw error;
673
+ }
674
+ });
675
+ }
676
+ };
677
+ export {
678
+ BadRequestError,
679
+ ForbiddenError,
680
+ HttpError,
681
+ InternalServerError,
682
+ NotFoundError,
683
+ UnauthorizedError,
684
+ UnprocessableEntityError,
685
+ authenticateJWT,
686
+ buildCacheKey,
687
+ comparePasswords,
688
+ errorHandler,
689
+ getTemplatePath,
690
+ hashPassword,
691
+ initRedisClient,
692
+ logger,
693
+ paginate,
694
+ renderHandlebarsTemplate,
695
+ signJwtToken,
696
+ toObjectId,
697
+ useAtlas,
698
+ useCache,
699
+ useMailer,
700
+ useRedis,
701
+ useRedisClient,
702
+ useS3
703
+ };
704
+ //# sourceMappingURL=index.mjs.map