arkos 1.1.58-test → 1.1.59-beta

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.
@@ -16,7 +16,7 @@ const pluralize_1 = __importDefault(require("pluralize"));
16
16
  class BaseController {
17
17
  constructor(modelName) {
18
18
  this.createOne = (0, catch_async_1.default)(async (req, res, next) => {
19
- const data = await this.baseService.createOne(req.body, req.prismaQueryOptions);
19
+ const data = await this.service.createOne(req.body, req.prismaQueryOptions);
20
20
  if (this.middlewares.afterCreateOne) {
21
21
  req.responseData = { data };
22
22
  req.responseStatus = 201;
@@ -25,7 +25,7 @@ class BaseController {
25
25
  res.status(201).json({ data });
26
26
  });
27
27
  this.createMany = (0, catch_async_1.default)(async (req, res, next) => {
28
- const data = await this.baseService.createMany(req.body, req.prismaQueryOptions);
28
+ const data = await this.service.createMany(req.body, req.prismaQueryOptions);
29
29
  if (!data) {
30
30
  return next(new app_error_1.default("Failed to create the resources. Please check your input.", 400));
31
31
  }
@@ -37,7 +37,7 @@ class BaseController {
37
37
  res.status(201).json({ data });
38
38
  });
39
39
  this.findMany = (0, catch_async_1.default)(async (req, res, next) => {
40
- const { filters: { where, ...queryOptions }, } = new api_features_1.default(req, this.modelName, this.baseService.relationFields?.singular.reduce((acc, curr) => {
40
+ const { filters: { where, ...queryOptions }, } = new api_features_1.default(req, this.modelName, this.service.relationFields?.singular.reduce((acc, curr) => {
41
41
  acc[curr.name] = true;
42
42
  return acc;
43
43
  }, {}))
@@ -46,8 +46,8 @@ class BaseController {
46
46
  .limitFields()
47
47
  .paginate();
48
48
  const [data, total] = await Promise.all([
49
- this.baseService.findMany(where, queryOptions),
50
- this.baseService.count(where),
49
+ this.service.findMany(where, queryOptions),
50
+ this.service.count(where),
51
51
  ]);
52
52
  if (this.middlewares.afterFindMany) {
53
53
  req.responseData = { total, results: data.length, data };
@@ -57,7 +57,7 @@ class BaseController {
57
57
  res.status(200).json({ total, results: data.length, data });
58
58
  });
59
59
  this.findOne = (0, catch_async_1.default)(async (req, res, next) => {
60
- const data = await this.baseService.findOne(req.params, req.prismaQueryOptions);
60
+ const data = await this.service.findOne(req.params, req.prismaQueryOptions);
61
61
  if (!data) {
62
62
  if (Object.keys(req.params).length === 1 &&
63
63
  "id" in req.params &&
@@ -76,7 +76,7 @@ class BaseController {
76
76
  res.status(200).json({ data });
77
77
  });
78
78
  this.updateOne = (0, catch_async_1.default)(async (req, res, next) => {
79
- const data = await this.baseService.updateOne(req.params, req.body, req.prismaQueryOptions);
79
+ const data = await this.service.updateOne(req.params, req.body, req.prismaQueryOptions);
80
80
  if (!data) {
81
81
  if (Object.keys(req.params).length === 1 && "id" in req.params) {
82
82
  return next(new app_error_1.default(`${(0, change_case_helpers_1.pascalCase)(String(this.modelName))} with ID ${req.params?.id} not found`, 404, {}, "not_found"));
@@ -99,7 +99,7 @@ class BaseController {
99
99
  req.query.filterMode = req.query?.filterMode || "AND";
100
100
  const features = new api_features_1.default(req, this.modelName).filter().sort();
101
101
  delete features.filters.include;
102
- const data = await this.baseService.updateMany(features.filters, req.body, req.prismaQueryOptions);
102
+ const data = await this.service.updateMany(features.filters, req.body, req.prismaQueryOptions);
103
103
  if (!data || data.count === 0) {
104
104
  return next(new app_error_1.default(`${(0, pluralize_1.default)((0, change_case_helpers_1.pascalCase)(String(this.modelName)))} not found`, 404));
105
105
  }
@@ -111,7 +111,7 @@ class BaseController {
111
111
  res.status(200).json({ results: data.count, data });
112
112
  });
113
113
  this.deleteOne = (0, catch_async_1.default)(async (req, res, next) => {
114
- const data = await this.baseService.deleteOne(req.params);
114
+ const data = await this.service.deleteOne(req.params);
115
115
  if (!data) {
116
116
  if (Object.keys(req.params).length === 1 && "id" in req.params) {
117
117
  return next(new app_error_1.default(`${(0, change_case_helpers_1.pascalCase)(String(this.modelName))} with ID ${req.params?.id} not found`, 404, {}, "not_found"));
@@ -132,9 +132,8 @@ class BaseController {
132
132
  return next(new app_error_1.default("Filter criteria not provided for bulk deletion.", 400));
133
133
  }
134
134
  req.query.filterMode = req.query?.filterMode || "AND";
135
- const { filters: { where, ...queryOptions }, } = new api_features_1.default(req, this.modelName).filter().sort();
136
- console.log(where, queryOptions);
137
- const data = await this.baseService.deleteMany(where);
135
+ const { filters: { where }, } = new api_features_1.default(req, this.modelName).filter().sort();
136
+ const data = await this.service.deleteMany(where);
138
137
  if (!data || data.count === 0) {
139
138
  return next(new app_error_1.default(`No records found to delete`, 404));
140
139
  }
@@ -146,7 +145,7 @@ class BaseController {
146
145
  res.status(200).json({ results: data.count, data });
147
146
  });
148
147
  this.modelName = modelName;
149
- this.baseService = new base_service_1.BaseService(modelName);
148
+ this.service = new base_service_1.BaseService(modelName);
150
149
  this.middlewares = (0, models_helpers_1.getModelModules)(modelName)?.middlewares || {};
151
150
  }
152
151
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":";;;;;;AA2XA,8CAQC;AAlYD,qFAA4D;AAC5D,qFAA4D;AAC5D,iDAA6C;AAC7C,iFAAwD;AACxD,iFAAgF;AAChF,uEAAgF;AAChF,qFAAuE;AACvE,0DAAkC;AAMlC,MAAa,cAAc;IAuBzB,YAAY,SAAiB;QAa7B,cAAS,GAAG,IAAA,qBAAU,EACpB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,SAAS,CAC3C,GAAG,CAAC,IAAI,EACR,GAAG,CAAC,kBAAkB,CACvB,CAAC;YAEF,IAAI,IAAI,CAAC,WAAW,CAAC,cAAc,EAAE,CAAC;gBACpC,GAAG,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,CAAC;gBAC5B,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,C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CAAC,IAAA,+BAAS,EAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC;KAClE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport APIFeatures from \"../../utils/features/api.features\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport { getModelModules, getModels } from \"../../utils/helpers/models.helpers\";\nimport { getAppRoutes } from \"./utils/helpers/base.controller.helpers\";\nimport pluralize from \"pluralize\";\n\n/**\n * BaseController class providing standardized RESTful API endpoints for any prisma model\n * @class BaseController\n */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private baseService: BaseService;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: string) {\n this.modelName = modelName;\n this.baseService = new BaseService(modelName);\n this.middlewares = getModelModules(modelName)?.middlewares || {};\n }\n\n /**\n * Creates a single resource\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.createOne(\n req.body,\n req.prismaQueryOptions\n );\n\n if (this.middlewares.afterCreateOne) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Creates multiple resources in a single operation\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.createMany(\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n return next(\n new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400\n )\n );\n }\n\n if (this.middlewares.afterCreateMany) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(\n req,\n this.modelName,\n this.baseService.relationFields?.singular.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n )\n )\n .filter()\n .sort()\n .limitFields()\n .paginate();\n\n // Execute both operations separately\n const [data, total] = await Promise.all([\n this.baseService.findMany(where, queryOptions),\n this.baseService.count(where),\n ]);\n\n if (this.middlewares.afterFindMany) {\n req.responseData = { total, results: data.length, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ total, results: data.length, data });\n }\n );\n\n /**\n * Retrieves a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.findOne(\n req.params,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterFindOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.updateOne(\n req.params,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterUpdateOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk update.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const features = new APIFeatures(req, this.modelName).filter().sort();\n delete features.filters.include;\n\n const data = await this.baseService.updateMany(\n features.filters,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data || data.count === 0) {\n return next(\n new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n )\n );\n }\n\n if (this.middlewares.afterUpdateMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n\n /**\n * Deletes a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.deleteOne(req.params);\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterDeleteOne) {\n req.additionalData = { data };\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).send();\n }\n );\n\n /**\n * Deletes multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk deletion.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n console.log(where, queryOptions);\n\n const data = await this.baseService.deleteMany(where);\n\n if (!data || data.count === 0) {\n return next(new AppError(`No records found to delete`, 404));\n }\n\n if (this.middlewares.afterDeleteMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n}\n\n/**\n * Returns a list of all registered API routes in the Express application\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {void}\n */\nexport function getAvalibleRoutes(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n const routes = getAppRoutes();\n\n res.json(routes);\n}\n\n/**\n * Returns a list of all available resource endpoints based on the application's models\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\nexport const getAvailableResources = catchAsync(async (req, res, next) => {\n const models = getModels();\n res.status(200).json({\n data: [...models.map((model) => kebabCase(model)), \"file-upload\"],\n });\n});\n"]}
1
+ {"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":";;;;;;AAkYA,8CAQC;AAzYD,qFAA4D;AAC5D,qFAA4D;AAC5D,iDAA6C;AAC7C,iFAAwD;AACxD,iFAAgF;AAChF,uEAAgF;AAChF,qFAAuE;AACvE,0DAAkC;AAelC,MAAa,cAAc;IAuBzB,YAAY,SAAiB;QAa7B,cAAS,GAAG,IAAA,qBAAU,EACpB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,CACvC,GAAG,CAAC,IAAI,EACR,GAAG,CAAC,kBAAkB,CACvB,CAAC;YAEF,IAAI,IAAI,CAAC,WAAW,CAAC,cAAc,EAAE,CAAC;gBACpC,GAAG,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,CAAC;gBAC5B,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QACjC,CAAC,CACF,CAAC;QASF,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE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CAAC;gBACrC,GAAG,CAAC,YAAY,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;gBACjD,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,CAAC,CACF,CAAC;QAzUA,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,0BAAW,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,WAAW,GAAG,IAAA,gCAAe,EAAC,SAAS,CAAC,EAAE,WAAW,IAAI,EAAE,CAAC;IACnE,CAAC;CAuUF;AAlWD,wCAkWC;AASD,SAAgB,iBAAiB,CAC/B,GAAiB,EACjB,GAAkB,EAClB,IAAuB;IAEvB,MAAM,MAAM,GAAG,IAAA,sCAAY,GAAE,CAAC;IAE9B,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC;AASY,QAAA,qBAAqB,GAAG,IAAA,qBAAU,EAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;IACvE,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,IAAI,EAAE,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAA,+BAAS,EAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC;KAClE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport APIFeatures from \"../../utils/features/api.features\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport { getModelModules, getModels } from \"../../utils/helpers/models.helpers\";\nimport { getAppRoutes } from \"./utils/helpers/base.controller.helpers\";\nimport pluralize from \"pluralize\";\n\n/**\n * BaseController class providing standardized RESTful API endpoints for any prisma model\n * @class BaseController\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-controller-class}\n *\n * **Example:**\n *\n * ```ts\n *\n *\n * ```\n */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private service: BaseService;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: string) {\n this.modelName = modelName;\n this.service = new BaseService(modelName);\n this.middlewares = getModelModules(modelName)?.middlewares || {};\n }\n\n /**\n * Creates a single resource\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createOne(\n req.body,\n req.prismaQueryOptions\n );\n\n if (this.middlewares.afterCreateOne) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Creates multiple resources in a single operation\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createMany(\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n return next(\n new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400\n )\n );\n }\n\n if (this.middlewares.afterCreateMany) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(\n req,\n this.modelName,\n this.service.relationFields?.singular.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n )\n )\n .filter()\n .sort()\n .limitFields()\n .paginate();\n\n // Execute both operations separately\n const [data, total] = await Promise.all([\n this.service.findMany(where, queryOptions),\n this.service.count(where),\n ]);\n\n if (this.middlewares.afterFindMany) {\n req.responseData = { total, results: data.length, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ total, results: data.length, data });\n }\n );\n\n /**\n * Retrieves a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.findOne(\n req.params,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterFindOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.updateOne(\n req.params,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterUpdateOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk update.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const features = new APIFeatures(req, this.modelName).filter().sort();\n delete features.filters.include;\n\n const data = await this.service.updateMany(\n features.filters,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data || data.count === 0) {\n return next(\n new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n )\n );\n }\n\n if (this.middlewares.afterUpdateMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n\n /**\n * Deletes a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.deleteOne(req.params);\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterDeleteOne) {\n req.additionalData = { data };\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).send();\n }\n );\n\n /**\n * Deletes multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk deletion.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n const data = await this.service.deleteMany(where);\n\n if (!data || data.count === 0) {\n return next(new AppError(`No records found to delete`, 404));\n }\n\n if (this.middlewares.afterDeleteMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n}\n\n/**\n * Returns a list of all registered API routes in the Express application\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {void}\n */\nexport function getAvalibleRoutes(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n const routes = getAppRoutes();\n\n res.json(routes);\n}\n\n/**\n * Returns a list of all available resource endpoints based on the application's models\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\nexport const getAvailableResources = catchAsync(async (req, res, next) => {\n const models = getModels();\n res.status(200).json({\n data: [...models.map((model) => kebabCase(model)), \"file-upload\"],\n });\n});\n"]}
@@ -22,7 +22,10 @@ function setupRouters(models, router, arkosConfigs) {
22
22
  const isCompletelyDisabled = disableConfig === true;
23
23
  const customRouter = customRouterModule?.default || {};
24
24
  const hasCustomImplementation = (path, method) => {
25
- return customRouter.stack?.some((layer) => layer.path === `/api/${path}` &&
25
+ return customRouter.stack?.some((layer) => (layer.path === `/api/${path}` ||
26
+ layer.path === `api/${path}` ||
27
+ layer.path === `api/${path}/` ||
28
+ layer.path === `/api/${path}/`) &&
26
29
  layer.method.toLowerCase() === method.toLowerCase());
27
30
  };
28
31
  const isEndpointDisabled = (endpoint) => {
@@ -40,6 +43,8 @@ function setupRouters(models, router, arkosConfigs) {
40
43
  }
41
44
  return undefined;
42
45
  };
46
+ if (customRouterModule?.default && !customRouterModule?.config?.disable)
47
+ router.use(`/${routeName}`, customRouterModule.default);
43
48
  if (!isEndpointDisabled("createOne") &&
44
49
  !hasCustomImplementation(`/${routeName}`, "post")) {
45
50
  router.post(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("create")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "createOne"), middlewares?.beforeCreateOne || controller.createOne, middlewares?.beforeCreateOne
@@ -104,9 +109,6 @@ function setupRouters(models, router, arkosConfigs) {
104
109
  ? middlewares?.afterDeleteOne
105
110
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
106
111
  }
107
- if (customRouterModule?.default && !customRouterModule?.config?.disable) {
108
- router.use(`/${routeName}`, customRouterModule.default);
109
- }
110
112
  });
111
113
  }
112
114
  //# sourceMappingURL=base.router.helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAeA,oCAyVC;AAvWD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAEhC,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,MAAM,SAAS,GAAG,IAAA,kBAAM,EAAC,gBAAgB,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,IAAI,gCAAc,CAAC,KAAK,CAAC,CAAC;QAG7C,MAAM,YAAY,GAAiB,kBAAkB,EAAE,MAAM,CAAC;QAC9D,MAAM,aAAa,GAAG,YAAY,EAAE,OAAO,IAAI,EAAE,CAAC;QAClD,MAAM,oBAAoB,GAAG,aAAa,KAAK,IAAI,CAAC;QAGpD,MAAM,YAAY,GAAI,kBAAkB,EAAE,OAAkB,IAAI,EAAE,CAAC;QACnE,MAAM,uBAAuB,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,EAAE;YAC/D,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAC7B,CAAC,KAAK,EAAE,EAA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":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n // console.log(JSON.stringify(customRouterModule, null, 2));\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n // console.log(JSON.stringify(customRouterModule.defaull, null, 2));\n router.use(`/${routeName}`, customRouterModule.default);\n // customRouter.stack.forEach((layer) => {\n // if (layer.route) {\n // const route = layer.route;\n // const path = route.path;\n\n // route.stack.forEach((routeLayer) => {\n // const method = routeLayer.method.toLowerCase() as any;\n\n // // Get all middleware handlers for this route\n // const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // // Apply all middleware handlers to the matching route method\n // (router as any)[method](`/${routeName}/${path}`, ...handlers);\n // });\n // }\n // });\n }\n });\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAeA,oCA0UC;AAxVD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAq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B,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,+BAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;QACJ,CAAC;QAGD,IACE,CAAC,kBAAkB,CAAC,WAAW,CAAC;YAChC,CAAC,uBAAuB,CAAC,IAAI,SAAS,MAAM,EAAE,QAAQ,CAAC,EACvD,CAAC;YACD,MAAM,CAAC,MAAM,CACX,IAAI,SAAS,MAAM,EACnB,sBAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,EAAE,qBAAqB,CACnC,EACD,sBAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,IAAA,iBAAS,EAAC,IAAA,oBAAQ,EAAC,gBAAgB,CAAC,CAAC,EACrC,WAAW,EAAE,aAAa,IAAI,EAAE,CACjC,EACD,IAAA,+DAA4C,EAC1C,wBAAwB,CAAC,QAAQ,CAAC,CACnC,EACD,IAAA,iDAA8B,EAC5B,kBAA6C,EAC7C,WAAW,CACZ,EACD,WAAW,EAAE,eAAe,IAAI,UAAU,CAAC,SAAS,EACpD,WAAW,EAAE,eAAe;gBAC1B,CAAC,CAAC,UAAU,CAAC,SAAS;gBACtB,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,+BAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable)\n router.use(`/${routeName}`, customRouterModule.default);\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAiFA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAtFxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;AAElB,IAAI,YAAY,GAA0C;IACxD,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,C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,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(port, _arkosConfig.host!, () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://localhost:${port}`\n );\n // console.info(\n // `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n // );\n // if (!!process.env.NODE_ENV)\n // console.info(`${`Environment: ${process.env.NODE_ENV}`}`);\n });\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AA4EA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAjFxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH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AO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(port, _arkosConfig.host!, () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://localhost:${port}`\n );\n });\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers](https://https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers)\n */\nexport type RouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [ttps://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers](https://ttps://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n foreignKey?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | RouterEndpoint | RouterEndpoint[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
1
+ {"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [https://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers](https://https://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers)\n */\nexport type RouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [ttps://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers](https://ttps://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n foreignKeyField?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | RouterEndpoint[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
@@ -9,7 +9,7 @@ import pluralize from "pluralize";
9
9
  export class BaseController {
10
10
  constructor(modelName) {
11
11
  this.createOne = catchAsync(async (req, res, next) => {
12
- const data = await this.baseService.createOne(req.body, req.prismaQueryOptions);
12
+ const data = await this.service.createOne(req.body, req.prismaQueryOptions);
13
13
  if (this.middlewares.afterCreateOne) {
14
14
  req.responseData = { data };
15
15
  req.responseStatus = 201;
@@ -18,7 +18,7 @@ export class BaseController {
18
18
  res.status(201).json({ data });
19
19
  });
20
20
  this.createMany = catchAsync(async (req, res, next) => {
21
- const data = await this.baseService.createMany(req.body, req.prismaQueryOptions);
21
+ const data = await this.service.createMany(req.body, req.prismaQueryOptions);
22
22
  if (!data) {
23
23
  return next(new AppError("Failed to create the resources. Please check your input.", 400));
24
24
  }
@@ -30,7 +30,7 @@ export class BaseController {
30
30
  res.status(201).json({ data });
31
31
  });
32
32
  this.findMany = catchAsync(async (req, res, next) => {
33
- const { filters: { where, ...queryOptions }, } = new APIFeatures(req, this.modelName, this.baseService.relationFields?.singular.reduce((acc, curr) => {
33
+ const { filters: { where, ...queryOptions }, } = new APIFeatures(req, this.modelName, this.service.relationFields?.singular.reduce((acc, curr) => {
34
34
  acc[curr.name] = true;
35
35
  return acc;
36
36
  }, {}))
@@ -39,8 +39,8 @@ export class BaseController {
39
39
  .limitFields()
40
40
  .paginate();
41
41
  const [data, total] = await Promise.all([
42
- this.baseService.findMany(where, queryOptions),
43
- this.baseService.count(where),
42
+ this.service.findMany(where, queryOptions),
43
+ this.service.count(where),
44
44
  ]);
45
45
  if (this.middlewares.afterFindMany) {
46
46
  req.responseData = { total, results: data.length, data };
@@ -50,7 +50,7 @@ export class BaseController {
50
50
  res.status(200).json({ total, results: data.length, data });
51
51
  });
52
52
  this.findOne = catchAsync(async (req, res, next) => {
53
- const data = await this.baseService.findOne(req.params, req.prismaQueryOptions);
53
+ const data = await this.service.findOne(req.params, req.prismaQueryOptions);
54
54
  if (!data) {
55
55
  if (Object.keys(req.params).length === 1 &&
56
56
  "id" in req.params &&
@@ -69,7 +69,7 @@ export class BaseController {
69
69
  res.status(200).json({ data });
70
70
  });
71
71
  this.updateOne = catchAsync(async (req, res, next) => {
72
- const data = await this.baseService.updateOne(req.params, req.body, req.prismaQueryOptions);
72
+ const data = await this.service.updateOne(req.params, req.body, req.prismaQueryOptions);
73
73
  if (!data) {
74
74
  if (Object.keys(req.params).length === 1 && "id" in req.params) {
75
75
  return next(new AppError(`${pascalCase(String(this.modelName))} with ID ${req.params?.id} not found`, 404, {}, "not_found"));
@@ -92,7 +92,7 @@ export class BaseController {
92
92
  req.query.filterMode = req.query?.filterMode || "AND";
93
93
  const features = new APIFeatures(req, this.modelName).filter().sort();
94
94
  delete features.filters.include;
95
- const data = await this.baseService.updateMany(features.filters, req.body, req.prismaQueryOptions);
95
+ const data = await this.service.updateMany(features.filters, req.body, req.prismaQueryOptions);
96
96
  if (!data || data.count === 0) {
97
97
  return next(new AppError(`${pluralize(pascalCase(String(this.modelName)))} not found`, 404));
98
98
  }
@@ -104,7 +104,7 @@ export class BaseController {
104
104
  res.status(200).json({ results: data.count, data });
105
105
  });
106
106
  this.deleteOne = catchAsync(async (req, res, next) => {
107
- const data = await this.baseService.deleteOne(req.params);
107
+ const data = await this.service.deleteOne(req.params);
108
108
  if (!data) {
109
109
  if (Object.keys(req.params).length === 1 && "id" in req.params) {
110
110
  return next(new AppError(`${pascalCase(String(this.modelName))} with ID ${req.params?.id} not found`, 404, {}, "not_found"));
@@ -125,9 +125,8 @@ export class BaseController {
125
125
  return next(new AppError("Filter criteria not provided for bulk deletion.", 400));
126
126
  }
127
127
  req.query.filterMode = req.query?.filterMode || "AND";
128
- const { filters: { where, ...queryOptions }, } = new APIFeatures(req, this.modelName).filter().sort();
129
- console.log(where, queryOptions);
130
- const data = await this.baseService.deleteMany(where);
128
+ const { filters: { where }, } = new APIFeatures(req, this.modelName).filter().sort();
129
+ const data = await this.service.deleteMany(where);
131
130
  if (!data || data.count === 0) {
132
131
  return next(new AppError(`No records found to delete`, 404));
133
132
  }
@@ -139,7 +138,7 @@ export class BaseController {
139
138
  res.status(200).json({ results: data.count, data });
140
139
  });
141
140
  this.modelName = modelName;
142
- this.baseService = new BaseService(modelName);
141
+ this.service = new BaseService(modelName);
143
142
  this.middlewares = getModelModules(modelName)?.middlewares || {};
144
143
  }
145
144
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":"AACA,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,WAAW,MAAM,mCAAmC,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,yCAAyC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,MAAM,yCAAyC,CAAC;AACvE,OAAO,SAAS,MAAM,WAAW,CAAC;AAMlC,MAAM,OAAO,cAAc;IAuBzB,YAAY,SAAiB;QAa7B,cAAS,GAAG,UAAU,CACpB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,SAAS,CAC3C,GAAG,CAAC,IAAI,EACR,GAAG,CAAC,kBAAkB,CACvB,CAAC;YAEF,IAAI,IAAI,CAAC,WAAW,CAAC,cAAc,EAAE,CAAC;gBACpC,GAAG,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,CAAC;gBAC5B,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAA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,IAAI,CAAC,WAAW,CAAC,eAAe,EAAE,CAAC;gBACrC,GAAG,CAAC,YAAY,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;gBACjD,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,CAAC,CACF,CAAC;QA3UA,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,WAAW,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,SAAS,CAAC,EAAE,WAAW,IAAI,EAAE,CAAC;IACnE,CAAC;CAyUF;AASD,MAAM,UAAU,iBAAiB,CAC/B,GAAiB,EACjB,GAAkB,EAClB,IAAuB;IAEvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAE9B,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC;AASD,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;IACvE,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,IAAI,EAAE,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC;KAClE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport APIFeatures from \"../../utils/features/api.features\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport { getModelModules, getModels } from \"../../utils/helpers/models.helpers\";\nimport { getAppRoutes } from \"./utils/helpers/base.controller.helpers\";\nimport pluralize from \"pluralize\";\n\n/**\n * BaseController class providing standardized RESTful API endpoints for any prisma model\n * @class BaseController\n */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private baseService: BaseService;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: string) {\n this.modelName = modelName;\n this.baseService = new BaseService(modelName);\n this.middlewares = getModelModules(modelName)?.middlewares || {};\n }\n\n /**\n * Creates a single resource\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.createOne(\n req.body,\n req.prismaQueryOptions\n );\n\n if (this.middlewares.afterCreateOne) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Creates multiple resources in a single operation\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.createMany(\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n return next(\n new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400\n )\n );\n }\n\n if (this.middlewares.afterCreateMany) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(\n req,\n this.modelName,\n this.baseService.relationFields?.singular.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n )\n )\n .filter()\n .sort()\n .limitFields()\n .paginate();\n\n // Execute both operations separately\n const [data, total] = await Promise.all([\n this.baseService.findMany(where, queryOptions),\n this.baseService.count(where),\n ]);\n\n if (this.middlewares.afterFindMany) {\n req.responseData = { total, results: data.length, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ total, results: data.length, data });\n }\n );\n\n /**\n * Retrieves a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.findOne(\n req.params,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterFindOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.updateOne(\n req.params,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterUpdateOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk update.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const features = new APIFeatures(req, this.modelName).filter().sort();\n delete features.filters.include;\n\n const data = await this.baseService.updateMany(\n features.filters,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data || data.count === 0) {\n return next(\n new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n )\n );\n }\n\n if (this.middlewares.afterUpdateMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n\n /**\n * Deletes a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.baseService.deleteOne(req.params);\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterDeleteOne) {\n req.additionalData = { data };\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).send();\n }\n );\n\n /**\n * Deletes multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk deletion.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n console.log(where, queryOptions);\n\n const data = await this.baseService.deleteMany(where);\n\n if (!data || data.count === 0) {\n return next(new AppError(`No records found to delete`, 404));\n }\n\n if (this.middlewares.afterDeleteMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n}\n\n/**\n * Returns a list of all registered API routes in the Express application\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {void}\n */\nexport function getAvalibleRoutes(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n const routes = getAppRoutes();\n\n res.json(routes);\n}\n\n/**\n * Returns a list of all available resource endpoints based on the application's models\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\nexport const getAvailableResources = catchAsync(async (req, res, next) => {\n const models = getModels();\n res.status(200).json({\n data: [...models.map((model) => kebabCase(model)), \"file-upload\"],\n });\n});\n"]}
1
+ {"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":"AACA,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,WAAW,MAAM,mCAAmC,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,yCAAyC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,MAAM,yCAAyC,CAAC;AACvE,OAAO,SAAS,MAAM,WAAW,CAAC;AAelC,MAAM,OAAO,cAAc;IAuBzB,YAAY,SAAiB;QAa7B,cAAS,GAAG,UAAU,CACpB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,CACvC,GAAG,CAAC,IAAI,EACR,GAAG,CAAC,kBAAkB,CACvB,CAAC;YAEF,IAAI,IAAI,CAAC,WAAW,CAAC,cAAc,EAAE,CAAC;gBACpC,GAAG,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,CAAC;gBAC5B,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QACjC,CAAC,CACF,CAAC;QASF,e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,EAAE,CAAC;gBACjD,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,CAAC,CACF,CAAC;QAzUA,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,WAAW,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,SAAS,CAAC,EAAE,WAAW,IAAI,EAAE,CAAC;IACnE,CAAC;CAuUF;AASD,MAAM,UAAU,iBAAiB,CAC/B,GAAiB,EACjB,GAAkB,EAClB,IAAuB;IAEvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAE9B,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC;AASD,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;IACvE,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,IAAI,EAAE,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC;KAClE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport APIFeatures from \"../../utils/features/api.features\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport { getModelModules, getModels } from \"../../utils/helpers/models.helpers\";\nimport { getAppRoutes } from \"./utils/helpers/base.controller.helpers\";\nimport pluralize from \"pluralize\";\n\n/**\n * BaseController class providing standardized RESTful API endpoints for any prisma model\n * @class BaseController\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-controller-class}\n *\n * **Example:**\n *\n * ```ts\n *\n *\n * ```\n */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private service: BaseService;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: string) {\n this.modelName = modelName;\n this.service = new BaseService(modelName);\n this.middlewares = getModelModules(modelName)?.middlewares || {};\n }\n\n /**\n * Creates a single resource\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createOne(\n req.body,\n req.prismaQueryOptions\n );\n\n if (this.middlewares.afterCreateOne) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Creates multiple resources in a single operation\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createMany(\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n return next(\n new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400\n )\n );\n }\n\n if (this.middlewares.afterCreateMany) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(\n req,\n this.modelName,\n this.service.relationFields?.singular.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n )\n )\n .filter()\n .sort()\n .limitFields()\n .paginate();\n\n // Execute both operations separately\n const [data, total] = await Promise.all([\n this.service.findMany(where, queryOptions),\n this.service.count(where),\n ]);\n\n if (this.middlewares.afterFindMany) {\n req.responseData = { total, results: data.length, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ total, results: data.length, data });\n }\n );\n\n /**\n * Retrieves a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.findOne(\n req.params,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterFindOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.updateOne(\n req.params,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterUpdateOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk update.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const features = new APIFeatures(req, this.modelName).filter().sort();\n delete features.filters.include;\n\n const data = await this.service.updateMany(\n features.filters,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data || data.count === 0) {\n return next(\n new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n )\n );\n }\n\n if (this.middlewares.afterUpdateMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n\n /**\n * Deletes a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.deleteOne(req.params);\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterDeleteOne) {\n req.additionalData = { data };\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).send();\n }\n );\n\n /**\n * Deletes multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk deletion.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n const data = await this.service.deleteMany(where);\n\n if (!data || data.count === 0) {\n return next(new AppError(`No records found to delete`, 404));\n }\n\n if (this.middlewares.afterDeleteMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n}\n\n/**\n * Returns a list of all registered API routes in the Express application\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {void}\n */\nexport function getAvalibleRoutes(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n const routes = getAppRoutes();\n\n res.json(routes);\n}\n\n/**\n * Returns a list of all available resource endpoints based on the application's models\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\nexport const getAvailableResources = catchAsync(async (req, res, next) => {\n const models = getModels();\n res.status(200).json({\n data: [...models.map((model) => kebabCase(model)), \"file-upload\"],\n });\n});\n"]}
@@ -16,7 +16,10 @@ export function setupRouters(models, router, arkosConfigs) {
16
16
  const isCompletelyDisabled = disableConfig === true;
17
17
  const customRouter = customRouterModule?.default || {};
18
18
  const hasCustomImplementation = (path, method) => {
19
- return customRouter.stack?.some((layer) => layer.path === `/api/${path}` &&
19
+ return customRouter.stack?.some((layer) => (layer.path === `/api/${path}` ||
20
+ layer.path === `api/${path}` ||
21
+ layer.path === `api/${path}/` ||
22
+ layer.path === `/api/${path}/`) &&
20
23
  layer.method.toLowerCase() === method.toLowerCase());
21
24
  };
22
25
  const isEndpointDisabled = (endpoint) => {
@@ -34,6 +37,8 @@ export function setupRouters(models, router, arkosConfigs) {
34
37
  }
35
38
  return undefined;
36
39
  };
40
+ if (customRouterModule?.default && !customRouterModule?.config?.disable)
41
+ router.use(`/${routeName}`, customRouterModule.default);
37
42
  if (!isEndpointDisabled("createOne") &&
38
43
  !hasCustomImplementation(`/${routeName}`, "post")) {
39
44
  router.post(`/${routeName}`, authService.handleAuthenticationControl("Create", authConfigs?.authenticationControl), authService.handleAccessControl("Create", kebabCase(singular(modelNameInKebab)), authConfigs?.accessControl || {}), handleRequestBodyValidationAndTransformation(getValidationSchemaOrDto("create")), addPrismaQueryOptionsToRequest(prismaQueryOptions, "createOne"), middlewares?.beforeCreateOne || controller.createOne, middlewares?.beforeCreateOne
@@ -98,9 +103,6 @@ export function setupRouters(models, router, arkosConfigs) {
98
103
  ? middlewares?.afterDeleteOne
99
104
  : sendResponse, sendResponse);
100
105
  }
101
- if (customRouterModule?.default && !customRouterModule?.config?.disable) {
102
- router.use(`/${routeName}`, customRouterModule.default);
103
- }
104
106
  });
105
107
  }
106
108
  //# sourceMappingURL=base.router.helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/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C,WAAW,CAAC;YAChC,CAAC,uBAAuB,CAAC,IAAI,SAAS,MAAM,EAAE,QAAQ,CAAC,EACvD,CAAC;YACD,MAAM,CAAC,MAAM,CACX,IAAI,SAAS,MAAM,EACnB,WAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,EAAE,qBAAqB,CACnC,EACD,WAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC,EACrC,WAAW,EAAE,aAAa,IAAI,EAAE,CACjC,EACD,4CAA4C,CAC1C,wBAAwB,CAAC,QAAQ,CAAC,CACnC,EACD,8BAA8B,CAC5B,kBAA6C,EAC7C,WAAW,CACZ,EACD,WAAW,EAAE,eAAe,IAAI,UAAU,CAAC,SAAS,EACpD,WAAW,EAAE,eAAe;gBAC1B,CAAC,CAAC,UAAU,CAAC,SAAS;gBACtB,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,YAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,YAAY,EAChB,YAAY,CACb,CAAC;QACJ,CAAC;QAGD,IAAI,kBAAkB,EAAE,OAAO,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAExE,MAAM,CAAC,GAAG,CAAC,IAAI,SAAS,EAAE,EAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;QAiB1D,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n // console.log(JSON.stringify(customRouterModule, null, 2));\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n // console.log(JSON.stringify(customRouterModule.defaull, null, 2));\n router.use(`/${routeName}`, customRouterModule.default);\n // customRouter.stack.forEach((layer) => {\n // if (layer.route) {\n // const route = layer.route;\n // const path = route.path;\n\n // route.stack.forEach((routeLayer) => {\n // const method = routeLayer.method.toLowerCase() as any;\n\n // // Get all middleware handlers for this route\n // const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // // Apply all middleware handlers to the matching route method\n // (router as any)[method](`/${routeName}/${path}`, ...handlers);\n // });\n // }\n // });\n }\n });\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAGtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,wBAAwB,CA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IAAI,SAAS,MAAM,EAAE,QAAQ,CAAC,EACvD,CAAC;YACD,MAAM,CAAC,MAAM,CACX,IAAI,SAAS,MAAM,EACnB,WAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,EAAE,qBAAqB,CACnC,EACD,WAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC,EACrC,WAAW,EAAE,aAAa,IAAI,EAAE,CACjC,EACD,4CAA4C,CAC1C,wBAAwB,CAAC,QAAQ,CAAC,CACnC,EACD,8BAA8B,CAC5B,kBAA6C,EAC7C,WAAW,CACZ,EACD,WAAW,EAAE,eAAe,IAAI,UAAU,CAAC,SAAS,EACpD,WAAW,EAAE,eAAe;gBAC1B,CAAC,CAAC,UAAU,CAAC,SAAS;gBACtB,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,YAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,YAAY,EAChB,YAAY,CACb,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable)\n router.use(`/${routeName}`, customRouterModule.default);\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;AAElB,IAAI,YAAY,GAA0C;IACxD,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;IACtE,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,WAAW;IAC7D,UAAU,EAAE;QACV,aAAa,EAAE,SAAS;QACxB,SAAS,EAAE,cA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,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(port, _arkosConfig.host!, () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://localhost:${port}`\n );\n // console.info(\n // `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n // );\n // if (!!process.env.NODE_ENV)\n // console.info(`${`Environment: ${process.env.NODE_ENV}`}`);\n });\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;AAElB,IAAI,YAAY,GAA0C;IACxD,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,C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C,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(port, _arkosConfig.host!, () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://localhost:${port}`\n );\n });\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers](https://https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers)\n */\nexport type RouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [ttps://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers](https://ttps://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n foreignKey?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | RouterEndpoint | RouterEndpoint[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
1
+ {"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [https://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers](https://https://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers)\n */\nexport type RouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [ttps://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers](https://ttps://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n foreignKeyField?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | RouterEndpoint[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  import { ArkosRequest, ArkosResponse, ArkosNextFunction } from "../../types";
2
2
  export declare class BaseController {
3
- private baseService;
3
+ private service;
4
4
  private modelName;
5
5
  private middlewares;
6
6
  constructor(modelName: string);
@@ -2,8 +2,8 @@ export type RouterEndpoint = "createOne" | "findOne" | "updateOne" | "deleteOne"
2
2
  export type RouterConfig = {
3
3
  parent?: {
4
4
  model?: string;
5
- foreignKey?: string;
6
- endpoints?: "*" | RouterEndpoint | RouterEndpoint[];
5
+ foreignKeyField?: string;
6
+ endpoints?: "*" | RouterEndpoint[];
7
7
  };
8
8
  disable?: boolean | {
9
9
  createOne?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkos",
3
- "version": "1.1.58-test",
3
+ "version": "1.1.59-beta",
4
4
  "description": "The Express & Prisma Framework For RESTful API",
5
5
  "main": "dist/cjs/exports/index.js",
6
6
  "module": "dist/es2020/exports/index.js",