arkos 1.1.18-test → 1.1.20-test
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/cjs/modules/auth/auth.controller.js +4 -4
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +56 -15
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +4 -7
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js +44 -132
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.controller.helpers.js +2 -0
- package/dist/cjs/modules/base/utils/helpers/base.controller.helpers.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +1 -1
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/features/api.features.js +3 -5
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +1 -3
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/es2020/modules/auth/auth.controller.js +5 -5
- package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
- package/dist/es2020/modules/base/base.controller.js +57 -16
- package/dist/es2020/modules/base/base.controller.js.map +1 -1
- package/dist/es2020/modules/base/base.middlewares.js +4 -7
- package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
- package/dist/es2020/modules/base/base.service.js +44 -132
- package/dist/es2020/modules/base/base.service.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.controller.helpers.js +1 -0
- package/dist/es2020/modules/base/utils/helpers/base.controller.helpers.js.map +1 -1
- package/dist/es2020/types/index.js.map +1 -1
- package/dist/es2020/utils/cli/index.js +1 -1
- package/dist/es2020/utils/cli/index.js.map +1 -1
- package/dist/es2020/utils/features/api.features.js +3 -5
- package/dist/es2020/utils/features/api.features.js.map +1 -1
- package/dist/es2020/utils/helpers/prisma.helpers.js +4 -6
- package/dist/es2020/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/types/modules/base/base.middlewares.d.ts +1 -1
- package/dist/types/modules/base/base.service.d.ts +10 -23
- package/dist/types/modules/base/utils/helpers/base.controller.helpers.d.ts +2 -0
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/utils/features/api.features.d.ts +2 -1
- package/package.json +1 -1
|
@@ -8,8 +8,6 @@ exports.getBaseServices = getBaseServices;
|
|
|
8
8
|
const change_case_helpers_1 = require("../../utils/helpers/change-case.helpers");
|
|
9
9
|
const models_helpers_1 = require("../../utils/helpers/models.helpers");
|
|
10
10
|
const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerge.helper"));
|
|
11
|
-
const app_error_1 = __importDefault(require("../error-handler/utils/app-error"));
|
|
12
|
-
const pluralize_1 = __importDefault(require("pluralize"));
|
|
13
11
|
const base_service_helpers_1 = require("./utils/helpers/base.service.helpers");
|
|
14
12
|
const prisma_helpers_1 = require("../../utils/helpers/prisma.helpers");
|
|
15
13
|
const auth_service_1 = __importDefault(require("../auth/auth.service"));
|
|
@@ -17,159 +15,73 @@ class BaseService {
|
|
|
17
15
|
constructor(modelName) {
|
|
18
16
|
this.modelName = (0, change_case_helpers_1.camelCase)(modelName);
|
|
19
17
|
this.relationFields = (0, models_helpers_1.getPrismaModelRelations)((0, change_case_helpers_1.pascalCase)(modelName));
|
|
20
|
-
this.singularRelationFieldToInclude = this.relationFields?.singular?.reduce((acc, curr) => {
|
|
21
|
-
acc[curr.name] = true;
|
|
22
|
-
return acc;
|
|
23
|
-
}, {});
|
|
24
|
-
this.listRelationFieldToInclude = this.relationFields?.list?.reduce((acc, curr) => {
|
|
25
|
-
acc[curr.name] = true;
|
|
26
|
-
return acc;
|
|
27
|
-
}, {});
|
|
28
18
|
}
|
|
29
|
-
async createOne(
|
|
30
|
-
if ((0, change_case_helpers_1.kebabCase)(this.modelName) === "user" &&
|
|
31
|
-
|
|
19
|
+
async createOne(data, queryOptions) {
|
|
20
|
+
if ((0, change_case_helpers_1.kebabCase)(this.modelName) === "user" && data.password) {
|
|
21
|
+
data.password = await auth_service_1.default.hashPassword(data.password);
|
|
32
22
|
}
|
|
33
23
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
34
|
-
const
|
|
24
|
+
const dataWithRelationFieldsHandled = (0, base_service_helpers_1.handleRelationFieldsInBody)(data, {
|
|
35
25
|
...this.relationFields,
|
|
36
26
|
}, ["delete", "disconnect", "update"]);
|
|
37
27
|
return await prisma[this.modelName].create((0, deepmerge_helper_1.default)({
|
|
38
|
-
data:
|
|
39
|
-
|
|
40
|
-
? {
|
|
41
|
-
select: {
|
|
42
|
-
...this.singularRelationFieldToInclude,
|
|
43
|
-
...this.listRelationFieldToInclude,
|
|
44
|
-
},
|
|
45
|
-
}
|
|
46
|
-
: {
|
|
47
|
-
include: {
|
|
48
|
-
...this.singularRelationFieldToInclude,
|
|
49
|
-
...this.listRelationFieldToInclude,
|
|
50
|
-
},
|
|
51
|
-
}),
|
|
52
|
-
}, JSON.parse(queryOptions || "{}")));
|
|
28
|
+
data: dataWithRelationFieldsHandled,
|
|
29
|
+
}, queryOptions || {}));
|
|
53
30
|
}
|
|
54
|
-
async createMany(
|
|
31
|
+
async createMany(data, queryOptions) {
|
|
55
32
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
56
|
-
|
|
57
|
-
throw new app_error_1.default("Invalid or empty data array provided for creation.", 400);
|
|
58
|
-
}
|
|
59
|
-
const [data, total] = await Promise.all([
|
|
60
|
-
prisma[this.modelName].createMany({
|
|
61
|
-
data: body,
|
|
62
|
-
}),
|
|
63
|
-
prisma[this.modelName].count(),
|
|
64
|
-
]);
|
|
65
|
-
return { total, data };
|
|
33
|
+
return await prisma[this.modelName].createMany((0, deepmerge_helper_1.default)({ data }, queryOptions || {}));
|
|
66
34
|
}
|
|
67
|
-
async
|
|
35
|
+
async count(filters) {
|
|
68
36
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
})
|
|
74
|
-
: (0, deepmerge_helper_1.default)({ ...filters }, {
|
|
75
|
-
include: this.singularRelationFieldToInclude,
|
|
76
|
-
})),
|
|
77
|
-
prisma[this.modelName].count({
|
|
78
|
-
where: filters.where,
|
|
79
|
-
}),
|
|
80
|
-
]);
|
|
81
|
-
return { total, data };
|
|
37
|
+
const where = filters.where || {};
|
|
38
|
+
return await prisma[this.modelName].count({
|
|
39
|
+
where,
|
|
40
|
+
});
|
|
82
41
|
}
|
|
83
|
-
async
|
|
42
|
+
async findMany(filters, queryOptions) {
|
|
84
43
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
85
|
-
|
|
86
|
-
where: { ...filters },
|
|
87
|
-
...(JSON.parse(queryOptions || "{}").hasOwnProperty("select")
|
|
88
|
-
? {
|
|
89
|
-
select: {
|
|
90
|
-
...this.singularRelationFieldToInclude,
|
|
91
|
-
...this.listRelationFieldToInclude,
|
|
92
|
-
},
|
|
93
|
-
}
|
|
94
|
-
: {
|
|
95
|
-
include: {
|
|
96
|
-
...this.singularRelationFieldToInclude,
|
|
97
|
-
...this.listRelationFieldToInclude,
|
|
98
|
-
},
|
|
99
|
-
}),
|
|
100
|
-
}, JSON.parse(queryOptions || "{}")));
|
|
101
|
-
if (!data && Object.keys(filters).length === 1 && "id" in filters)
|
|
102
|
-
throw new app_error_1.default(`${(0, change_case_helpers_1.pascalCase)(String(this.modelName))} with ID ${filters?.id} not found`, 404, {}, "not_found");
|
|
103
|
-
else if (!data)
|
|
104
|
-
throw new app_error_1.default(`${(0, change_case_helpers_1.pascalCase)(String(this.modelName))} not found`, 404, {}, "not_found");
|
|
105
|
-
return data;
|
|
44
|
+
return await prisma[this.modelName].findMany((0, deepmerge_helper_1.default)(filters, queryOptions || {}));
|
|
106
45
|
}
|
|
107
|
-
async
|
|
46
|
+
async findOne(filters, queryOptions) {
|
|
108
47
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
109
|
-
if ((
|
|
110
|
-
|
|
48
|
+
if (Object.keys(filters).length === 1 &&
|
|
49
|
+
"id" in filters &&
|
|
50
|
+
filters.id !== "me")
|
|
51
|
+
return prisma[this.modelName].findUnique((0, deepmerge_helper_1.default)({
|
|
52
|
+
where: filters,
|
|
53
|
+
}, queryOptions || {}));
|
|
54
|
+
return await prisma[this.modelName].findFirst((0, deepmerge_helper_1.default)({
|
|
55
|
+
where: filters,
|
|
56
|
+
}, queryOptions || {}));
|
|
57
|
+
}
|
|
58
|
+
async updateOne(filters, data, queryOptions) {
|
|
59
|
+
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
60
|
+
if ((0, change_case_helpers_1.kebabCase)(this.modelName) === "user" && data.password) {
|
|
61
|
+
data.password = await auth_service_1.default.hashPassword(data.password);
|
|
111
62
|
}
|
|
112
|
-
const
|
|
63
|
+
const dataWithRelationFieldsHandled = (0, base_service_helpers_1.handleRelationFieldsInBody)(data, {
|
|
113
64
|
...this.relationFields,
|
|
114
65
|
});
|
|
115
|
-
|
|
116
|
-
where:
|
|
117
|
-
data:
|
|
118
|
-
|
|
119
|
-
? {
|
|
120
|
-
select: {
|
|
121
|
-
...this.singularRelationFieldToInclude,
|
|
122
|
-
...this.listRelationFieldToInclude,
|
|
123
|
-
},
|
|
124
|
-
}
|
|
125
|
-
: {
|
|
126
|
-
include: {
|
|
127
|
-
...this.singularRelationFieldToInclude,
|
|
128
|
-
...this.listRelationFieldToInclude,
|
|
129
|
-
},
|
|
130
|
-
}),
|
|
131
|
-
}, JSON.parse(queryOptions || "{}")));
|
|
132
|
-
if (!data && Object.keys(filters).length === 1 && "id" in filters)
|
|
133
|
-
throw new app_error_1.default(`${(0, change_case_helpers_1.pascalCase)(String(this.modelName))} with ID ${filters?.id} not found`, 404, {}, "not_found");
|
|
134
|
-
else if (!data)
|
|
135
|
-
throw new app_error_1.default(`${(0, change_case_helpers_1.pascalCase)(String(this.modelName))} not found`, 404, {}, "not_found");
|
|
136
|
-
return data;
|
|
66
|
+
return await prisma[this.modelName].update((0, deepmerge_helper_1.default)({
|
|
67
|
+
where: filters,
|
|
68
|
+
data: dataWithRelationFieldsHandled,
|
|
69
|
+
}, queryOptions || {}));
|
|
137
70
|
}
|
|
138
|
-
async updateMany(filters,
|
|
71
|
+
async updateMany(filters, data, queryOptions) {
|
|
139
72
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
}
|
|
143
|
-
const data = await prisma[this.modelName].updateMany({
|
|
144
|
-
...filters,
|
|
145
|
-
data: body,
|
|
146
|
-
});
|
|
147
|
-
if (!data || data.count === 0) {
|
|
148
|
-
throw new app_error_1.default(`${(0, pluralize_1.default)((0, change_case_helpers_1.pascalCase)(String(this.modelName)))} not found`, 404);
|
|
149
|
-
}
|
|
150
|
-
const total = await prisma[this.modelName].count();
|
|
151
|
-
return { total, data };
|
|
73
|
+
const firstMerge = (0, deepmerge_helper_1.default)({ data }, queryOptions || {});
|
|
74
|
+
return await prisma[this.modelName].updateMany((0, deepmerge_helper_1.default)({ where: filters }, firstMerge));
|
|
152
75
|
}
|
|
153
|
-
async deleteOne(
|
|
76
|
+
async deleteOne(filters, queryOptions) {
|
|
154
77
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
155
|
-
return await prisma[this.modelName].delete({
|
|
156
|
-
where:
|
|
157
|
-
|
|
158
|
-
id: String(params.id),
|
|
159
|
-
},
|
|
160
|
-
});
|
|
78
|
+
return await prisma[this.modelName].delete((0, deepmerge_helper_1.default)({
|
|
79
|
+
where: filters,
|
|
80
|
+
}, queryOptions || {}));
|
|
161
81
|
}
|
|
162
|
-
async deleteMany(filters) {
|
|
82
|
+
async deleteMany(filters, queryOptions = {}) {
|
|
163
83
|
const prisma = (0, prisma_helpers_1.getPrismaInstance)();
|
|
164
|
-
|
|
165
|
-
throw new app_error_1.default("Invalid filters provided for deletion.", 400);
|
|
166
|
-
}
|
|
167
|
-
const data = await prisma[this.modelName].deleteMany(filters);
|
|
168
|
-
if (!data || data.count === 0) {
|
|
169
|
-
throw new app_error_1.default(`No records found to delete`, 404);
|
|
170
|
-
}
|
|
171
|
-
const total = await prisma[this.modelName].count();
|
|
172
|
-
return { total, data };
|
|
84
|
+
return await prisma[this.modelName].deleteMany((0, deepmerge_helper_1.default)(filters, queryOptions || {}));
|
|
173
85
|
}
|
|
174
86
|
}
|
|
175
87
|
exports.BaseService = BaseService;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AA2YA,0CAOC;AAlZD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,iFAAwD;AACxD,0DAAkC;AAClC,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAS/C,MAAa,WAAW;IAmCtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc,GAAG,IAAA,wCAAuB,EAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAE,CAAC;QACtE,IAAI,CAAC,8BAA8B,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,EAAE,MAAM,CACzE,CAAC,GAA4B,EAAE,IAAI,EAAE,EAAE;YACrC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;YACtB,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CACH,CAAC;QACF,IAAI,CAAC,0BAA0B,GAAG,IAAI,CAAC,cAAc,EAAE,IAAI,EAAE,MAAM,CACjE,CAAC,GAA4B,EAAE,IAAI,EAAE,EAAE;YACrC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;YACtB,OAA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AAE,CAAC;QAEnC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,MAAM,IAAI,mBAAQ,CAAC,wCAAwC,EAAE,GAAG,CAAC,CAAC;QACpE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAE9D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,mBAAQ,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAC;QACxD,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;QACnD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACzB,CAAC;CACF;AA5WD,kCA4WC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAgC,EAAE,CAAC;IACrD,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,IAAA,+BAAS,EAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport pluralize from \"pluralize\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n * by model-specific service classes.\n *\n * @class BaseService\n */\nexport class BaseService {\n /**\n * The camelCase name of the model\n * @public\n */\n modelName: string;\n\n /**\n * Object containing singular and list relation fields for the model\n * @public\n */\n relationFields: RelationFields;\n\n /**\n * Map of singular relation fields to include in queries\n * @public\n */\n singularRelationFieldToInclude: Record<string, boolean>;\n\n /**\n * Map of list relation fields to include in queries\n * @public\n */\n listRelationFieldToInclude: Record<string, boolean>;\n\n /**\n * Instance of the Prisma client\n * @public\n */\n prisma: any;\n\n /**\n * Creates an instance of BaseService.\n * @param {string} modelName - The name of the model to perform operations on.\n */\n constructor(modelName: string) {\n this.modelName = camelCase(modelName);\n this.relationFields = getPrismaModelRelations(pascalCase(modelName))!;\n this.singularRelationFieldToInclude = this.relationFields?.singular?.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n );\n this.listRelationFieldToInclude = this.relationFields?.list?.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n );\n }\n /**\n * Creates a single record in the database.\n *\n * @param {Record<string, any>} body - The data to create the record with.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The created record.\n */\n async createOne(\n body: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n if (kebabCase(this.modelName) === \"user\" && body.password) {\n body.password = await authService.hashPassword(body.password);\n }\n\n const prisma = getPrismaInstance();\n\n const bodyWithRelationFieldsHandled = handleRelationFieldsInBody(\n body,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await prisma[this.modelName].create(\n deepmerge(\n {\n data: bodyWithRelationFieldsHandled,\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Record<string, any>[]} body - An array of data to create records with.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the created data.\n * @throws {AppError} Throws an error if the data array is invalid or empty.\n */\n async createMany(\n body: Record<string, any>[]\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!Array.isArray(body) || body.length === 0) {\n throw new AppError(\n \"Invalid or empty data array provided for creation.\",\n 400\n );\n }\n\n const [data, total] = await Promise.all([\n prisma[this.modelName].createMany({\n data: body,\n }),\n prisma[this.modelName].count(),\n ]);\n\n return { total, data };\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Record<string, any>} filters - The filters to apply to the query.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the found data.\n */\n async findMany(\n filters: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n const [data, total] = await Promise.all([\n prisma[this.modelName].findMany(\n \"select\" in filters\n ? deepmerge(\n { ...filters },\n {\n select: this.singularRelationFieldToInclude,\n }\n )\n : deepmerge(\n { ...filters },\n {\n include: this.singularRelationFieldToInclude,\n }\n )\n ),\n prisma[this.modelName].count({\n where: filters.where,\n }),\n ]);\n\n return { total, data };\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Record<string, any>} filters - The parameters to find the record by.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The found record.\n * @throws {AppError} Throws an error if the record is not found.\n */\n async findOne(\n filters: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n const prisma = getPrismaInstance();\n\n const data = await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: { ...filters },\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n\n if (!data && Object.keys(filters).length === 1 && \"id\" in filters)\n throw new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n filters?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n );\n else if (!data)\n throw new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n );\n\n return data;\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Record<string, any>} filters - The parameters to find the record by.\n * @param {Record<string, any>} body - The data to update the record with.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The updated record.\n * @throws {AppError} Throws an error if the record is not found.\n */\n async updateOne(\n filters: Record<string, any>,\n body: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && body.password) {\n body.password = await authService.hashPassword(body.password);\n }\n\n const bodyWithRelationFieldsHandled = handleRelationFieldsInBody(body, {\n ...this.relationFields,\n });\n\n const data = await prisma[this.modelName].update(\n deepmerge(\n {\n where: { ...filters },\n data: bodyWithRelationFieldsHandled,\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n\n if (!data && Object.keys(filters).length === 1 && \"id\" in filters)\n throw new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n filters?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n );\n else if (!data)\n throw new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n );\n\n return data;\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Record<string, any>} filters - The filters to identify records to update.\n * @param {Record<string, any>} body - The data to update the records with.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the updated data.\n * @throws {AppError} Throws an error if no records match the filters.\n */\n async updateMany(\n filters: Record<string, any>,\n body: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!filters || typeof filters !== \"object\") {\n throw new AppError(\"Invalid filters provided for udpate many.\", 400);\n }\n\n const data = await prisma[this.modelName].updateMany({\n ...filters,\n data: body,\n });\n\n if (!data || data.count === 0) {\n throw new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n );\n }\n\n const total = await prisma[this.modelName].count();\n return { total, data };\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Record<string, any>} params - The parameters to find the record by.\n * @returns {Promise<any>} The deleted record.\n */\n async deleteOne(params: Record<string, any>): Promise<any> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: {\n ...params,\n id: String(params.id),\n },\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Record<string, any>} filter - The filter to identify records to delete.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the deleted data.\n * @throws {AppError} Throws an error if no records match the filter.\n */\n async deleteMany(\n filters: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!filters || typeof filters !== \"object\") {\n throw new AppError(\"Invalid filters provided for deletion.\", 400);\n }\n\n const data = await prisma[this.modelName].deleteMany(filters);\n\n if (!data || data.count === 0) {\n throw new AppError(`No records found to delete`, 404);\n }\n\n const total = await prisma[this.modelName].count();\n return { total, data };\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService> {\n const models = getModels();\n const baseServices: Record<string, BaseService> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AA4SA,0CAOC;AAnTD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAsB/C,MAAa,WAAW;IA4BtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc,GAAG,IAAA,wCAAuB,EAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAE,CAAC;IACxE,CAAC;IASD,KAAK,CAAC,SAAS,CACb,IAA6C,EAC7C,YAA4D;QAE5D,IAAI,IAAA,+BAAS,EAAC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC1D,IAAI,CAAC,QAAQ,GAAG,MAAM,sBAAW,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAChE,CAAC;QAED,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,MAAM,6BAA6B,GAAG,IAAA,iDAA0B,EAC9D,IAAI,EACJ;YACE,GAAG,IAAI,CAAC,cAAc;SACvB,EACD,CAAC,QAAQ,EAAE,YAAY,EAAE,QAAQ,CAAC,CACnC,CAAC;QAEF,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CACxC,IAAA,0BAAS,EACP;YACE,IAAI,EAAE,6BAA6B;SACpC,EACA,YAAmB,IAAI,EAAE,CAC3B,CACF,CAAC;IACJ,CAAC;IASD,KAAK,CAAC,UAAU,CACd,IAAiD,EACjD,YAAgE;QAEhE,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,OA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AO;SACf,EACA,YAAmB,IAAI,EAAE,CAC3B,CACF,CAAC;IACJ,CAAC;IASD,KAAK,CAAC,UAAU,CACd,OAA4B,EAC5B,eAA6D,EAAE;QAE/D,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,CAC5C,IAAA,0BAAS,EAAC,OAAO,EAAG,YAAmB,IAAI,EAAE,CAAC,CAC/C,CAAC;IACJ,CAAC;CACF;AAlQD,kCAkQC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAgC,EAAE,CAAC;IACrD,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,IAAA,+BAAS,EAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import prisma from 'your-prisma-path'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n */\nexport class BaseService<\n TModel extends Record<string, (args: Record<string, any>) => any> = Record<\n string,\n any\n >\n> {\n /**\n * The camelCase name of the model\n * @public\n */\n modelName: string;\n\n /**\n * Object containing singular and list relation fields for the model\n * @public\n */\n relationFields: RelationFields;\n\n /**\n * Instance of the Prisma client\n * @public\n */\n prisma: any;\n\n /**\n * Creates an instance of BaseService.\n * @param {string} modelName - The name of the model to perform operations on.\n */\n constructor(modelName: string) {\n this.modelName = camelCase(modelName);\n this.relationFields = getPrismaModelRelations(pascalCase(modelName))!;\n }\n\n /**\n * Creates a single record in the database.\n *\n * @param {Parameters<TModel[\"create\"]>[0][\"data\"]} data - The data to create the record with.\n * @param {Omit<Parameters<TModel[\"create\"]>[0], \"data\">} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<Promise<ReturnType<TModel[\"create\"]>>>} The created record.\n */\n async createOne(\n data: Parameters<TModel[\"create\"]>[0][\"data\"],\n queryOptions?: Omit<Parameters<TModel[\"create\"]>[0], \"data\">\n ): Promise<ReturnType<TModel[\"create\"]>> {\n if (kebabCase(this.modelName) === \"user\" && data.password) {\n data.password = await authService.hashPassword(data.password);\n }\n\n const prisma = getPrismaInstance();\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await prisma[this.modelName].create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n )\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Array<Omit<Parameters<TModel[\"createMany\"]>[0][\"data\"], never>[0]>} data - An array of data to create records with.\n * @param {Omit<Parameters<TModel[\"createMany\"]>[0], \"data\">} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<TModel[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany(\n data: Parameters<TModel[\"createMany\"]>[0][\"data\"],\n queryOptions?: Omit<Parameters<TModel[\"createMany\"]>[0], \"data\">\n ): Promise<ReturnType<TModel[\"createMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].createMany(\n deepmerge({ data }, (queryOptions as {}) || {})\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<TModel[\"count\"]>[0]} filters - The filters to apply to the query.\n * @returns {Promise<number>} The count of records matching the filters.\n */\n async count(filters: Parameters<TModel[\"count\"]>[0]): Promise<number> {\n const prisma = getPrismaInstance();\n\n const where = filters.where || {};\n return await prisma[this.modelName].count({\n where,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<TModel[\"findMany\"]>[0]['where']} filters - The filters to apply to the query.\n * @param {Partial<Parameters<TModel[\"findMany\"]>[0]>} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<TModel[\"findMany\"]>>} The found data.\n */\n async findMany(\n filters: Parameters<TModel[\"findMany\"]>[0][\"where\"],\n queryOptions?: Omit<Partial<Parameters<TModel[\"findMany\"]>[0]>, \"where\">\n ): Promise<ReturnType<TModel[\"findMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].findMany(\n deepmerge(filters, (queryOptions as {}) || {})\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<TModel[\"findFirst\"]>[0][\"where\"] | Parameters<TModel[\"findUnique\"]>[0][\"where\"]} filters - The parameters to find the record by.\n * @param {Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise< ReturnType<TModel[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne(\n filters:\n | Parameters<TModel[\"findFirst\"]>[0][\"where\"]\n | Parameters<TModel[\"findUnique\"]>[0][\"where\"],\n queryOptions?:\n | Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">\n ): Promise<\n ReturnType<TModel[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>\n > {\n const prisma = getPrismaInstance();\n\n if (\n Object.keys(filters).length === 1 &&\n \"id\" in filters &&\n (filters as any).id !== \"me\"\n )\n return prisma[this.modelName].findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n )\n );\n\n return await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n )\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<TModel[\"update\"]>[0][\"where\"]} filters - The parameters to find the record by.\n * @param {Parameters<TModel[\"update\"]>[0][\"data\"]} data - The data to update the record with.\n * @param {Omit<Parameters<TModel[\"update\"]>[0], \"where\" | \"data\">} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<TModel[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne(\n filters: Parameters<TModel[\"update\"]>[0][\"where\"],\n data: Parameters<TModel[\"update\"]>[0][\"data\"],\n queryOptions?: Omit<Parameters<TModel[\"update\"]>[0], \"where\" | \"data\">\n ): Promise<ReturnType<TModel[\"update\"]>> {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && data.password) {\n data.password = await authService.hashPassword(data.password);\n }\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(data, {\n ...this.relationFields,\n });\n\n return await prisma[this.modelName].update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n )\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<TModel[\"updateMany\"]>[0]['where']} filters - The filters to identify records to update.\n * @param {Parameters<TModel[\"updateMany\"]>[0][\"data\"]} data - The data to update the records with.\n * @param {Partial<Parameters<TModel[\"updateMany\"]>[0]>} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<TModel[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany(\n filters: Parameters<TModel[\"updateMany\"]>[0][\"where\"],\n data: Parameters<TModel[\"updateMany\"]>[0][\"data\"],\n queryOptions?: Partial<Parameters<TModel[\"updateMany\"]>[0]>\n ): Promise<ReturnType<TModel[\"updateMany\"]>> {\n const prisma = getPrismaInstance();\n\n const firstMerge = deepmerge({ data }, (queryOptions as {}) || {});\n\n return await prisma[this.modelName].updateMany(\n deepmerge({ where: filters }, firstMerge)\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<TModel[\"delete\"]>[0][\"where\"]} filters - The parameters to find the record by.\n * @param {Omit<Parameters<TModel[\"delete\"]>[0], \"where\">} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<TModel[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<TModel[\"delete\"]>[0][\"where\"],\n queryOptions?: Omit<Parameters<TModel[\"delete\"]>[0], \"where\">\n ): Promise<ReturnType<TModel[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n )\n );\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<TModel[\"deleteMany\"]>[0]['where']} filters - The filter to identify records to delete.\n * @param {Omit<Parameters<TModel[\"deleteMany\"]>[0], \"where\">} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<TModel[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Record<string, any>,\n queryOptions: Partial<Parameters<TModel[\"deleteMany\"]>[0]> = {}\n ): Promise<ReturnType<TModel[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].deleteMany(\n deepmerge(filters, (queryOptions as {}) || {})\n );\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService> {\n const models = getModels();\n const baseServices: Record<string, BaseService> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getAppRoutes = void 0;
|
|
4
|
+
exports.parseAndGetPrismaQueryOptions = parseAndGetPrismaQueryOptions;
|
|
4
5
|
const server_1 = require("../../../../server");
|
|
5
6
|
const getAppRoutes = () => {
|
|
6
7
|
const app = (0, server_1.getExpressApp)();
|
|
@@ -77,4 +78,5 @@ const getAppRoutes = () => {
|
|
|
77
78
|
return routes;
|
|
78
79
|
};
|
|
79
80
|
exports.getAppRoutes = getAppRoutes;
|
|
81
|
+
function parseAndGetPrismaQueryOptions(req) { }
|
|
80
82
|
//# sourceMappingURL=base.controller.helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.controller.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.controller.helpers.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"base.controller.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.controller.helpers.ts"],"names":[],"mappings":";;;AA+FA,sEAAmE;AA/FnE,+CAAmD;AAG5C,MAAM,YAAY,GAAG,GAAG,EAAE;IAC/B,MAAM,GAAG,GAAG,IAAA,sBAAa,GAAE,CAAC;IAC5B,MAAM,MAAM,GAAuC,EAAE,CAAC;IAEtD,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAe,EAAE,EAAE;QAC5C,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC;YAErB,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;gBACvD,MAAM,CAAC,IAAI,CAAC;oBACV,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE;oBAC5B,IAAI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E,MAAM,CAAC,WAAW,EAAE;4BAC5B,IAAI,EAAE,QAAQ;yBACf,CAAC,CAAC;oBACL,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AA1FW,QAAA,YAAY,gBA0FvB;AAEF,SAAgB,6BAA6B,CAAC,GAAiB,IAAG,CAAC","sourcesContent":["import { getExpressApp } from \"../../../../server\";\nimport { ArkosRequest } from \"../../../../types\";\n\nexport const getAppRoutes = () => {\n const app = getExpressApp();\n const routes: { method: string; path: string }[] = [];\n\n app._router.stack.forEach((middleware: any) => {\n if (middleware.route) {\n // Direct routes on the app\n Object.keys(middleware.route.methods).forEach((method) => {\n routes.push({\n method: method.toUpperCase(),\n path: middleware.route.path,\n });\n });\n } else if (middleware.handle && middleware.handle.stack) {\n // Extract the base path from the middleware's regexp pattern\n let basePath = \"\";\n if (middleware.regexp) {\n // Handle pattern like /^\\/api\\/?(?=\\/|$)/i\n const regexpStr = middleware.regexp.toString();\n\n // More robust pattern matching\n if (regexpStr.includes?.(\"/?(?=\")) {\n // Extract everything between the start and the '/?(?=' pattern\n const match = regexpStr.match(/\\/\\^(\\\\\\/[^?]+)/);\n if (match) {\n // Clean up the extracted path\n basePath = match[1].replace(/\\\\\\//g, \"/\");\n }\n } else {\n // Handle other regexp patterns\n const simpleMatch = regexpStr.match(/\\/\\^(\\\\\\/[^\\\\]+)/);\n if (simpleMatch) {\n basePath = simpleMatch[1].replace(/\\\\\\//g, \"/\");\n }\n }\n }\n\n // Process routes in the middleware's router\n middleware.handle.stack.forEach((routerMiddleware: any) => {\n if (routerMiddleware.route) {\n Object.keys(routerMiddleware.route.methods).forEach((method) => {\n let routePath = routerMiddleware.route.path;\n let fullPath;\n\n // Check if routePath already contains regex artifacts\n if (routePath.includes?.(\"/?(?=\")) {\n // Extract the actual path from the regex pattern\n const pathMatch = routePath.match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (pathMatch) {\n const cleanPath = pathMatch[1].replace(/\\\\\\//g, \"/\");\n fullPath = basePath ? basePath + cleanPath : cleanPath;\n } else {\n // If we can't clean it, at least extract what's after '/?(?='\n const fallbackMatch = routePath.match(/\\?\\(\\?=([^)]+)/);\n if (fallbackMatch) {\n fullPath = fallbackMatch[1];\n } else {\n fullPath = routePath; // Use as is if no pattern matches\n }\n }\n } else {\n // Normal path joining\n fullPath = basePath\n ? basePath.replace(/\\/$/, \"\") +\n (routePath.startsWith(\"/\") ? routePath : \"/\" + routePath)\n : routePath;\n }\n\n // Clean up any remaining regex artifacts\n fullPath = fullPath\n .replace(/\\\\\\//g, \"/\")\n .replace(/\\^/g, \"\")\n .replace(/\\$/g, \"\");\n\n // Remove any \"/?(?=\" patterns that might remain\n if (fullPath.includes?.(\"/?(?=\")) {\n fullPath = fullPath.replace(/\\/\\?\\(\\?=[^)]*\\)/g, \"\");\n }\n\n routes.push({\n method: method.toUpperCase(),\n path: fullPath,\n });\n });\n }\n });\n }\n });\n\n return routes;\n};\n\nexport function parseAndGetPrismaQueryOptions(req: ArkosRequest) {}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AAmCA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T extends Record<string, any>> = {\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n create = \"create\",\n view = \"view\",\n update = \"update\",\n delete = \"delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest<Body = any, Query = any> extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n body: Body;\n // query: Query extends Request['ParsedQs'];\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AAmCA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T extends Record<string, any>> = {\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n create = \"create\",\n view = \"view\",\n update = \"update\",\n delete = \"delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest<Body = any, Query = any> extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n body: Body;\n prismaQueryOptions?: Record<string, any>;\n // query: Query extends Request['ParsedQs'];\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
|
|
@@ -20,7 +20,7 @@ function getVersion() {
|
|
|
20
20
|
}
|
|
21
21
|
const program = new commander_1.Command();
|
|
22
22
|
exports.program = program;
|
|
23
|
-
program.name("arkos").description("Arkos
|
|
23
|
+
program.name("arkos").description("Arkos.js CLI").version(getVersion());
|
|
24
24
|
program
|
|
25
25
|
.command("build")
|
|
26
26
|
.description("Build your Arkos project")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/cli/index.ts"],"names":[],"mappings":";;;;;;AAQA,gCAMC;AAbD,yCAAoC;AACpC,mCAAuC;AAwCrB,6FAxCT,oBAAY,OAwCS;AAvC9B,gDAAwB;AACxB,4CAAoB;AACpB,+BAAmC;AAqCH,2FArCvB,gBAAU,OAqCuB;AApC1C,mCAAuC;AAoCK,6FApCnC,oBAAY,OAoCmC;AAlCxD,SAAgB,UAAU;IACxB,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAC5B,YAAE,CAAC,YAAY,CAAC,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,0BAA0B,CAAC,EAAE,MAAM,CAAC,CAC1E,CAAC;IAEF,OAAO,WAAW,CAAC,OAAO,IAAI,OAAO,CAAC;AACxC,CAAC;AAED,MAAM,OAAO,GAAG,IAAI,mBAAO,EAAE,CAAC;AA0BrB,0BAAO;AAxBhB,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/cli/index.ts"],"names":[],"mappings":";;;;;;AAQA,gCAMC;AAbD,yCAAoC;AACpC,mCAAuC;AAwCrB,6FAxCT,oBAAY,OAwCS;AAvC9B,gDAAwB;AACxB,4CAAoB;AACpB,+BAAmC;AAqCH,2FArCvB,gBAAU,OAqCuB;AApC1C,mCAAuC;AAoCK,6FApCnC,oBAAY,OAoCmC;AAlCxD,SAAgB,UAAU;IACxB,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAC5B,YAAE,CAAC,YAAY,CAAC,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,0BAA0B,CAAC,EAAE,MAAM,CAAC,CAC1E,CAAC;IAEF,OAAO,WAAW,CAAC,OAAO,IAAI,OAAO,CAAC;AACxC,CAAC;AAED,MAAM,OAAO,GAAG,IAAI,mBAAO,EAAE,CAAC;AA0BrB,0BAAO;AAxBhB,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;AAExE,OAAO;KACJ,OAAO,CAAC,OAAO,CAAC;KAChB,WAAW,CAAC,0BAA0B,CAAC;KACvC,MAAM,CAAC,qBAAqB,EAAE,0BAA0B,EAAE,KAAK,CAAC;KAChE,MAAM,CAAC,oBAAY,CAAC,CAAC;AAExB,OAAO;KACJ,OAAO,CAAC,KAAK,CAAC;KACd,WAAW,CAAC,wBAAwB,CAAC;KACrC,MAAM,CAAC,qBAAqB,EAAE,aAAa,EAAE,MAAM,CAAC;KACpD,MAAM,CAAC,mBAAmB,EAAE,iBAAiB,EAAE,WAAW,CAAC;KAC3D,MAAM,CAAC,gBAAU,CAAC,CAAC;AAEtB,OAAO;KACJ,OAAO,CAAC,OAAO,CAAC;KAChB,WAAW,CAAC,uBAAuB,CAAC;KACpC,MAAM,CAAC,qBAAqB,EAAE,aAAa,EAAE,MAAM,CAAC;KACpD,MAAM,CAAC,mBAAmB,EAAE,iBAAiB,EAAE,WAAW,CAAC;KAC3D,MAAM,CAAC,oBAAY,CAAC,CAAC;AAExB,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC","sourcesContent":["// src/utils/cli/index.ts\nimport { Command } from \"commander\";\nimport { buildCommand } from \"./build\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { devCommand } from \"./dev\";\nimport { startCommand } from \"./start\";\n\nexport function getVersion() {\n const packageJson = JSON.parse(\n fs.readFileSync(path.join(__dirname, \"../../../../package.json\"), \"utf8\")\n );\n\n return packageJson.version || \"1.0.0\";\n}\n\nconst program = new Command();\n\nprogram.name(\"arkos\").description(\"Arkos.js CLI\").version(getVersion());\n\nprogram\n .command(\"build\")\n .description(\"Build your Arkos project\")\n .option(\"-m, --module <type>\", \"Module type (cjs or esm)\", \"cjs\")\n .action(buildCommand);\n\nprogram\n .command(\"dev\")\n .description(\"Run development server\")\n .option(\"-p, --port <number>\", \"Port number\", \"8000\")\n .option(\"-h, --host <host>\", \"Host to bind to\", \"localhost\")\n .action(devCommand);\n\nprogram\n .command(\"start\")\n .description(\"Run production server\")\n .option(\"-p, --port <number>\", \"Port number\", \"8000\")\n .option(\"-h, --host <host>\", \"Host to bind to\", \"localhost\")\n .action(startCommand);\n\nprogram.parse(process.argv);\n\nexport { program, buildCommand, devCommand, startCommand };\n"]}
|
|
@@ -69,12 +69,10 @@ class APIFeatures {
|
|
|
69
69
|
OR: searchableFields,
|
|
70
70
|
});
|
|
71
71
|
}
|
|
72
|
-
const
|
|
73
|
-
? JSON.parse(this.req.query?.prismaQueryOptions)
|
|
74
|
-
: {};
|
|
75
|
-
this.filters = (0, deepmerge_helper_1.default)({
|
|
72
|
+
const firstMerge = (0, deepmerge_helper_1.default)({
|
|
76
73
|
where: whereOptions,
|
|
77
|
-
},
|
|
74
|
+
}, this.req.prismaQueryOptions || {});
|
|
75
|
+
this.filters = (0, deepmerge_helper_1.default)(firstMerge, this.filters);
|
|
78
76
|
return this;
|
|
79
77
|
}
|
|
80
78
|
search() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.features.js","sourceRoot":"","sources":["../../../../src/utils/features/api.features.ts"],"names":[],"mappings":";;;;;AACA,mFAAoD;AACpD,0EAAgF;AAChF,4FAAmE;AACnE,8DAA8D;AAI9D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CAAC;IACtE,CAAC;CACF;AA5RD,8BA4RC","sourcesContent":["import { Request } from \"express\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { parseQueryParamsWithModifiers } from \"../helpers/api.features.helpers\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { getPrismaInstance } from \"../helpers/prisma.helpers\";\n\ntype ModelName = string;\n\nexport default class APIFeatures {\n req: Request;\n searchParams: any; // The query string parameters from the request\n searchParamsWithModifiers: any; // The query string parameters from the request\n filters: any = {};\n modelName: ModelName;\n relationFields: Record<string, boolean>;\n excludedFields = [\n \"page\",\n \"sort\",\n \"limit\",\n \"fields\",\n \"addFields\",\n \"removeFields\",\n \"search\",\n \"include\",\n \"filterMode\",\n \"where\",\n \"prismaQueryOptions\",\n \"ignoredFields\",\n ];\n\n constructor(\n req: Request,\n modelName: ModelName,\n relationFields?: Record<string, boolean>\n ) {\n this.req = req;\n this.modelName = modelName;\n this.searchParams = parseQueryParamsWithModifiers(req.query);\n this.filters = { ...this.filters };\n\n if (relationFields) this.filters.iclude = relationFields;\n this.relationFields = relationFields || {};\n }\n\n filter() {\n const searchableFields: Record<string, any>[] = [];\n\n const queryObj = { ...this.searchParams };\n\n this.excludedFields.forEach((el) => delete queryObj[el]);\n\n let queryStr = JSON.stringify(queryObj);\n queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, (match) => `${match}`);\n\n const whereObj = { ...this.req.params, ...queryObj };\n const whereLogicalOperatorFilters = Object.keys(whereObj).map((key) => ({\n [key]: whereObj[key],\n }));\n\n let whereOptions =\n whereLogicalOperatorFilters.length > 0\n ? {\n [(this.req.query?.filterMode as string) ?? \"OR\"]:\n whereLogicalOperatorFilters,\n }\n : {};\n\n if (!!this.searchParams.search) {\n const prisma = getPrismaInstance();\n\n Object.keys((prisma as any)[this.modelName].fields).forEach((key) => {\n const field = ((prisma as any)[this.modelName].fields as any)[key];\n if (\n field.typeName === \"String\" &&\n key !== \"id\" &&\n key !== \"password\" &&\n !field.isList &&\n !key?.includes?.(\"Id\") &&\n !key?.includes?.(\"ID\")\n ) {\n searchableFields.push({\n [`${key}`]: {\n contains: this.searchParams.search,\n mode: \"insensitive\",\n },\n });\n }\n });\n\n whereOptions = deepmerge(whereOptions, {\n OR: searchableFields,\n });\n }\n\n const parsedQueryOptions =\n typeof this.req.query?.prismaQueryOptions === \"string\"\n ? JSON.parse(this.req.query?.prismaQueryOptions)\n : {};\n\n this.filters = deepmerge(\n {\n where: whereOptions,\n },\n parsedQueryOptions,\n this.filters\n );\n return this;\n }\n\n search() {\n if (this.searchParams?.search) {\n this.filters = deepmerge(this.filters, {\n where: {\n OR: [],\n },\n });\n }\n }\n\n sort() {\n if (this.searchParams.sort) {\n const sortBy = this.searchParams?.sort\n ?.split(\",\")\n ?.map((field: string) => ({\n [field.startsWith(\"-\") ? field.substring(1) : field]:\n field.startsWith(\"-\") ? \"desc\" : \"asc\",\n }));\n this.filters = deepmerge(this.filters, { orderBy: sortBy });\n }\n\n return this;\n }\n\n // limitFields() {\n // if (\n // this.searchParams?.fields &&\n // !this.searchParams?.addFields &&\n // !this.searchParams?.removeFields\n // ) {\n // const fieldsToSelect = this.searchParams.fields\n // .split(\",\")\n // .filter(\n // (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n // );\n\n // this.filters = {\n // ...this.filters,\n // select: fieldsToSelect.reduce((acc: any, field: string) => {\n // acc[field] = true;\n // return acc;\n // }, {}),\n // };\n // this.filters.select = { ...this.filters.select, ...this.filters.include };\n // delete this.filters.include;\n // } else if (\n // this.searchParams?.fields &&\n // (this.searchParams?.addFields || this.searchParams?.removeFields)\n // )\n // throw new AppError(\n // \"Cannot use fields in the same query with addFields or removeFields.\",\n // 400\n // );\n\n // if (this.searchParams?.addFields && !this.searchParams?.fields) {\n // const fieldsToAdd = this.searchParams.addFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"+\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToAdd.reduce((acc: any, field: string) => {\n // acc[field.replace(\"+\", \"\")] = true;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.fields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use addFields in the same query with fields.\",\n // 400\n // );\n\n // if (this.searchParams?.removeFields && !this.searchParams?.fields) {\n // const fieldsToRemove = this.searchParams.removeFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"-\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToRemove.reduce((acc: any, field: string) => {\n // acc[field.replace(\"-\", \"\")] = false;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.removeFields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use removeFields in the same query with fields.\",\n // 400\n // );\n\n // return this;\n // }\n\n limitFields() {\n if (this.searchParams?.fields) {\n const fields = this.searchParams.fields.split(\",\");\n\n // Separate fields into includes, excludes, and regular fields\n const regularFields = fields.filter(\n (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n );\n const includeFields = fields\n .filter((field: string) => field.startsWith(\"+\"))\n .map((field: string) => field.substring(1));\n const excludeFields = fields\n .filter((field: string) => field.startsWith(\"-\"))\n .map((field: string) => field.substring(1));\n\n // Create selection object based on field type\n let selection: Record<string, any> = {};\n\n // If regular fields exist, use them as the base selection\n if (regularFields.length > 0) {\n selection = regularFields.reduce(\n (acc: Record<string, any>, field: string) => {\n acc[field] = true;\n return acc;\n },\n {} as Record<string, any>\n );\n }\n // Otherwise, use include fields as additions to any existing included fields\n else {\n // Start with current include fields if they exist\n selection = this.filters.include || {};\n\n // Add any explicitly included fields\n includeFields.forEach((field: string) => {\n selection[field] = true;\n });\n\n // Add any explicitly excluded fields\n excludeFields.forEach((field: string) => {\n selection[field] = false;\n });\n }\n\n // Apply the selection to filters\n this.filters = {\n ...this.filters,\n select: selection,\n };\n\n // Remove the include filter as it's now part of select\n if (this.filters.include) {\n delete this.filters.include;\n }\n }\n\n // Remove any references to the now-unused parameters\n if (this.searchParams?.addFields || this.searchParams?.removeFields) {\n throw new AppError(\n \"The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.\",\n 400\n );\n }\n\n return this;\n }\n\n paginate() {\n const page = parseInt(this.searchParams.page, 10) || 1;\n const limit = parseInt(this.searchParams.limit, 10) || 30;\n const skip = (page - 1) * limit;\n\n this.filters = {\n ...this.filters,\n skip,\n take: limit,\n };\n return this;\n }\n\n async exec() {\n const prisma = getPrismaInstance();\n return await (prisma as any)[this.modelName].findMany(this.filters);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"api.features.js","sourceRoot":"","sources":["../../../../src/utils/features/api.features.ts"],"names":[],"mappings":";;;;;AACA,mFAAoD;AACpD,0EAAgF;AAChF,4FAAmE;AACnE,8DAA8D;AAK9D,MAAqB,WAAW;IAsB9B,YACE,GAAY,EACZ,SAAoB,EACpB,cAAwC;QArB1C,YAAO,GAAQ,EAAE,CAAC;QAGlB,mBAAc,GAAG;YACf,MAAM;YACN,MAAM;YACN,OAAO;YACP,QAAQ;YACR,WAAW;YACX,cAAc;YACd,QAAQ;YACR,SAAS;YACT,YAAY;YACZ,OAAO;YACP,oBAAoB;YACpB,eAAe;SAChB,CAAC;QAOA,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,IAAA,oDAA6B,EAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC7D,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAEnC,IAAI,cAAc;YAAE,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,cAAc,CAAC;QACzD,IAAI,CAAC,cAAc,GAAG,cAAc,IAAI,EAAE,CAAC;IAC7C,CAAC;IAED,MAAM;QACJ,MAAM,gBAAgB,GAA0B,EAAE,CAAC;QAEnD,M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,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC;QAC1D,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;QAEhC,IAAI,CAAC,OAAO,GAAG;YACb,GAAG,IAAI,CAAC,OAAO;YACf,IAAI;YACJ,IAAI,EAAE,KAAK;SACZ,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QACnC,OAAO,MAAO,MAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACtE,CAAC;CACF;AAxRD,8BAwRC","sourcesContent":["import { Request } from \"express\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { parseQueryParamsWithModifiers } from \"../helpers/api.features.helpers\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { getPrismaInstance } from \"../helpers/prisma.helpers\";\nimport { ArkosRequest } from \"../../types\";\n\ntype ModelName = string;\n\nexport default class APIFeatures {\n req: ArkosRequest;\n searchParams: any; // The query string parameters from the request\n searchParamsWithModifiers: any; // The query string parameters from the request\n filters: any = {};\n modelName: ModelName;\n relationFields: Record<string, boolean>;\n excludedFields = [\n \"page\",\n \"sort\",\n \"limit\",\n \"fields\",\n \"addFields\",\n \"removeFields\",\n \"search\",\n \"include\",\n \"filterMode\",\n \"where\",\n \"prismaQueryOptions\",\n \"ignoredFields\",\n ];\n\n constructor(\n req: Request,\n modelName: ModelName,\n relationFields?: Record<string, boolean>\n ) {\n this.req = req;\n this.modelName = modelName;\n this.searchParams = parseQueryParamsWithModifiers(req.query);\n this.filters = { ...this.filters };\n\n if (relationFields) this.filters.iclude = relationFields;\n this.relationFields = relationFields || {};\n }\n\n filter() {\n const searchableFields: Record<string, any>[] = [];\n\n const queryObj = { ...this.searchParams };\n\n this.excludedFields.forEach((el) => delete queryObj[el]);\n\n let queryStr = JSON.stringify(queryObj);\n queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, (match) => `${match}`);\n\n const whereObj = { ...this.req.params, ...queryObj };\n const whereLogicalOperatorFilters = Object.keys(whereObj).map((key) => ({\n [key]: whereObj[key],\n }));\n\n let whereOptions =\n whereLogicalOperatorFilters.length > 0\n ? {\n [(this.req.query?.filterMode as string) ?? \"OR\"]:\n whereLogicalOperatorFilters,\n }\n : {};\n\n if (!!this.searchParams.search) {\n const prisma = getPrismaInstance();\n\n Object.keys((prisma as any)[this.modelName].fields).forEach((key) => {\n const field = ((prisma as any)[this.modelName].fields as any)[key];\n if (\n field.typeName === \"String\" &&\n key !== \"id\" &&\n key !== \"password\" &&\n !field.isList &&\n !key?.includes?.(\"Id\") &&\n !key?.includes?.(\"ID\")\n ) {\n searchableFields.push({\n [`${key}`]: {\n contains: this.searchParams.search,\n mode: \"insensitive\",\n },\n });\n }\n });\n\n whereOptions = deepmerge(whereOptions, {\n OR: searchableFields,\n });\n }\n\n const firstMerge = deepmerge(\n {\n where: whereOptions,\n },\n this.req.prismaQueryOptions || {}\n );\n\n this.filters = deepmerge(firstMerge, this.filters);\n return this;\n }\n\n search() {\n if (this.searchParams?.search) {\n this.filters = deepmerge(this.filters, {\n where: {\n OR: [],\n },\n });\n }\n }\n\n sort() {\n if (this.searchParams.sort) {\n const sortBy = this.searchParams?.sort\n ?.split(\",\")\n ?.map((field: string) => ({\n [field.startsWith(\"-\") ? field.substring(1) : field]:\n field.startsWith(\"-\") ? \"desc\" : \"asc\",\n }));\n this.filters = deepmerge(this.filters, { orderBy: sortBy });\n }\n\n return this;\n }\n\n // limitFields() {\n // if (\n // this.searchParams?.fields &&\n // !this.searchParams?.addFields &&\n // !this.searchParams?.removeFields\n // ) {\n // const fieldsToSelect = this.searchParams.fields\n // .split(\",\")\n // .filter(\n // (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n // );\n\n // this.filters = {\n // ...this.filters,\n // select: fieldsToSelect.reduce((acc: any, field: string) => {\n // acc[field] = true;\n // return acc;\n // }, {}),\n // };\n // this.filters.select = { ...this.filters.select, ...this.filters.include };\n // delete this.filters.include;\n // } else if (\n // this.searchParams?.fields &&\n // (this.searchParams?.addFields || this.searchParams?.removeFields)\n // )\n // throw new AppError(\n // \"Cannot use fields in the same query with addFields or removeFields.\",\n // 400\n // );\n\n // if (this.searchParams?.addFields && !this.searchParams?.fields) {\n // const fieldsToAdd = this.searchParams.addFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"+\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToAdd.reduce((acc: any, field: string) => {\n // acc[field.replace(\"+\", \"\")] = true;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.fields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use addFields in the same query with fields.\",\n // 400\n // );\n\n // if (this.searchParams?.removeFields && !this.searchParams?.fields) {\n // const fieldsToRemove = this.searchParams.removeFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"-\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToRemove.reduce((acc: any, field: string) => {\n // acc[field.replace(\"-\", \"\")] = false;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.removeFields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use removeFields in the same query with fields.\",\n // 400\n // );\n\n // return this;\n // }\n\n limitFields() {\n if (this.searchParams?.fields) {\n const fields = this.searchParams.fields.split(\",\");\n\n // Separate fields into includes, excludes, and regular fields\n const regularFields = fields.filter(\n (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n );\n const includeFields = fields\n .filter((field: string) => field.startsWith(\"+\"))\n .map((field: string) => field.substring(1));\n const excludeFields = fields\n .filter((field: string) => field.startsWith(\"-\"))\n .map((field: string) => field.substring(1));\n\n // Create selection object based on field type\n let selection: Record<string, any> = {};\n\n // If regular fields exist, use them as the base selection\n if (regularFields.length > 0) {\n selection = regularFields.reduce(\n (acc: Record<string, any>, field: string) => {\n acc[field] = true;\n return acc;\n },\n {} as Record<string, any>\n );\n }\n // Otherwise, use include fields as additions to any existing included fields\n else {\n // Start with current include fields if they exist\n selection = this.filters.include || {};\n\n // Add any explicitly included fields\n includeFields.forEach((field: string) => {\n selection[field] = true;\n });\n\n // Add any explicitly excluded fields\n excludeFields.forEach((field: string) => {\n selection[field] = false;\n });\n }\n\n // Apply the selection to filters\n this.filters = {\n ...this.filters,\n select: selection,\n };\n\n // Remove the include filter as it's now part of select\n if (this.filters.include) {\n delete this.filters.include;\n }\n }\n\n // Remove any references to the now-unused parameters\n if (this.searchParams?.addFields || this.searchParams?.removeFields) {\n throw new AppError(\n \"The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.\",\n 400\n );\n }\n\n return this;\n }\n\n paginate() {\n const page = parseInt(this.searchParams.page, 10) || 1;\n const limit = parseInt(this.searchParams.limit, 10) || 30;\n const skip = (page - 1) * limit;\n\n this.filters = {\n ...this.filters,\n skip,\n take: limit,\n };\n return this;\n }\n\n async exec() {\n const prisma = getPrismaInstance();\n return await (prisma as any)[this.modelName].findMany(this.filters);\n }\n}\n"]}
|
|
@@ -26,9 +26,7 @@ async function loadPrismaModule() {
|
|
|
26
26
|
}
|
|
27
27
|
catch (error) {
|
|
28
28
|
if (error.message === "Prisma not found")
|
|
29
|
-
throw new app_error_1.default(
|
|
30
|
-
tip: `Make sure your prisma instance is exported under src/utils/prisma.${(0, fs_helpers_1.getUserFileExtension)()} or src/utils/prisma/index.${(0, fs_helpers_1.getUserFileExtension)()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`,
|
|
31
|
-
});
|
|
29
|
+
throw new app_error_1.default(`Could not initialize Prisma module. Make sure your prisma instance is exported under src/utils/prisma.${(0, fs_helpers_1.getUserFileExtension)()} or src/utils/prisma/index.${(0, fs_helpers_1.getUserFileExtension)()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`, 500, {}, "prisma_instance_not_found");
|
|
32
30
|
throw error;
|
|
33
31
|
}
|
|
34
32
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/prisma.helpers.ts"],"names":[],"mappings":";;;;;;AASA,
|
|
1
|
+
{"version":3,"file":"prisma.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/prisma.helpers.ts"],"names":[],"mappings":";;;;;;AASA,4CAyBC;AAED,8CAEC;AAtCD,4CAAoB;AAEpB,gGAAuE;AACvE,4FAAmE;AACnE,6CAAgE;AAChE,qDAAgD;AAErC,QAAA,cAAc,GAAQ,IAAI,CAAC;AAE/B,KAAK,UAAU,gBAAgB;IACpC,IAAI,CAAC,sBAAc,EAAE,CAAC;QACpB,IAAI,CAAC;YACH,IAAI,UAAU,GAAG,GAAG,IAAA,gBAAG,GAAE,qBAAqB,IAAA,iCAAG,GAAE,EAAE,CAAC;YAEtD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC/B,UAAU,GAAG,GAAG,IAAA,gBAAG,GAAE,2BAA2B,IAAA,iCAAG,GAAE,EAAE,CAAC;YAC1D,CAAC;YAED,MAAM,YAAY,GAAG,MAAM,IAAA,6BAAY,EAAC,UAAU,CAAC,CAAC;YACpD,sBAAc,GAAG,YAAY,CAAC,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC;YAE7D,IAAI,CAAC,sBAAc;gBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;QAC3D,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,KAAK,CAAC,OAAO,KAAK,kBAAkB;gBACtC,MAAM,IAAI,mBAAQ,CAChB,yGAAyG,IAAA,iCAAG,GAAE,8BAA8B,IAAA,iCAAG,GAAE,gHAAgH,EACjQ,GAAG,EACH,EAAE,EACF,2BAA2B,CAC5B,CAAC;YACJ,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,sBAAc,CAAC;AACxB,CAAC;AAED,SAAgB,iBAAiB;IAC/B,OAAO,sBAAc,CAAC;AACxB,CAAC;AAEY,QAAA,uBAAuB,GAAG,IAAA,qBAAU,EAC/C,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IACxD,MAAM,MAAM,GAAG,MAAM,gBAAgB,EAAE,CAAC;IACxC,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;QACxB,IAAI,EAAE,CAAC;IACT,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,mBAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IACzC,CAAC;AACH,CAAC,CACF,CAAC","sourcesContent":["import fs from \"fs\";\nimport { Request, Response, NextFunction } from \"express\";\nimport catchAsync from \"../../modules/error-handler/utils/catch-async\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { crd, getUserFileExtension as ext } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaInstance: any = null;\n\nexport async function loadPrismaModule() {\n if (!prismaInstance) {\n try {\n let prismaPath = `${crd()}/src/utils/prisma.${ext()}`;\n\n if (!fs.existsSync(prismaPath)) {\n prismaPath = `${crd()}/src/utils/prisma/index.${ext()}`;\n }\n\n const prismaModule = await importModule(prismaPath);\n prismaInstance = prismaModule.default || prismaModule.prisma;\n\n if (!prismaInstance) throw new Error(\"Prisma not found\");\n } catch (error: any) {\n if (error.message === \"Prisma not found\")\n throw new AppError(\n `Could not initialize Prisma module. Make sure your prisma instance is exported under src/utils/prisma.${ext()} or src/utils/prisma/index.${ext()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`,\n 500,\n {},\n \"prisma_instance_not_found\"\n );\n throw error;\n }\n }\n return prismaInstance;\n}\n\nexport function getPrismaInstance() {\n return prismaInstance;\n}\n\nexport const checkDatabaseConnection = catchAsync(\n async (req: Request, res: Response, next: NextFunction) => {\n const prisma = await loadPrismaModule();\n try {\n await prisma.$connect();\n next();\n } catch (error: any) {\n console.error(\"Database connection error\", error.message);\n next(new AppError(error.message, 503));\n }\n }\n);\n"]}
|
|
@@ -3,7 +3,7 @@ import AppError from "../error-handler/utils/app-error";
|
|
|
3
3
|
import authService from "./auth.service";
|
|
4
4
|
import { getBaseServices } from "../base/base.service";
|
|
5
5
|
import { getPrismaInstance } from "../../utils/helpers/prisma.helpers";
|
|
6
|
-
import { importPrismaModelModules
|
|
6
|
+
import { importPrismaModelModules } from "../../utils/helpers/models.helpers";
|
|
7
7
|
import deepmerge from "../../utils/helpers/deepmerge.helper";
|
|
8
8
|
import arkosEnv from "../../utils/arkos-env";
|
|
9
9
|
import { getArkosConfig } from "../../server";
|
|
@@ -17,10 +17,10 @@ export const authControllerFactory = async (middlewares = {}) => {
|
|
|
17
17
|
const userModules = await importPrismaModelModules("user");
|
|
18
18
|
if (userModules)
|
|
19
19
|
prismaQueryOptions = userModules?.prismaQueryOptions || {};
|
|
20
|
-
const
|
|
20
|
+
const queryOptions = deepmerge(prismaQueryOptions?.queryOptions || {}, prismaQueryOptions?.findOne || {});
|
|
21
21
|
return {
|
|
22
22
|
getMe: catchAsync(async (req, res, next) => {
|
|
23
|
-
const user = await baseServices["user"].findOne({ id: req.user.id }
|
|
23
|
+
const user = await baseServices["user"].findOne({ id: req.user.id });
|
|
24
24
|
Object.keys(defaultExcludedUserFields).forEach((key) => {
|
|
25
25
|
if (user)
|
|
26
26
|
delete user[key];
|
|
@@ -35,7 +35,7 @@ export const authControllerFactory = async (middlewares = {}) => {
|
|
|
35
35
|
updateMe: catchAsync(async (req, res, next) => {
|
|
36
36
|
if ("password" in req.body)
|
|
37
37
|
throw new AppError("In order to update password use the update-password endpoint.", 400);
|
|
38
|
-
const user = await baseServices["user"].updateOne({ id: req.user.id }, req.body
|
|
38
|
+
const user = await baseServices["user"].updateOne({ id: req.user.id }, req.body);
|
|
39
39
|
Object.keys(defaultExcludedUserFields).forEach((key) => {
|
|
40
40
|
if (user)
|
|
41
41
|
delete user[key];
|
|
@@ -131,7 +131,7 @@ export const authControllerFactory = async (middlewares = {}) => {
|
|
|
131
131
|
}),
|
|
132
132
|
signup: catchAsync(async (req, res, next) => {
|
|
133
133
|
const userService = baseServices["user"];
|
|
134
|
-
const user = await userService.createOne(req.body,
|
|
134
|
+
const user = await userService.createOne(req.body, queryOptions);
|
|
135
135
|
if (middlewares?.afterSignup) {
|
|
136
136
|
req.responseData = { data: user };
|
|
137
137
|
req.responseStatus = 201;
|