@exyconn/common 2.3.2 → 2.3.3
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/README.md +117 -12
- package/dist/client/http/index.d.mts +217 -49
- package/dist/client/http/index.d.ts +217 -49
- package/dist/client/http/index.js +473 -94
- package/dist/client/http/index.js.map +1 -1
- package/dist/client/http/index.mjs +441 -84
- package/dist/client/http/index.mjs.map +1 -1
- package/dist/client/index.d.mts +3 -3
- package/dist/client/index.d.ts +3 -3
- package/dist/client/index.js +481 -319
- package/dist/client/index.js.map +1 -1
- package/dist/client/index.mjs +449 -290
- package/dist/client/index.mjs.map +1 -1
- package/dist/client/utils/index.d.mts +3 -279
- package/dist/client/utils/index.d.ts +3 -279
- package/dist/{index-DuxL84IW.d.mts → index-BZf42T3R.d.mts} +39 -39
- package/dist/{index-D9a9oxQy.d.ts → index-CF0D8PGE.d.ts} +39 -39
- package/dist/{index-D3yCCjBZ.d.mts → index-Ckhm_HaX.d.mts} +21 -2
- package/dist/{index-01hoqibP.d.ts → index-br6POSyA.d.ts} +21 -2
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1122 -329
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1134 -341
- package/dist/index.mjs.map +1 -1
- package/dist/packageCheck-B_qfsD6R.d.ts +280 -0
- package/dist/packageCheck-C2_FT_Rl.d.mts +280 -0
- package/dist/server/index.d.mts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +631 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +625 -2
- package/dist/server/index.mjs.map +1 -1
- package/dist/server/middleware/index.d.mts +283 -2
- package/dist/server/middleware/index.d.ts +283 -2
- package/dist/server/middleware/index.js +761 -0
- package/dist/server/middleware/index.js.map +1 -1
- package/dist/server/middleware/index.mjs +751 -1
- package/dist/server/middleware/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/server/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import winston from 'winston';
|
|
2
2
|
import DailyRotateFile from 'winston-daily-rotate-file';
|
|
3
3
|
import path, { resolve } from 'path';
|
|
4
|
-
import mongoose from 'mongoose';
|
|
4
|
+
import mongoose, { Types } from 'mongoose';
|
|
5
5
|
import jwt from 'jsonwebtoken';
|
|
6
6
|
import { existsSync, readFileSync } from 'fs';
|
|
7
7
|
import rateLimit from 'express-rate-limit';
|
|
@@ -417,6 +417,629 @@ var requireOrganization = (req, res, next) => {
|
|
|
417
417
|
next();
|
|
418
418
|
};
|
|
419
419
|
|
|
420
|
+
// src/server/middleware/queryParser.middleware.ts
|
|
421
|
+
var queryParser = (req, _, next) => {
|
|
422
|
+
const { page, limit, sort, sortBy, sortOrder, search, filter, ...otherParams } = req.query;
|
|
423
|
+
const parsed = {
|
|
424
|
+
page: Math.max(Number(page) || 1, 1),
|
|
425
|
+
limit: Math.min(Number(limit) || 10, 100),
|
|
426
|
+
filter: {}
|
|
427
|
+
};
|
|
428
|
+
if (typeof sort === "string") {
|
|
429
|
+
const [field, order] = sort.split(":");
|
|
430
|
+
parsed.sort = {
|
|
431
|
+
field,
|
|
432
|
+
order: order === "asc" ? "asc" : "desc"
|
|
433
|
+
};
|
|
434
|
+
} else if (typeof sortBy === "string") {
|
|
435
|
+
parsed.sort = {
|
|
436
|
+
field: sortBy,
|
|
437
|
+
order: sortOrder === "asc" ? "asc" : "desc"
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
if (typeof search === "string") {
|
|
441
|
+
parsed.search = search;
|
|
442
|
+
}
|
|
443
|
+
if (typeof filter === "object" && filter !== null) {
|
|
444
|
+
Object.entries(filter).forEach(([key, value]) => {
|
|
445
|
+
if (value !== "all") {
|
|
446
|
+
parsed.filter[key] = value;
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
Object.entries(otherParams).forEach(([key, value]) => {
|
|
451
|
+
if (typeof value === "string" && value !== "all" && !["page", "limit", "sort", "sortBy", "sortOrder", "search"].includes(key)) {
|
|
452
|
+
parsed.filter[key] = value;
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
req.parsedQuery = parsed;
|
|
456
|
+
next();
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
// src/server/middleware/utils/schemaMeta.util.ts
|
|
460
|
+
var getZodTypeName = (schema) => {
|
|
461
|
+
const typeName = schema._def?.typeName;
|
|
462
|
+
switch (typeName) {
|
|
463
|
+
case "ZodString":
|
|
464
|
+
return "string";
|
|
465
|
+
case "ZodNumber":
|
|
466
|
+
return "number";
|
|
467
|
+
case "ZodBoolean":
|
|
468
|
+
return "boolean";
|
|
469
|
+
case "ZodDate":
|
|
470
|
+
return "date";
|
|
471
|
+
case "ZodArray":
|
|
472
|
+
return "array";
|
|
473
|
+
case "ZodObject":
|
|
474
|
+
return "object";
|
|
475
|
+
case "ZodOptional":
|
|
476
|
+
case "ZodNullable":
|
|
477
|
+
return schema._def?.innerType ? getZodTypeName(schema._def.innerType) : "unknown";
|
|
478
|
+
case "ZodDefault":
|
|
479
|
+
return schema._def?.innerType ? getZodTypeName(schema._def.innerType) : "unknown";
|
|
480
|
+
case "ZodEnum":
|
|
481
|
+
return "enum";
|
|
482
|
+
case "ZodUnion":
|
|
483
|
+
return "union";
|
|
484
|
+
default:
|
|
485
|
+
return "unknown";
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
var isZodRequired = (schema) => {
|
|
489
|
+
const typeName = schema._def?.typeName;
|
|
490
|
+
return typeName !== "ZodOptional" && typeName !== "ZodNullable";
|
|
491
|
+
};
|
|
492
|
+
var extractSchemaMeta = (model, zodSchema) => {
|
|
493
|
+
const columns = [];
|
|
494
|
+
if (zodSchema && zodSchema.shape) {
|
|
495
|
+
const shape = zodSchema.shape;
|
|
496
|
+
for (const [key, value] of Object.entries(shape)) {
|
|
497
|
+
if (key.startsWith("_")) continue;
|
|
498
|
+
columns.push({
|
|
499
|
+
name: key,
|
|
500
|
+
datatype: getZodTypeName(value),
|
|
501
|
+
required: isZodRequired(value)
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
return columns;
|
|
505
|
+
}
|
|
506
|
+
try {
|
|
507
|
+
const schema = model.schema;
|
|
508
|
+
const paths = schema.paths;
|
|
509
|
+
for (const [key, pathInfo] of Object.entries(paths)) {
|
|
510
|
+
if (key.startsWith("_") || key === "__v") continue;
|
|
511
|
+
const schemaType = pathInfo;
|
|
512
|
+
columns.push({
|
|
513
|
+
name: key,
|
|
514
|
+
datatype: (schemaType.instance || "unknown").toLowerCase(),
|
|
515
|
+
required: schemaType.isRequired || false
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
} catch {
|
|
519
|
+
}
|
|
520
|
+
return columns;
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// src/server/middleware/pagination.middleware.ts
|
|
524
|
+
var queryPagination = (model, options = {}, withOrgId = true) => {
|
|
525
|
+
return async (req, res, next) => {
|
|
526
|
+
try {
|
|
527
|
+
const { page, limit, sort, search, filter } = req.parsedQuery;
|
|
528
|
+
const query = {};
|
|
529
|
+
Object.entries(filter).forEach(([key, value]) => {
|
|
530
|
+
if (options.regexFilterFields?.includes(key)) {
|
|
531
|
+
query[key] = { $regex: value, $options: "i" };
|
|
532
|
+
} else {
|
|
533
|
+
query[key] = value;
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
const organizationId = req.headers["x-organization-id"];
|
|
537
|
+
if (organizationId && typeof organizationId === "string" && withOrgId) {
|
|
538
|
+
query.organizationId = organizationId;
|
|
539
|
+
}
|
|
540
|
+
if (search && options.searchFields?.length) {
|
|
541
|
+
query.$or = options.searchFields.map((field) => ({
|
|
542
|
+
[field]: { $regex: search, $options: "i" }
|
|
543
|
+
}));
|
|
544
|
+
}
|
|
545
|
+
const sortQuery = sort ? { [sort.field]: sort.order } : { createdAt: "desc" };
|
|
546
|
+
const skip = (page - 1) * limit;
|
|
547
|
+
const [data, total] = await Promise.all([
|
|
548
|
+
model.find(query).sort(sortQuery).skip(skip).limit(limit),
|
|
549
|
+
model.countDocuments(query)
|
|
550
|
+
]);
|
|
551
|
+
res.paginatedResult = {
|
|
552
|
+
data,
|
|
553
|
+
meta: {
|
|
554
|
+
page,
|
|
555
|
+
limit,
|
|
556
|
+
total,
|
|
557
|
+
totalPages: Math.ceil(total / limit)
|
|
558
|
+
},
|
|
559
|
+
columns: extractSchemaMeta(model, options.validatorSchema)
|
|
560
|
+
};
|
|
561
|
+
next();
|
|
562
|
+
} catch (error) {
|
|
563
|
+
next(error);
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
};
|
|
567
|
+
var isZodError = (error) => {
|
|
568
|
+
return error !== null && typeof error === "object" && "errors" in error && Array.isArray(error.errors);
|
|
569
|
+
};
|
|
570
|
+
var getOrgId = (req, orgField = "organizationId") => {
|
|
571
|
+
const orgReq = req;
|
|
572
|
+
return orgReq.organizationId || req.headers["x-organization-id"] || req.query[orgField];
|
|
573
|
+
};
|
|
574
|
+
var buildOrgFilter = (req, config) => {
|
|
575
|
+
const filter = {};
|
|
576
|
+
if (config.withOrganization !== false) {
|
|
577
|
+
const orgId = getOrgId(req, config.orgField);
|
|
578
|
+
if (orgId) {
|
|
579
|
+
filter[config.orgField || "organizationId"] = orgId;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return filter;
|
|
583
|
+
};
|
|
584
|
+
var formatZodError = (error) => {
|
|
585
|
+
return error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");
|
|
586
|
+
};
|
|
587
|
+
function createCrudControllers(config) {
|
|
588
|
+
const {
|
|
589
|
+
model,
|
|
590
|
+
resourceName,
|
|
591
|
+
createSchema,
|
|
592
|
+
updateSchema,
|
|
593
|
+
searchFields = [],
|
|
594
|
+
regexFilterFields = [],
|
|
595
|
+
withOrganization = true,
|
|
596
|
+
orgField = "organizationId",
|
|
597
|
+
transformCreate,
|
|
598
|
+
transformUpdate,
|
|
599
|
+
afterCreate,
|
|
600
|
+
afterUpdate,
|
|
601
|
+
afterDelete,
|
|
602
|
+
excludeFields = [],
|
|
603
|
+
populateFields = [],
|
|
604
|
+
buildQuery
|
|
605
|
+
} = config;
|
|
606
|
+
const getAll = async (req, res, _next) => {
|
|
607
|
+
try {
|
|
608
|
+
const paginatedRes = res;
|
|
609
|
+
if (paginatedRes.paginatedResult) {
|
|
610
|
+
successResponse(res, paginatedRes.paginatedResult, `${resourceName} list fetched successfully`);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
const page = parseInt(req.query.page) || 1;
|
|
614
|
+
const limit = parseInt(req.query.limit) || 10;
|
|
615
|
+
const sortField = req.query.sortBy || "createdAt";
|
|
616
|
+
const sortOrder = req.query.sortOrder || "desc";
|
|
617
|
+
const search = req.query.search;
|
|
618
|
+
let query = {};
|
|
619
|
+
if (withOrganization) {
|
|
620
|
+
const orgId = getOrgId(req, orgField);
|
|
621
|
+
if (orgId) {
|
|
622
|
+
query[orgField] = orgId;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (search && searchFields.length > 0) {
|
|
626
|
+
query.$or = searchFields.map((field) => ({
|
|
627
|
+
[field]: { $regex: search, $options: "i" }
|
|
628
|
+
}));
|
|
629
|
+
}
|
|
630
|
+
const filterableParams = Object.keys(req.query).filter(
|
|
631
|
+
(key) => !["page", "limit", "sortBy", "sortOrder", "search"].includes(key)
|
|
632
|
+
);
|
|
633
|
+
filterableParams.forEach((key) => {
|
|
634
|
+
const value = req.query[key];
|
|
635
|
+
if (value !== void 0 && value !== "" && value !== "all") {
|
|
636
|
+
if (regexFilterFields.includes(key)) {
|
|
637
|
+
query[key] = { $regex: value, $options: "i" };
|
|
638
|
+
} else {
|
|
639
|
+
query[key] = value;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
if (buildQuery) {
|
|
644
|
+
query = buildQuery(req, query);
|
|
645
|
+
}
|
|
646
|
+
const sortQuery = { [sortField]: sortOrder };
|
|
647
|
+
const skip = (page - 1) * limit;
|
|
648
|
+
let projection = {};
|
|
649
|
+
if (excludeFields.length > 0) {
|
|
650
|
+
projection = excludeFields.reduce(
|
|
651
|
+
(acc, field) => ({ ...acc, [field]: 0 }),
|
|
652
|
+
{}
|
|
653
|
+
);
|
|
654
|
+
}
|
|
655
|
+
let dbQuery = model.find(query, projection);
|
|
656
|
+
if (populateFields.length > 0) {
|
|
657
|
+
populateFields.forEach((field) => {
|
|
658
|
+
dbQuery = dbQuery.populate(field);
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
const [data, total] = await Promise.all([
|
|
662
|
+
dbQuery.sort(sortQuery).skip(skip).limit(limit),
|
|
663
|
+
model.countDocuments(query)
|
|
664
|
+
]);
|
|
665
|
+
successResponse(
|
|
666
|
+
res,
|
|
667
|
+
{
|
|
668
|
+
data,
|
|
669
|
+
meta: {
|
|
670
|
+
page,
|
|
671
|
+
limit,
|
|
672
|
+
total,
|
|
673
|
+
totalPages: Math.ceil(total / limit)
|
|
674
|
+
},
|
|
675
|
+
columns: extractSchemaMeta(model, createSchema)
|
|
676
|
+
},
|
|
677
|
+
`${resourceName} list fetched successfully`
|
|
678
|
+
);
|
|
679
|
+
} catch (error) {
|
|
680
|
+
logger.error(`Error in getAll ${resourceName}`, {
|
|
681
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
682
|
+
});
|
|
683
|
+
errorResponse(res, `Failed to fetch ${resourceName.toLowerCase()} list`);
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const getById = async (req, res, _next) => {
|
|
687
|
+
try {
|
|
688
|
+
const { id } = req.params;
|
|
689
|
+
if (!id || !Types.ObjectId.isValid(id)) {
|
|
690
|
+
badRequestResponse(res, "Invalid ID format");
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const query = {
|
|
694
|
+
_id: new Types.ObjectId(id),
|
|
695
|
+
...buildOrgFilter(req, { ...config, withOrganization, orgField })
|
|
696
|
+
};
|
|
697
|
+
let dbQuery = model.findOne(query);
|
|
698
|
+
if (populateFields.length > 0) {
|
|
699
|
+
populateFields.forEach((field) => {
|
|
700
|
+
dbQuery = dbQuery.populate(field);
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
const doc = await dbQuery;
|
|
704
|
+
if (!doc) {
|
|
705
|
+
notFoundResponse(res, `${resourceName} not found`);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
successResponse(res, doc, `${resourceName} fetched successfully`);
|
|
709
|
+
} catch (error) {
|
|
710
|
+
logger.error(`Error in getById ${resourceName}`, {
|
|
711
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
712
|
+
id: req.params.id
|
|
713
|
+
});
|
|
714
|
+
errorResponse(res, `Failed to fetch ${resourceName.toLowerCase()}`);
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
const create = async (req, res, _next) => {
|
|
718
|
+
try {
|
|
719
|
+
let input = req.body;
|
|
720
|
+
if (createSchema) {
|
|
721
|
+
try {
|
|
722
|
+
input = createSchema.parse(input);
|
|
723
|
+
} catch (error) {
|
|
724
|
+
if (isZodError(error)) {
|
|
725
|
+
badRequestResponse(res, formatZodError(error));
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
throw error;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
if (transformCreate) {
|
|
732
|
+
input = transformCreate(input, req);
|
|
733
|
+
}
|
|
734
|
+
if (withOrganization) {
|
|
735
|
+
const orgId = getOrgId(req, orgField);
|
|
736
|
+
if (orgId) {
|
|
737
|
+
input[orgField] = orgId;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
const doc = new model(input);
|
|
741
|
+
await doc.save();
|
|
742
|
+
if (afterCreate) {
|
|
743
|
+
await afterCreate(doc, req);
|
|
744
|
+
}
|
|
745
|
+
logger.info(`${resourceName} created successfully`, {
|
|
746
|
+
id: doc._id,
|
|
747
|
+
[orgField]: input[orgField]
|
|
748
|
+
});
|
|
749
|
+
createdResponse(res, doc, `${resourceName} created successfully`);
|
|
750
|
+
} catch (error) {
|
|
751
|
+
logger.error(`Error in create ${resourceName}`, {
|
|
752
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
753
|
+
});
|
|
754
|
+
if (error.code === 11e3) {
|
|
755
|
+
badRequestResponse(res, `A ${resourceName.toLowerCase()} with this data already exists`);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
errorResponse(res, `Failed to create ${resourceName.toLowerCase()}`);
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
const update = async (req, res, _next) => {
|
|
762
|
+
try {
|
|
763
|
+
const { id } = req.params;
|
|
764
|
+
if (!id || !Types.ObjectId.isValid(id)) {
|
|
765
|
+
badRequestResponse(res, "Invalid ID format");
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
let input = req.body;
|
|
769
|
+
if (updateSchema) {
|
|
770
|
+
try {
|
|
771
|
+
input = updateSchema.parse(input);
|
|
772
|
+
} catch (error) {
|
|
773
|
+
if (isZodError(error)) {
|
|
774
|
+
badRequestResponse(res, formatZodError(error));
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
throw error;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
if (transformUpdate) {
|
|
781
|
+
input = transformUpdate(input, req);
|
|
782
|
+
}
|
|
783
|
+
const query = {
|
|
784
|
+
_id: new Types.ObjectId(id),
|
|
785
|
+
...buildOrgFilter(req, { ...config, withOrganization, orgField })
|
|
786
|
+
};
|
|
787
|
+
const doc = await model.findOneAndUpdate(query, { $set: input }, { new: true });
|
|
788
|
+
if (!doc) {
|
|
789
|
+
notFoundResponse(res, `${resourceName} not found`);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (afterUpdate) {
|
|
793
|
+
await afterUpdate(doc, req);
|
|
794
|
+
}
|
|
795
|
+
logger.info(`${resourceName} updated successfully`, { id });
|
|
796
|
+
successResponse(res, doc, `${resourceName} updated successfully`);
|
|
797
|
+
} catch (error) {
|
|
798
|
+
logger.error(`Error in update ${resourceName}`, {
|
|
799
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
800
|
+
id: req.params.id
|
|
801
|
+
});
|
|
802
|
+
errorResponse(res, `Failed to update ${resourceName.toLowerCase()}`);
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
const deleteOne = async (req, res, _next) => {
|
|
806
|
+
try {
|
|
807
|
+
const { id } = req.params;
|
|
808
|
+
if (!id || !Types.ObjectId.isValid(id)) {
|
|
809
|
+
badRequestResponse(res, "Invalid ID format");
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const query = {
|
|
813
|
+
_id: new Types.ObjectId(id),
|
|
814
|
+
...buildOrgFilter(req, { ...config, withOrganization, orgField })
|
|
815
|
+
};
|
|
816
|
+
const result = await model.deleteOne(query);
|
|
817
|
+
if (result.deletedCount === 0) {
|
|
818
|
+
notFoundResponse(res, `${resourceName} not found`);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
if (afterDelete) {
|
|
822
|
+
await afterDelete(id, req);
|
|
823
|
+
}
|
|
824
|
+
logger.info(`${resourceName} deleted successfully`, { id });
|
|
825
|
+
noContentResponse(res, null, `${resourceName} deleted successfully`);
|
|
826
|
+
} catch (error) {
|
|
827
|
+
logger.error(`Error in delete ${resourceName}`, {
|
|
828
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
829
|
+
id: req.params.id
|
|
830
|
+
});
|
|
831
|
+
errorResponse(res, `Failed to delete ${resourceName.toLowerCase()}`);
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
const bulkDelete = async (req, res, _next) => {
|
|
835
|
+
try {
|
|
836
|
+
const bulkReq = req;
|
|
837
|
+
const { deleteIds = [], deleteAll = false } = bulkReq;
|
|
838
|
+
const baseFilter = buildOrgFilter(req, { ...config, withOrganization, orgField });
|
|
839
|
+
let filter;
|
|
840
|
+
if (deleteAll) {
|
|
841
|
+
filter = baseFilter;
|
|
842
|
+
} else if (deleteIds.length > 0) {
|
|
843
|
+
filter = {
|
|
844
|
+
...baseFilter,
|
|
845
|
+
_id: { $in: deleteIds.map((id) => new Types.ObjectId(id)) }
|
|
846
|
+
};
|
|
847
|
+
} else {
|
|
848
|
+
badRequestResponse(res, "No IDs provided for deletion");
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
const result = await model.deleteMany(filter);
|
|
852
|
+
if (afterDelete && deleteIds.length > 0) {
|
|
853
|
+
await Promise.all(deleteIds.map((id) => afterDelete(id, req)));
|
|
854
|
+
}
|
|
855
|
+
logger.info(`${resourceName}(s) bulk deleted successfully`, {
|
|
856
|
+
deletedCount: result.deletedCount,
|
|
857
|
+
deleteAll
|
|
858
|
+
});
|
|
859
|
+
successResponse(
|
|
860
|
+
res,
|
|
861
|
+
{ deletedCount: result.deletedCount },
|
|
862
|
+
`${result.deletedCount} ${resourceName.toLowerCase()}(s) deleted successfully`
|
|
863
|
+
);
|
|
864
|
+
} catch (error) {
|
|
865
|
+
logger.error(`Error in bulkDelete ${resourceName}`, {
|
|
866
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
867
|
+
});
|
|
868
|
+
errorResponse(res, `Failed to delete ${resourceName.toLowerCase()}(s)`);
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
return {
|
|
872
|
+
getAll,
|
|
873
|
+
getById,
|
|
874
|
+
create,
|
|
875
|
+
update,
|
|
876
|
+
deleteOne,
|
|
877
|
+
bulkDelete
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function createPaginationMiddleware(model, config = {}) {
|
|
881
|
+
const {
|
|
882
|
+
searchFields = [],
|
|
883
|
+
regexFilterFields = [],
|
|
884
|
+
withOrganization = true,
|
|
885
|
+
orgField = "organizationId"
|
|
886
|
+
} = config;
|
|
887
|
+
return async (req, res, next) => {
|
|
888
|
+
try {
|
|
889
|
+
const page = parseInt(req.query.page) || 1;
|
|
890
|
+
const limit = parseInt(req.query.limit) || 10;
|
|
891
|
+
const sortField = req.query.sortBy || "createdAt";
|
|
892
|
+
const sortOrder = req.query.sortOrder || "desc";
|
|
893
|
+
const search = req.query.search;
|
|
894
|
+
const query = {};
|
|
895
|
+
if (withOrganization) {
|
|
896
|
+
const orgId = getOrgId(req, orgField);
|
|
897
|
+
if (orgId) {
|
|
898
|
+
query[orgField] = orgId;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
if (search && searchFields.length > 0) {
|
|
902
|
+
query.$or = searchFields.map((field) => ({
|
|
903
|
+
[field]: { $regex: search, $options: "i" }
|
|
904
|
+
}));
|
|
905
|
+
}
|
|
906
|
+
const filterableParams = Object.keys(req.query).filter(
|
|
907
|
+
(key) => !["page", "limit", "sortBy", "sortOrder", "search"].includes(key)
|
|
908
|
+
);
|
|
909
|
+
filterableParams.forEach((key) => {
|
|
910
|
+
const value = req.query[key];
|
|
911
|
+
if (value !== void 0 && value !== "" && value !== "all") {
|
|
912
|
+
if (regexFilterFields.includes(key)) {
|
|
913
|
+
query[key] = { $regex: value, $options: "i" };
|
|
914
|
+
} else {
|
|
915
|
+
query[key] = value;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
const sortQuery = { [sortField]: sortOrder };
|
|
920
|
+
const skip = (page - 1) * limit;
|
|
921
|
+
const [data, total] = await Promise.all([
|
|
922
|
+
model.find(query).sort(sortQuery).skip(skip).limit(limit),
|
|
923
|
+
model.countDocuments(query)
|
|
924
|
+
]);
|
|
925
|
+
const paginatedRes = res;
|
|
926
|
+
paginatedRes.paginatedResult = {
|
|
927
|
+
data,
|
|
928
|
+
meta: {
|
|
929
|
+
page,
|
|
930
|
+
limit,
|
|
931
|
+
total,
|
|
932
|
+
totalPages: Math.ceil(total / limit)
|
|
933
|
+
},
|
|
934
|
+
columns: extractSchemaMeta(model, config.createSchema)
|
|
935
|
+
};
|
|
936
|
+
next();
|
|
937
|
+
} catch (error) {
|
|
938
|
+
next(error);
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
var parseBulkDelete = (req, res, next) => {
|
|
943
|
+
try {
|
|
944
|
+
const bulkReq = req;
|
|
945
|
+
let ids = [];
|
|
946
|
+
if (Array.isArray(req.body)) {
|
|
947
|
+
ids = req.body;
|
|
948
|
+
} else if (req.body && Array.isArray(req.body.ids)) {
|
|
949
|
+
ids = req.body.ids;
|
|
950
|
+
} else if (req.body && typeof req.body === "object") {
|
|
951
|
+
if (Array.isArray(req.body.data)) {
|
|
952
|
+
ids = req.body.data;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
if (ids.length === 0) {
|
|
956
|
+
return badRequestResponse(
|
|
957
|
+
res,
|
|
958
|
+
'Request body must contain an array of IDs. Use ["*"] to delete all records or ["id1", "id2"] to delete specific records.'
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
if (ids.length === 1 && ids[0] === "*") {
|
|
962
|
+
bulkReq.deleteAll = true;
|
|
963
|
+
bulkReq.deleteIds = [];
|
|
964
|
+
logger.info("Bulk delete: Deleting all records");
|
|
965
|
+
return next();
|
|
966
|
+
}
|
|
967
|
+
const validIds = [];
|
|
968
|
+
const invalidIds = [];
|
|
969
|
+
for (const id of ids) {
|
|
970
|
+
if (typeof id === "string" && Types.ObjectId.isValid(id)) {
|
|
971
|
+
validIds.push(id);
|
|
972
|
+
} else {
|
|
973
|
+
invalidIds.push(id);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
if (invalidIds.length > 0) {
|
|
977
|
+
return badRequestResponse(
|
|
978
|
+
res,
|
|
979
|
+
`Invalid ID format(s): ${invalidIds.slice(0, 5).join(", ")}${invalidIds.length > 5 ? "..." : ""}. All IDs must be valid MongoDB ObjectIds.`
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
if (validIds.length === 0) {
|
|
983
|
+
return badRequestResponse(res, "No valid IDs provided for deletion.");
|
|
984
|
+
}
|
|
985
|
+
bulkReq.deleteAll = false;
|
|
986
|
+
bulkReq.deleteIds = validIds;
|
|
987
|
+
logger.info(`Bulk delete: Deleting ${validIds.length} record(s)`);
|
|
988
|
+
next();
|
|
989
|
+
} catch (error) {
|
|
990
|
+
logger.error("Error in parseBulkDelete middleware", error);
|
|
991
|
+
return badRequestResponse(res, "Failed to parse delete request");
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
var buildDeleteFilter = (req, organizationId) => {
|
|
995
|
+
const filter = {
|
|
996
|
+
organizationId: new Types.ObjectId(organizationId)
|
|
997
|
+
};
|
|
998
|
+
if (!req.deleteAll && req.deleteIds && req.deleteIds.length > 0) {
|
|
999
|
+
filter._id = {
|
|
1000
|
+
$in: req.deleteIds.map((id) => new Types.ObjectId(id))
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
return filter;
|
|
1004
|
+
};
|
|
1005
|
+
var createBulkDeleteHandler = (Model2, modelName) => {
|
|
1006
|
+
return async (req, res) => {
|
|
1007
|
+
const bulkReq = req;
|
|
1008
|
+
const organizationId = req.headers["x-organization-id"];
|
|
1009
|
+
if (!organizationId) {
|
|
1010
|
+
return badRequestResponse(res, "Organization ID is required");
|
|
1011
|
+
}
|
|
1012
|
+
try {
|
|
1013
|
+
const filter = buildDeleteFilter(bulkReq, organizationId);
|
|
1014
|
+
const result = await Model2.deleteMany(filter);
|
|
1015
|
+
const deletedCount = result.deletedCount || 0;
|
|
1016
|
+
logger.info(`Bulk delete completed: ${deletedCount} ${modelName}(s) deleted`, {
|
|
1017
|
+
organizationId,
|
|
1018
|
+
deleteAll: bulkReq.deleteAll,
|
|
1019
|
+
requestedIds: bulkReq.deleteIds?.length || "all",
|
|
1020
|
+
deletedCount
|
|
1021
|
+
});
|
|
1022
|
+
return res.status(200).json({
|
|
1023
|
+
message: `Successfully deleted ${deletedCount} ${modelName}(s)`,
|
|
1024
|
+
data: {
|
|
1025
|
+
deletedCount,
|
|
1026
|
+
deleteAll: bulkReq.deleteAll
|
|
1027
|
+
},
|
|
1028
|
+
status: "success",
|
|
1029
|
+
statusCode: 200
|
|
1030
|
+
});
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
logger.error(`Error in bulk delete ${modelName}`, error);
|
|
1033
|
+
return res.status(500).json({
|
|
1034
|
+
message: `Failed to delete ${modelName}(s)`,
|
|
1035
|
+
data: null,
|
|
1036
|
+
status: "error",
|
|
1037
|
+
statusCode: 500
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
};
|
|
1042
|
+
|
|
420
1043
|
// src/server/utils/filter-builder.ts
|
|
421
1044
|
var buildFilter = (options) => {
|
|
422
1045
|
const {
|
|
@@ -1371,6 +1994,6 @@ var getDatabaseOptions = (config) => {
|
|
|
1371
1994
|
};
|
|
1372
1995
|
};
|
|
1373
1996
|
|
|
1374
|
-
export { ConfigBuilder, DEFAULT_AUTH_CONFIG, DEFAULT_CORS_CONFIG, DEFAULT_CORS_ORIGINS, DEFAULT_DATABASE_CONFIG, DEFAULT_LOGGING_CONFIG, DEFAULT_RATE_LIMIT_CONFIG, DEFAULT_RATE_LIMIT_TIERS, DEFAULT_SERVER_CONFIG, EXYCONN_CORS_CONFIG, PERMISSIVE_CORS_CONFIG, RATE_LIMIT_CONFIG, RateLimiterBuilder, STRICT_CORS_CONFIG, StatusCode, StatusMessage, authenticateApiKey, authenticateJWT, badRequestResponse, buildConfig, buildFilter, buildPagination, buildPaginationMeta, checkPackageServer, conflictResponse, connectDB, corsOptions, createApiKeyGenerator, createApiRateLimiter, createBrandCorsOptions, createConfig, createCorsOptions, createDdosRateLimiter, createLogger, createMorganStream, createMultiBrandCorsOptions, createPrefixedKeyGenerator, createRateLimiter, createStandardRateLimiter, createStrictRateLimiter, createUserKeyGenerator, createdResponse, ddosProtectionLimiter, defaultKeyGenerator, disconnectDB, errorResponse, extractColumns, extractOrganization, forbiddenResponse, formatPackageCheckResult, generateNcuCommand, getConnectionStatus, getDatabaseOptions, isDevelopment, isProduction, isTest, logger, noContentResponse, notFoundResponse, omitFields, optionalAuthenticateJWT, packageCheckServer, pickFields, printPackageCheckSummary, rateLimitResponse, rateLimiter, requireOrganization, sanitizeDocument, sanitizeUser, simpleLogger, standardRateLimiter, statusCode, statusMessage, stream, strictRateLimiter, successResponse, successResponseArr, unauthorizedResponse, validationErrorResponse };
|
|
1997
|
+
export { ConfigBuilder, DEFAULT_AUTH_CONFIG, DEFAULT_CORS_CONFIG, DEFAULT_CORS_ORIGINS, DEFAULT_DATABASE_CONFIG, DEFAULT_LOGGING_CONFIG, DEFAULT_RATE_LIMIT_CONFIG, DEFAULT_RATE_LIMIT_TIERS, DEFAULT_SERVER_CONFIG, EXYCONN_CORS_CONFIG, PERMISSIVE_CORS_CONFIG, RATE_LIMIT_CONFIG, RateLimiterBuilder, STRICT_CORS_CONFIG, StatusCode, StatusMessage, authenticateApiKey, authenticateJWT, badRequestResponse, buildConfig, buildDeleteFilter, buildFilter, buildPagination, buildPaginationMeta, checkPackageServer, conflictResponse, connectDB, corsOptions, createApiKeyGenerator, createApiRateLimiter, createBrandCorsOptions, createBulkDeleteHandler, createConfig, createCorsOptions, createCrudControllers, createDdosRateLimiter, createLogger, createMorganStream, createMultiBrandCorsOptions, createPaginationMiddleware, createPrefixedKeyGenerator, createRateLimiter, createStandardRateLimiter, createStrictRateLimiter, createUserKeyGenerator, createdResponse, ddosProtectionLimiter, defaultKeyGenerator, disconnectDB, errorResponse, extractColumns, extractOrganization, extractSchemaMeta, forbiddenResponse, formatPackageCheckResult, generateNcuCommand, getConnectionStatus, getDatabaseOptions, isDevelopment, isProduction, isTest, logger, noContentResponse, notFoundResponse, omitFields, optionalAuthenticateJWT, packageCheckServer, parseBulkDelete, pickFields, printPackageCheckSummary, queryPagination, queryParser, rateLimitResponse, rateLimiter, requireOrganization, sanitizeDocument, sanitizeUser, simpleLogger, standardRateLimiter, statusCode, statusMessage, stream, strictRateLimiter, successResponse, successResponseArr, unauthorizedResponse, validationErrorResponse };
|
|
1375
1998
|
//# sourceMappingURL=index.mjs.map
|
|
1376
1999
|
//# sourceMappingURL=index.mjs.map
|