arkos 1.0.19-beta → 1.0.20-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.
- package/dist/cjs/app.js +1 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/exports/middlewares/index.js +7 -0
- package/dist/cjs/exports/middlewares/index.js.map +1 -0
- package/dist/cjs/modules/auth/auth.controller.js +31 -26
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/auth/auth.router.js +4 -5
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +27 -24
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js +4 -4
- package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +2 -29
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +37 -1
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/base.router.js +2 -2
- package/dist/cjs/modules/base/base.router.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +2 -3
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js +9 -11
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +2 -0
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/catch-async.js +1 -1
- package/dist/cjs/modules/error-handler/utils/catch-async.js.map +1 -1
- package/dist/cjs/modules/file-uploader/file-uploader.service.js +4 -4
- package/dist/cjs/modules/file-uploader/file-uploader.service.js.map +1 -1
- package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js +7 -5
- package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +1 -1
- package/dist/cjs/server.js +1 -1
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/types/auth.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/utils/features/api.features.js +3 -2
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/api.features.helpers.js +4 -4
- package/dist/cjs/utils/helpers/api.features.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/base.controller.helpers.js +77 -35
- package/dist/cjs/utils/helpers/base.controller.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/change-case.helpers.js +3 -3
- package/dist/cjs/utils/helpers/change-case.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +35 -30
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/scripts/generate-insomnia-collection.js +228 -0
- package/dist/cjs/utils/scripts/generate-insomnia-collection.js.map +1 -0
- package/dist/cjs/utils/scripts/index.js +12 -0
- package/dist/cjs/utils/scripts/index.js.map +1 -0
- package/dist/es2020/app.js +1 -1
- package/dist/es2020/app.js.map +1 -1
- package/dist/es2020/exports/middlewares/index.js +2 -0
- package/dist/es2020/exports/middlewares/index.js.map +1 -0
- package/dist/es2020/modules/auth/auth.controller.js +32 -27
- package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
- package/dist/es2020/modules/auth/auth.router.js +1 -2
- package/dist/es2020/modules/auth/auth.router.js.map +1 -1
- package/dist/es2020/modules/auth/auth.service.js +27 -24
- package/dist/es2020/modules/auth/auth.service.js.map +1 -1
- package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js +4 -4
- package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -1
- package/dist/es2020/modules/base/base.controller.js +2 -29
- package/dist/es2020/modules/base/base.controller.js.map +1 -1
- package/dist/es2020/modules/base/base.middlewares.js +33 -1
- package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
- package/dist/es2020/modules/base/base.router.js +2 -2
- package/dist/es2020/modules/base/base.router.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +1 -2
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js +9 -11
- package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/es2020/modules/error-handler/error-handler.controller.js +2 -0
- package/dist/es2020/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/es2020/modules/error-handler/utils/catch-async.js +1 -1
- package/dist/es2020/modules/error-handler/utils/catch-async.js.map +1 -1
- package/dist/es2020/modules/file-uploader/file-uploader.service.js +4 -4
- package/dist/es2020/modules/file-uploader/file-uploader.service.js.map +1 -1
- package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js +7 -5
- package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +1 -1
- package/dist/es2020/server.js +1 -1
- package/dist/es2020/server.js.map +1 -1
- package/dist/es2020/types/auth.js.map +1 -1
- package/dist/es2020/types/index.js.map +1 -1
- package/dist/es2020/utils/features/api.features.js +3 -2
- package/dist/es2020/utils/features/api.features.js.map +1 -1
- package/dist/es2020/utils/helpers/api.features.helpers.js +4 -4
- package/dist/es2020/utils/helpers/api.features.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/base.controller.helpers.js +75 -31
- package/dist/es2020/utils/helpers/base.controller.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/change-case.helpers.js +3 -3
- package/dist/es2020/utils/helpers/change-case.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +35 -30
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/utils/scripts/generate-insomnia-collection.js +189 -0
- package/dist/es2020/utils/scripts/generate-insomnia-collection.js.map +1 -0
- package/dist/es2020/utils/scripts/index.js +10 -0
- package/dist/es2020/utils/scripts/index.js.map +1 -0
- package/dist/types/exports/middlewares/index.d.ts +1 -0
- package/dist/types/modules/auth/auth.service.d.ts +3 -3
- package/dist/types/modules/base/base.middlewares.d.ts +6 -1
- package/dist/types/modules/base/utils/helpers/base.service.helpers.d.ts +1 -1
- package/dist/types/types/auth.d.ts +9 -8
- package/dist/types/types/index.d.ts +2 -1
- package/dist/types/utils/helpers/base.controller.helpers.d.ts +4 -6
- package/dist/types/utils/scripts/generate-insomnia-collection.d.ts +1 -0
- package/dist/types/utils/scripts/index.d.ts +2 -0
- package/package.json +10 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAEC;AAED,4EAyCC;AAED,sCAwDC;AASD,4DA2CC;AA2BD,8CAgBC;AAOD,wDA4HC;AAUD,0DAKC;AAmBQ,8BAAS;AAAE,oDAAoB;AA1XxC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAoD;AACpD,qDAAgD;AAErC,QAAA,mBAAmB,GAG1B,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,2BAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,cAAc,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC;IACpD,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IAExD,OAAO;QACL,IAAI,EAAE;YACJ,OAA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,IAAI,uBAAJ,IAAI,CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EAAE,CAAC;oBAC1B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n return {\n core: {\n service: `${kebabModelName}.service.${getUserFileExtension()}`,\n controller: `${kebabModelName}.controller.${getUserFileExtension()}`,\n middlewares: `${kebabModelName}.middlewares.${getUserFileExtension()}`,\n authConfigs: `${kebabModelName}.auth-configs.${getUserFileExtension()}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${getUserFileExtension()}`,\n router: `${kebabModelName}.router.${getUserFileExtension()}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${getUserFileExtension()}`,\n signup: `signup.dto.${getUserFileExtension()}`,\n updateMe: `update-me.dto.${getUserFileExtension()}`,\n updatePassword: `update-password.dto.${getUserFileExtension()}`,\n }\n : {\n model: `${lowerModelName}.dto.${getUserFileExtension()}`,\n create: `create-${lowerModelName}.dto.${getUserFileExtension()}`,\n update: `update-${lowerModelName}.dto.${getUserFileExtension()}`,\n query: `query-${lowerModelName}.dto.${getUserFileExtension()}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${getUserFileExtension()}`,\n signup: `signup.schema.${getUserFileExtension()}`,\n updateMe: `update-me.schema.${getUserFileExtension()}`,\n updatePassword: `update-password.schema.${getUserFileExtension()}`,\n }\n : {\n model: `${lowerModelName}.schema.${getUserFileExtension()}`,\n create: `create-${lowerModelName}.schema.${getUserFileExtension()}`,\n update: `update-${lowerModelName}.schema.${getUserFileExtension()}`,\n query: `query-${lowerModelName}.schema.${getUserFileExtension()}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(\n process.cwd(),\n \"src\",\n \"modules\",\n kebabCase(modelName)\n );\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<Record<string, any>> {\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n\n const result: {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n } = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n // let modelFile;\n // for (const file of files) {\n // const filePath = path.join(file);\n // const stats = fs.statSync(filePath);\n\n // if (stats.isFile()) {\n // const content = fs.readFileSync(filePath, \"utf-8\");\n // prismaContent.push(content);\n // if (content?.includes(`model ${modelName} {`)) {\n // modelFile = file;\n // break;\n // }\n // }\n // }\n\n // if (!modelFile) {\n // return;\n // }\n\n // const content = fs.readFileSync(path.join(modelFile), \"utf-8\");\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes(camelCase(cleanType || \"\"))\n ) {\n const modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n ) {\n continue;\n }\n\n if (!type?.includes(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
1
|
+
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAEC;AAED,4EA0CC;AAED,sCAwDC;AASD,4DA2CC;AA2BD,8CAgBC;AAOD,wDA4GC;AAUD,0DAKC;AAmBQ,8BAAS;AAAE,oDAAoB;AA3WxC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAoD;AACpD,qDAAgD;AAErC,QAAA,mBAAmB,GAG1B,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,2BAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,cAAc,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC;IACpD,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxD,M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SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${lowerModelName}.dto.${ext}`,\n create: `create-${lowerModelName}.dto.${ext}`,\n update: `update-${lowerModelName}.dto.${ext}`,\n query: `query-${lowerModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${lowerModelName}.schema.${ext}`,\n create: `create-${lowerModelName}.schema.${ext}`,\n update: `update-${lowerModelName}.schema.${ext}`,\n query: `query-${lowerModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(\n process.cwd(),\n \"src\",\n \"modules\",\n kebabCase(modelName)\n );\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<Record<string, any>> {\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n\n const result: {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n } = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
36
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
37
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
38
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
39
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
40
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
41
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
45
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
46
|
+
};
|
|
47
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
48
|
+
exports.writeInsomniaCollectionJson = writeInsomniaCollectionJson;
|
|
49
|
+
const change_case_helpers_1 = require("../helpers/change-case.helpers");
|
|
50
|
+
const fs_1 = __importDefault(require("fs"));
|
|
51
|
+
const path_1 = __importDefault(require("path"));
|
|
52
|
+
const pluralize_1 = __importDefault(require("pluralize"));
|
|
53
|
+
const base_controller_helpers_1 = require("../helpers/base.controller.helpers");
|
|
54
|
+
function generateInsomniaCollection() {
|
|
55
|
+
const routes = (0, base_controller_helpers_1.getAppRoutes)();
|
|
56
|
+
const resourceTypes = [
|
|
57
|
+
...new Set(routes.map((route) => route.path.split("/")[1] || "root")),
|
|
58
|
+
];
|
|
59
|
+
const collection = {
|
|
60
|
+
_type: "export",
|
|
61
|
+
__export_format: 4,
|
|
62
|
+
__export_date: new Date().toISOString(),
|
|
63
|
+
__export_source: "script-generated",
|
|
64
|
+
resources: [],
|
|
65
|
+
};
|
|
66
|
+
collection.resources.push({
|
|
67
|
+
_id: "wrk_arkos",
|
|
68
|
+
parentId: null,
|
|
69
|
+
modified: new Date().toISOString(),
|
|
70
|
+
created: new Date().toISOString(),
|
|
71
|
+
name: "Project API",
|
|
72
|
+
description: "Automatically generated Arkos API collection",
|
|
73
|
+
_type: "workspace",
|
|
74
|
+
});
|
|
75
|
+
const routesByResource = resourceTypes.reduce((acc, resourceType) => {
|
|
76
|
+
if (resourceType === "root")
|
|
77
|
+
return acc;
|
|
78
|
+
acc[resourceType] = {
|
|
79
|
+
findMany: routes.find((r) => r.method === "GET" && r.path === `/${resourceType}`),
|
|
80
|
+
findOne: routes.find((r) => r.method === "GET" && r.path === `/${resourceType}/:id`),
|
|
81
|
+
createOne: routes.find((r) => r.method === "POST" && r.path === `/${resourceType}`),
|
|
82
|
+
createMany: routes.find((r) => r.method === "POST" && r.path === `/${resourceType}/many`),
|
|
83
|
+
updateOne: routes.find((r) => r.method === "PATCH" && r.path === `/${resourceType}/:id`),
|
|
84
|
+
updateMany: routes.find((r) => r.method === "PATCH" && r.path === `/${resourceType}/many`),
|
|
85
|
+
deleteOne: routes.find((r) => r.method === "DELETE" && r.path === `/${resourceType}/:id`),
|
|
86
|
+
deleteMany: routes.find((r) => r.method === "DELETE" && r.path === `/${resourceType}/many`),
|
|
87
|
+
};
|
|
88
|
+
return acc;
|
|
89
|
+
}, {});
|
|
90
|
+
Object.entries(routesByResource).forEach(([resourceType, resourceRoutes], index) => {
|
|
91
|
+
const folderId = `fld_${resourceType}`;
|
|
92
|
+
collection.resources.push({
|
|
93
|
+
_id: folderId,
|
|
94
|
+
parentId: "wrk_arkos",
|
|
95
|
+
modified: new Date().toISOString(),
|
|
96
|
+
created: new Date().toISOString(),
|
|
97
|
+
name: resourceType
|
|
98
|
+
.replace(/-/g, " ")
|
|
99
|
+
.replace(/\b\w/g, (l) => l.toUpperCase()),
|
|
100
|
+
description: `${resourceType
|
|
101
|
+
.replace(/-/g, " ")
|
|
102
|
+
.replace(/\b\w/g, (l) => l.toUpperCase())} endpoints`,
|
|
103
|
+
environment: {},
|
|
104
|
+
environmentPropertyOrder: null,
|
|
105
|
+
metaSortKey: -1000 + index * 100,
|
|
106
|
+
_type: "request_group",
|
|
107
|
+
});
|
|
108
|
+
const methodMappings = [
|
|
109
|
+
{ key: "findMany", name: "Find Many", method: "GET" },
|
|
110
|
+
{ key: "findOne", name: "Find One", method: "GET" },
|
|
111
|
+
{ key: "createOne", name: "Create One", method: "POST" },
|
|
112
|
+
{ key: "createMany", name: "Create Many", method: "POST" },
|
|
113
|
+
{ key: "updateOne", name: "Update One", method: "PATCH" },
|
|
114
|
+
{ key: "updateMany", name: "Update Many", method: "PATCH" },
|
|
115
|
+
{ key: "deleteOne", name: "Delete One", method: "DELETE" },
|
|
116
|
+
{ key: "deleteMany", name: "Delete Many", method: "DELETE" },
|
|
117
|
+
];
|
|
118
|
+
methodMappings.forEach((mapping, routeIndex) => __awaiter(this, void 0, void 0, function* () {
|
|
119
|
+
const route = resourceRoutes[mapping.key];
|
|
120
|
+
if (!route)
|
|
121
|
+
return;
|
|
122
|
+
const modelName = (0, change_case_helpers_1.kebabCase)(pluralize_1.default.singular(mapping.key));
|
|
123
|
+
const reqId = `req_${resourceType}_${mapping.key}`;
|
|
124
|
+
const dtoPath = path_1.default.join(process.cwd(), `src/modules/${modelName}/dtos`);
|
|
125
|
+
const dotMapping = {
|
|
126
|
+
createOne: `create-${modelName}.dto.ts`,
|
|
127
|
+
updateOne: `create-${modelName}.dto.ts`,
|
|
128
|
+
};
|
|
129
|
+
const dto = yield Promise.resolve(`${path_1.default.join(dtoPath, dotMapping[mapping.key])}`).then(s => __importStar(require(s)));
|
|
130
|
+
collection.resources.push({
|
|
131
|
+
_id: reqId,
|
|
132
|
+
parentId: folderId,
|
|
133
|
+
modified: new Date().toISOString(),
|
|
134
|
+
created: new Date().toISOString(),
|
|
135
|
+
url: `{{BASE_URL}}/${route.path}`,
|
|
136
|
+
name: mapping.name,
|
|
137
|
+
description: `${mapping.method} request for ${route.path}`,
|
|
138
|
+
method: route.method,
|
|
139
|
+
body: route.method !== "GET"
|
|
140
|
+
? {
|
|
141
|
+
mimeType: "application/json",
|
|
142
|
+
text: route.method === "POST" || route.method === "PATCH"
|
|
143
|
+
? route.path.includes("/many")
|
|
144
|
+
? "[{}]"
|
|
145
|
+
: "{}"
|
|
146
|
+
: "[]",
|
|
147
|
+
}
|
|
148
|
+
: {},
|
|
149
|
+
parameters: route.path.includes(":")
|
|
150
|
+
? route.path
|
|
151
|
+
.split("/")
|
|
152
|
+
.filter((p) => p.startsWith(":"))
|
|
153
|
+
.map((param) => ({
|
|
154
|
+
id: `par_${param.slice(1)}`,
|
|
155
|
+
name: param.slice(1),
|
|
156
|
+
value: "",
|
|
157
|
+
description: `${param.slice(1)} parameter`,
|
|
158
|
+
disabled: false,
|
|
159
|
+
}))
|
|
160
|
+
: [],
|
|
161
|
+
headers: route.method !== "GET"
|
|
162
|
+
? [
|
|
163
|
+
{
|
|
164
|
+
name: "Content-Type",
|
|
165
|
+
value: "application/json",
|
|
166
|
+
},
|
|
167
|
+
]
|
|
168
|
+
: [],
|
|
169
|
+
authentication: {},
|
|
170
|
+
metaSortKey: -1000 + routeIndex * 10,
|
|
171
|
+
isPrivate: false,
|
|
172
|
+
settingStoreCookies: true,
|
|
173
|
+
settingSendCookies: true,
|
|
174
|
+
settingDisableRenderRequestBody: false,
|
|
175
|
+
settingEncodeUrl: true,
|
|
176
|
+
settingRebuildPath: true,
|
|
177
|
+
settingFollowRedirects: "global",
|
|
178
|
+
_type: "request",
|
|
179
|
+
});
|
|
180
|
+
}));
|
|
181
|
+
});
|
|
182
|
+
const rootFolderId = "fld_root";
|
|
183
|
+
collection.resources.push({
|
|
184
|
+
_id: rootFolderId,
|
|
185
|
+
parentId: "wrk_arkos",
|
|
186
|
+
modified: new Date().toISOString(),
|
|
187
|
+
created: new Date().toISOString(),
|
|
188
|
+
name: "Root",
|
|
189
|
+
description: "Root API endpoints",
|
|
190
|
+
environment: {},
|
|
191
|
+
environmentPropertyOrder: null,
|
|
192
|
+
metaSortKey: -100,
|
|
193
|
+
_type: "request_group",
|
|
194
|
+
});
|
|
195
|
+
const rootRoutes = routes.filter((route) => route.path === "/api" || route.path === "/available-routes");
|
|
196
|
+
rootRoutes.forEach((route, index) => {
|
|
197
|
+
collection.resources.push({
|
|
198
|
+
_id: `req_root_${route.path.slice(1)}`,
|
|
199
|
+
parentId: rootFolderId,
|
|
200
|
+
modified: new Date().toISOString(),
|
|
201
|
+
created: new Date().toISOString(),
|
|
202
|
+
url: `{{BASE_URL}}/${route.path}`,
|
|
203
|
+
name: route.path === "/api" ? "Welcome" : "Available Routes",
|
|
204
|
+
description: `${route.method} request for ${route.path}`,
|
|
205
|
+
method: route.method,
|
|
206
|
+
body: {},
|
|
207
|
+
parameters: [],
|
|
208
|
+
headers: [],
|
|
209
|
+
authentication: {},
|
|
210
|
+
metaSortKey: -1000 + index * 10,
|
|
211
|
+
isPrivate: false,
|
|
212
|
+
settingStoreCookies: true,
|
|
213
|
+
settingSendCookies: true,
|
|
214
|
+
settingDisableRenderRequestBody: false,
|
|
215
|
+
settingEncodeUrl: true,
|
|
216
|
+
settingRebuildPath: true,
|
|
217
|
+
settingFollowRedirects: "global",
|
|
218
|
+
_type: "request",
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
return collection;
|
|
222
|
+
}
|
|
223
|
+
function writeInsomniaCollectionJson() {
|
|
224
|
+
const insomniaCollection = generateInsomniaCollection();
|
|
225
|
+
fs_1.default.writeFileSync(path_1.default.join(process.cwd(), ".cache", "insomnia-collection.json"), JSON.stringify(insomniaCollection, null, 2));
|
|
226
|
+
console.log("Insomnia collection generated successfully! .cache/insomnia-collection.json");
|
|
227
|
+
}
|
|
228
|
+
//# sourceMappingURL=generate-insomnia-collection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-insomnia-collection.js","sourceRoot":"","sources":["../../../../src/utils/scripts/generate-insomnia-collection.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqSA,kEAgBC;AApTD,wEAA2D;AAC3D,4CAAoB;AACpB,gDAAwB;AAC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,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,kBAAkB;YAC5D,WAAW,EAAE,GAAG,KAAK,CAAC,MAAM,gBAAgB,KAAK,CAAC,IAAI,EAAE;YACxD,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI,EAAE,EAAE;YACR,UAAU,EAAE,EAAE;YACd,OAAO,EAAE,EAAE;YACX,cAAc,EAAE,EAAE;YAClB,WAAW,EAAE,CAAC,IAAI,GAAG,KAAK,GAAG,EAAE;YAC/B,SAAS,EAAE,KAAK;YAChB,mBAAmB,EAAE,IAAI;YACzB,kBAAkB,EAAE,IAAI;YACxB,+BAA+B,EAAE,KAAK;YACtC,gBAAgB,EAAE,IAAI;YACtB,kBAAkB,EAAE,IAAI;YACxB,sBAAsB,EAAE,QAAQ;YAChC,KAAK,EAAE,SAAS;SACjB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,UAAU,CAAC;AACpB,CAAC;AAGD,SAAgB,2BAA2B;IAKzC,MAAM,kBAAkB,GAAG,0BAA0B,EAAE,CAAC;IAGxD,YAAE,CAAC,aAAa,CACd,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,0BAA0B,CAAC,EAC9D,IAAI,CAAC,SAAS,CAAC,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC,CAC5C,CAAC;IAEF,OAAO,CAAC,GAAG,CACT,6EAA6E,CAC9E,CAAC;AACJ,CAAC","sourcesContent":["// import { kebabCase } from \"change-case\";\nimport { kebabCase } from \"../helpers/change-case.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport pluralize from \"pluralize\";\n// import DtoParser from \"./dto-parser\";\nimport { getAppRoutes } from \"../helpers/base.controller.helpers\";\n\n// Define types for the routes and collection\ninterface Route {\n method: string;\n path: string;\n}\n\ninterface InsomniaResource {\n _id: string;\n parentId: string | null;\n modified: string;\n created: string;\n name: string;\n description?: string;\n _type: string;\n url?: string;\n method?: string;\n body?: {\n mimeType?: string;\n text?: string;\n };\n parameters?: Array<{\n id: string;\n name: string;\n value: string;\n description: string;\n disabled: boolean;\n }>;\n headers?: Array<{\n name: string;\n value: string;\n }>;\n authentication?: Record<string, unknown>;\n metaSortKey?: number;\n environment?: Record<string, unknown>;\n environmentPropertyOrder?: null;\n isPrivate?: boolean;\n settingStoreCookies?: boolean;\n settingSendCookies?: boolean;\n settingDisableRenderRequestBody?: boolean;\n settingEncodeUrl?: boolean;\n settingRebuildPath?: boolean;\n settingFollowRedirects?: string;\n}\n\ninterface InsomniaCollection {\n _type: string;\n __export_format: number;\n __export_date: string;\n __export_source: string;\n resources: InsomniaResource[];\n}\n\ninterface ResourceRoutes {\n findMany?: Route;\n findOne?: Route;\n createOne?: Route;\n createMany?: Route;\n updateOne?: Route;\n updateMany?: Route;\n deleteOne?: Route;\n deleteMany?: Route;\n}\n\nfunction generateInsomniaCollection(): InsomniaCollection {\n const routes = getAppRoutes();\n\n // Unique resource types\n const resourceTypes: string[] = [\n ...new Set(routes.map((route) => route.path.split(\"/\")[1] || \"root\")),\n ];\n\n // Base collection structure\n const collection: InsomniaCollection = {\n _type: \"export\",\n __export_format: 4,\n __export_date: new Date().toISOString(),\n __export_source: \"script-generated\",\n resources: [],\n };\n\n // Add workspace\n collection.resources.push({\n _id: \"wrk_arkos\",\n parentId: null,\n modified: new Date().toISOString(),\n created: new Date().toISOString(),\n name: \"Project API\",\n description: \"Automatically generated Arkos API collection\",\n _type: \"workspace\",\n });\n\n // Group routes by resource type\n const routesByResource: Record<string, ResourceRoutes> = resourceTypes.reduce(\n (acc, resourceType) => {\n if (resourceType === \"root\") return acc;\n\n acc[resourceType] = {\n findMany: routes.find(\n (r) => r.method === \"GET\" && r.path === `/${resourceType}`\n ),\n findOne: routes.find(\n (r) => r.method === \"GET\" && r.path === `/${resourceType}/:id`\n ),\n createOne: routes.find(\n (r) => r.method === \"POST\" && r.path === `/${resourceType}`\n ),\n createMany: routes.find(\n (r) => r.method === \"POST\" && r.path === `/${resourceType}/many`\n ),\n updateOne: routes.find(\n (r) => r.method === \"PATCH\" && r.path === `/${resourceType}/:id`\n ),\n updateMany: routes.find(\n (r) => r.method === \"PATCH\" && r.path === `/${resourceType}/many`\n ),\n deleteOne: routes.find(\n (r) => r.method === \"DELETE\" && r.path === `/${resourceType}/:id`\n ),\n deleteMany: routes.find(\n (r) => r.method === \"DELETE\" && r.path === `/${resourceType}/many`\n ),\n };\n\n return acc;\n },\n {} as Record<string, any>\n );\n\n // Create folders and requests for each resource type\n Object.entries(routesByResource).forEach(\n ([resourceType, resourceRoutes], index) => {\n // Main resource folder\n const folderId = `fld_${resourceType}`;\n collection.resources.push({\n _id: folderId,\n parentId: \"wrk_arkos\",\n modified: new Date().toISOString(),\n created: new Date().toISOString(),\n name: resourceType\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (l) => l.toUpperCase()),\n description: `${resourceType\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (l) => l.toUpperCase())} endpoints`,\n environment: {},\n environmentPropertyOrder: null,\n metaSortKey: -1000 + index * 100,\n _type: \"request_group\",\n });\n\n // Create specific method requests\n const methodMappings = [\n { key: \"findMany\", name: \"Find Many\", method: \"GET\" },\n { key: \"findOne\", name: \"Find One\", method: \"GET\" },\n { key: \"createOne\", name: \"Create One\", method: \"POST\" },\n { key: \"createMany\", name: \"Create Many\", method: \"POST\" },\n { key: \"updateOne\", name: \"Update One\", method: \"PATCH\" },\n { key: \"updateMany\", name: \"Update Many\", method: \"PATCH\" },\n { key: \"deleteOne\", name: \"Delete One\", method: \"DELETE\" },\n { key: \"deleteMany\", name: \"Delete Many\", method: \"DELETE\" },\n ];\n\n methodMappings.forEach(async (mapping, routeIndex) => {\n const route = resourceRoutes[mapping.key as keyof ResourceRoutes];\n if (!route) return;\n\n const modelName = kebabCase(pluralize.singular(mapping.key));\n const reqId = `req_${resourceType}_${mapping.key}`;\n const dtoPath = path.join(\n process.cwd(),\n `src/modules/${modelName}/dtos`\n );\n\n const dotMapping: Record<string, string> = {\n createOne: `create-${modelName}.dto.ts`,\n updateOne: `create-${modelName}.dto.ts`,\n };\n\n const dto = await import(path.join(dtoPath, dotMapping[mapping.key]));\n\n collection.resources.push({\n _id: reqId,\n parentId: folderId,\n modified: new Date().toISOString(),\n created: new Date().toISOString(),\n url: `{{BASE_URL}}/${route.path}`,\n name: mapping.name,\n description: `${mapping.method} request for ${route.path}`,\n method: route.method,\n body:\n route.method !== \"GET\"\n ? {\n mimeType: \"application/json\",\n text:\n route.method === \"POST\" || route.method === \"PATCH\"\n ? route.path.includes(\"/many\")\n ? \"[{}]\" // array for many\n : \"{}\" // object for single\n : \"[]\", // array for delete\n }\n : {},\n parameters: route.path.includes(\":\")\n ? route.path\n .split(\"/\")\n .filter((p) => p.startsWith(\":\"))\n .map((param) => ({\n id: `par_${param.slice(1)}`,\n name: param.slice(1),\n value: \"\",\n description: `${param.slice(1)} parameter`,\n disabled: false,\n }))\n : [],\n headers:\n route.method !== \"GET\"\n ? [\n {\n name: \"Content-Type\",\n value: \"application/json\",\n },\n ]\n : [],\n authentication: {},\n metaSortKey: -1000 + routeIndex * 10,\n isPrivate: false,\n settingStoreCookies: true,\n settingSendCookies: true,\n settingDisableRenderRequestBody: false,\n settingEncodeUrl: true,\n settingRebuildPath: true,\n settingFollowRedirects: \"global\",\n _type: \"request\",\n });\n });\n }\n );\n\n // Add root routes (api, available-routes)\n const rootFolderId = \"fld_root\";\n collection.resources.push({\n _id: rootFolderId,\n parentId: \"wrk_arkos\",\n modified: new Date().toISOString(),\n created: new Date().toISOString(),\n name: \"Root\",\n description: \"Root API endpoints\",\n environment: {},\n environmentPropertyOrder: null,\n metaSortKey: -100,\n _type: \"request_group\",\n });\n\n const rootRoutes = routes.filter(\n (route) => route.path === \"/api\" || route.path === \"/available-routes\"\n );\n rootRoutes.forEach((route, index) => {\n collection.resources.push({\n _id: `req_root_${route.path.slice(1)}`,\n parentId: rootFolderId,\n modified: new Date().toISOString(),\n created: new Date().toISOString(),\n url: `{{BASE_URL}}/${route.path}`,\n name: route.path === \"/api\" ? \"Welcome\" : \"Available Routes\",\n description: `${route.method} request for ${route.path}`,\n method: route.method,\n body: {},\n parameters: [],\n headers: [],\n authentication: {},\n metaSortKey: -1000 + index * 10,\n isPrivate: false,\n settingStoreCookies: true,\n settingSendCookies: true,\n settingDisableRenderRequestBody: false,\n settingEncodeUrl: true,\n settingRebuildPath: true,\n settingFollowRedirects: \"global\",\n _type: \"request\",\n });\n });\n\n return collection;\n}\n\n// Example usage\nexport function writeInsomniaCollectionJson() {\n // Generate the collection\n // const dtoParser = new DtoParser(\"./src/modules\");\n // const dtoBodies = dtoParser.parseAllDtos();\n\n const insomniaCollection = generateInsomniaCollection();\n\n // Write to file\n fs.writeFileSync(\n path.join(process.cwd(), \".cache\", \"insomnia-collection.json\"),\n JSON.stringify(insomniaCollection, null, 2)\n );\n\n console.log(\n \"Insomnia collection generated successfully! .cache/insomnia-collection.json\"\n );\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const generate_insomnia_collection_1 = require("./generate-insomnia-collection");
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
const command = args[0];
|
|
7
|
+
switch (command) {
|
|
8
|
+
case "generate-insomnia-collection":
|
|
9
|
+
(0, generate_insomnia_collection_1.writeInsomniaCollectionJson)();
|
|
10
|
+
break;
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/scripts/index.ts"],"names":[],"mappings":";;;AAEA,iFAA6E;AAE7E,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAExB,QAAQ,OAAO,EAAE,CAAC;IAChB,KAAK,8BAA8B;QACjC,IAAA,0DAA2B,GAAE,CAAC;QAC9B,MAAM;AACV,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { writeInsomniaCollectionJson } from \"./generate-insomnia-collection\";\n\nconst args = process.argv.slice(2);\nconst command = args[0];\n\nswitch (command) {\n case \"generate-insomnia-collection\":\n writeInsomniaCollectionJson();\n break;\n}\n\n// if (command === \"generate-something\") {\n// console.log(\"Hello World from arkos generate-something!\");\n// console.log(\"This is running from your installed arkos package.\");\n// } else {\n// console.log(\"Available commands:\");\n// console.log(\" generate-something - Prints a hello world message\");\n// console.log(\"\\nUsage: pnpm arkos [command]\");\n// }\n\n// // 3. Optional: Create an index.js file in the root:\n// // index.js\n\n// // This allows your package to be used programmatically\n// module.exports = {\n// generateSomething: () => {\n// console.log(\"Hello World from arkos generate-something!\");\n// console.log(\"This is running from your imported arkos package.\");\n// },\n// };\n"]}
|
package/dist/es2020/app.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var j=function(e,R,n,s){function b(u){return u instanceof n?u:new n(function(v){v(u)})}return new(n||(n=Promise))(function(u,v){function P(o){try{a(s.next(o))}catch(p){v(p)}}function q(o){try{a(s.throw(o))}catch(p){v(p)}}function a(o){o.done?u(o.value):b(o.value).then(P,q)}a((s=s.apply(e,R||[])).next())})};import U from"express";import N from"cors";import D from"cookie-parser";import{getAuthRouter as B}from"./modules/auth/auth.router";import{getPrismaModelsRouter as S,getAvailableResourcesAndRoutesRouter as V}from"./modules/base/base.router";import z from"./modules/error-handler/error-handler.controller";import{rateLimit as F}from"express-rate-limit";import _ from"path";import*as G from"dotenv";import I from"compression";import{handleRequestLogs as J}from"./modules/base/base.middlewares";import{checkDatabaseConnection as K,loadPrismaModule as Q}from"./utils/helpers/prisma.helpers";import{getFileUploaderRouter as W}from"./modules/file-uploader/file-uploader.router";import{queryParser as X}from"./utils/helpers/query-parser.helpers";import L from"./utils/helpers/deepmerge.helper";const y=process.env.NODE_ENV;let f=".env";y==="production"?f=_.resolve(process.cwd(),".env.production"):y==="staging"?f=_.resolve(process.cwd(),".env.staging"):y==="development"?f=_.resolve(process.cwd(),".env.development"):y==="local"?f=_.resolve(process.cwd(),".env.local"):y==="test"?f=_.resolve(process.cwd(),".env.test"):y==="qa"&&(f=_.resolve(process.cwd(),".env.qa")),G.config({path:f});export const app=U();export function bootstrap(e){return j(this,void 0,void 0,function*(){var R,n,s,b,u,v,P,q,a,o,p,E,A,O,H,M;yield Q(),e.configureApp&&(yield e.configureApp(app));const w=e?.middlewares,l=w?.disable||[],r=w?.replace||{};!((R=l?.includes)===null||R===void 0)&&R.call(l,"compression")||app.use(r.compression||I(e?.compressionOptions)),!((n=l?.includes)===null||n===void 0)&&n.call(l,"global-rate-limit")||app.use(r.globalRateLimit||F(L({windowMs:60*1e3,limit:1e3,standardHeaders:"draft-7",legacyHeaders:!1},e?.globalRequestRateLimitOptions||{}))),!((s=l?.includes)===null||s===void 0)&&s.call(l,"cors")||app.use(r.cors||N(!((b=e?.cors)===null||b===void 0)&&b.customHandler?e.cors.customHandler:L({origin:(d,h)=>{var x,T;const c=(x=e?.cors)===null||x===void 0?void 0:x.allowedOrigins;c==="*"?h(null,!0):Array.isArray(c)?h(null,!d||((T=c?.includes)===null||T===void 0?void 0:T.call(c,d))):typeof c=="string"?h(null,!d||c===d):h(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},((u=e?.cors)===null||u===void 0?void 0:u.options)||{}))),!((v=l?.includes)===null||v===void 0)&&v.call(l,"express-json")||app.use(r.expressJson||U.json(e?.jsonBodyParserOptions)),!((P=l?.includes)===null||P===void 0)&&P.call(l,"cookie-parser")||app.use(r.cookieParser||D(...e?.cookieParserParameters||[])),!((q=l?.includes)===null||q===void 0)&&q.call(l,"query-parser")||app.use(r.queryParser||X(L({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),!((a=l?.includes)===null||a===void 0)&&a.call(l,"database-connection")||app.use(r.databaseConnection||K),!((o=l?.includes)===null||o===void 0)&&o.call(l,"request-logger")||app.use(r.requestLogger||J),!((p=e?.middlewares)===null||p===void 0)&&p.additional&&e.middlewares.additional.forEach(d=>{app.use(d)});const t=e?.routers,i=t?.disable||[],m=t?.replace||{};if(!((E=i?.includes)===null||E===void 0)&&E.call(i,"welcome-endpoint")||app.get("/api",m.welcomeEndpoint||((d,h)=>{h.status(200).json({message:e.welcomeMessage})})),!(!((A=i?.includes)===null||A===void 0)&&A.call(i,"file-uploader"))){const d=m.fileUploader?yield m.fileUploader(e):yield W(e);app.use(d)}if(!(!((O=i?.includes)===null||O===void 0)&&O.call(i,"auth-router"))&&e.authentication){const d=m.authRouter?yield m.authRouter(e):yield B(e);app.use("/api",d)}if(!(!((H=i?.includes)===null||H===void 0)&&H.call(i,"prisma-models-router"))){const d=m.prismaModelsRouter?yield m.prismaModelsRouter(e):yield S(e);app.use("/api",d)}return app.use("/api",V()),t?.additional&&t.additional.forEach(d=>{app.use(d)}),!((M=l?.includes)===null||M===void 0)&&M.call(l,"global-error-handler")||app.use(r.globalErrorHandler||z),app})}
|
package/dist/es2020/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,M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QAAQ,CAAC,sBAAsB,CAAC,CAAA;YACxD,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;QAElE,OAAO,GAAG,CAAC;IACb,CAAC;CAAA","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport path from \"path\";\nimport * as dotenv from \"dotenv\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nconst ENV = process.env.NODE_ENV;\nlet envPath = \".env\";\n\n// Default to `.env.local` if available in any environment\nif (ENV === \"production\") {\n envPath = path.resolve(process.cwd(), \".env.production\");\n} else if (ENV === \"staging\") {\n envPath = path.resolve(process.cwd(), \".env.staging\");\n} else if (ENV === \"development\") {\n envPath = path.resolve(process.cwd(), \".env.development\");\n} else if (ENV === \"local\") {\n // For local development, .env.local can be used\n envPath = path.resolve(process.cwd(), \".env.local\");\n}\n\n// Optionally, add support for `.env.test`, `.env.qa`, or other environments if required\nelse if (ENV === \"test\") {\n envPath = path.resolve(process.cwd(), \".env.test\");\n} else if (ENV === \"qa\") {\n envPath = path.resolve(process.cwd(), \".env.qa\");\n}\n\ndotenv.config({ path: envPath });\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (!disabledRouters?.includes(\"auth-router\") && arkosConfig.authentication) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AAEzD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;AACjC,IAAI,OAAO,GAAG,MAAM,CAAC;AAGrB,IAAI,GAAG,KAAK,YAAY,EAAE,CAAC;IACzB,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,iBAAiB,CAAC,CAAC;AAC3D,CAAC;KAAM,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;IAC7B,OAAO,GAAG,IAAI,CAAC,OAAO,CA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ACzD,MAAM,YAAY,GAAG,eAAe,CAAC,kBAAkB;gBACrD,CAAC,CAAC,MAAM,eAAe,CAAC,kBAAkB,CAAC,WAAW,CAAC;gBACvD,CAAC,CAAC,MAAM,qBAAqB,CAAC,WAAW,CAAC,CAAC;YAC7C,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAChC,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;QAGxD,IAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,UAAU,EAAE,CAAC;YAC9B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;gBAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC;QAGD,IAAI,CAAC,CAAA,MAAA,mBAAmB,aAAnB,mBAAmB,uBAAnB,mBAAmB,CAAE,QAAQ,oEAAG,sBAAsB,CAAC,CAAA;YAC1D,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;QAElE,OAAO,GAAG,CAAC;IACb,CAAC;CAAA","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport path from \"path\";\nimport * as dotenv from \"dotenv\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nconst ENV = process.env.NODE_ENV;\nlet envPath = \".env\";\n\n// Default to `.env.local` if available in any environment\nif (ENV === \"production\") {\n envPath = path.resolve(process.cwd(), \".env.production\");\n} else if (ENV === \"staging\") {\n envPath = path.resolve(process.cwd(), \".env.staging\");\n} else if (ENV === \"development\") {\n envPath = path.resolve(process.cwd(), \".env.development\");\n} else if (ENV === \"local\") {\n // For local development, .env.local can be used\n envPath = path.resolve(process.cwd(), \".env.local\");\n}\n\n// Optionally, add support for `.env.test`, `.env.qa`, or other environments if required\nelse if (ENV === \"test\") {\n envPath = path.resolve(process.cwd(), \".env.test\");\n} else if (ENV === \"qa\") {\n envPath = path.resolve(process.cwd(), \".env.qa\");\n}\n\ndotenv.config({ path: envPath });\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/exports/middlewares/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EACnC,4CAA4C,GAC7C,MAAM,qCAAqC,CAAC","sourcesContent":["export {\n addPrismaQueryOptionsToRequestQuery,\n handleRequestBodyValidationAndTransformation,\n} from \"../../modules/base/base.middlewares\";\n"]}
|