UNPKG

@arianaprojects/prisma-nestjs-crud-generator

Version:
436 lines 17.4 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const interfaces_1 = require("./../interfaces"); const interfaces_2 = require("../interfaces"); const templates_1 = require("../templates"); const fs_1 = __importDefault(require("fs")); const const_1 = require("./const"); const util_1 = require("../util"); class CRUD { constructor(parent) { this.idGenerator = false; this.parent = parent; this.config = this.configParser(this.parent.option.configPath); this.generate(); } generate() { let conBody = []; let serBody = []; conBody.push(this.controllerClassConstructor()); serBody.push(this.serviceClassConstructor()); if (this.config.access && !this.config.accessBlackList.includes(this.parent.namePascal)) { serBody.push((0, templates_1.functionPromiseGenerator)('hasAccess', `${const_1.UserParamService}, ${this.parent.replace('query: FIND_DTO')}`, 'Boolean', this.parent.replace(` const ret = await this.prismaService.NAME_CAMEL.findMany({ where: { ...query, ...this.hasAccessData(user), ...this.isNotDeletedData(), }, }); return ret.length > 0; `))); serBody.push((0, templates_1.functionGenerator)('hasAccessData', `${const_1.UserParamService}`, `Access${this.parent.namePascal}Dto`, ` return { userId:user.id }; `)); } serBody.push((0, templates_1.functionGenerator)('isNotDeletedData', ``, `Deleted${this.parent.namePascal}Dto`, ` return { deletedAt:null }; `)); serBody.push((0, templates_1.functionGenerator)('pseudonymisationData', ``, `Pseudonymisation${this.parent.namePascal}Dto`, ` return { }; `)); this.parent.idsNoDefault.map((id) => { serBody.push((0, templates_1.functionGenerator)(`${id.name}Gen`, ``, (0, util_1.tsTypes)(id.type), `// TODO return null`)); }); const keys = Object.keys(const_1.fixedConfig.functions); keys.map((f, i) => { const d = this.config && this.config.functions && this.config.functions[f] && this.config.functions[f].disable; if (!(this.config && this.config.functions && this.config.functions[f] && this.config.functions[f].disable)) { if (i == 12) { conBody.push('\n\n//\t------------------ ADMIN -------------------\n'); serBody.push('\n\n//\t------------------ ADMIN -------------------\n'); } const c = const_1.fixedConfig.functions[f]; conBody.push(this.controllerFunction(interfaces_2.ReqNames[f], c, true, true, true)); serBody.push(this.serviceFunction(interfaces_2.ReqNames[f], c)); serBody.push('\n'); } }); this.controller = (0, util_1.prettierFormatFormat)(this.controllerGenerator(conBody.join('\n'))); this.service = (0, util_1.prettierFormatFormat)(this.serviceGenerator(serBody.join('\n'))); } configParser(path) { if (!!path) return JSON.parse(fs_1.default.readFileSync(process.cwd() + '/' + path, 'utf-8')); return null; } functionControllerDecorator(type, conf, name) { let res = []; let p = [conf.fixedPath]; if (conf.param) this.parent.idFields.map((id) => { if (this.parent.idFields.length > 1) p.push(`${id.name}/:${id.name}`); else p.push(`:${id.name}`); }); res.push((0, templates_1.decoratorGenerator)(String(type), p.join('/'))); if (this.config && this.config.functions && this.config.functions[name] && this.config.functions[name].additionalDecorator) res.push(this.config.functions[name].additionalDecorator.join('\n')); return res.join('\n'); } apiOperationDecorator(name, conf) { let res = []; res.push('@ApiOperation({'); if (this.config && this.config.functions && this.config.functions[name] && !!this.config.functions[name].summary) res.push(`summary:"${this.parent.replace(this.config.functions[name].summary)}",`); if (this.config && this.config.functions && this.config.functions[name] && !!this.config.functions[name].description) res.push(`description:"${this.parent.replace(this.config.functions[name].description)}",`); res.push(`summary:"${this.parent.replace(conf.info)}",`); res.push('})'); return res.join('\n'); } allApiResponseDecorators(conf) { return conf.responses.map((r) => this.apiResponseDecorator(r, conf)).join('\n'); } apiResponseDecorator(option, conf) { let res = []; res.push('@ApiResponse({'); res.push(`status:${this.parent.replace(option.status)},`); if (option.description) res.push(`description:"${this.parent.replace(option.description)}",`); if (option.type) res.push(`type:${this.parent.replace(option.type)},`); res.push('})'); return res.join('\n'); } apiRequestDecorator(option) { let res = []; if (option.body) { res.push('@ApiBody({'); if (option.bodyArray) res.push('isArray:true,'); res.push('type:' + this.parent.replace(option.body)); res.push('})'); } return res.join('\n'); } paramController(option, access = false) { let res = []; if (access && !option.admin) { res.push(const_1.UserDecoratorParam); res.push(','); } if (option.query) { res.push('@Query() query: '); res.push(this.parent.replace(option.query)); res.push(','); } if (option.param) { res.push('@Param() param: '); res.push(this.parent.replace(option.param)); if (option.paramArray) res.push('[]'); res.push(','); } if (option.header) { res.push('@Header() header: '); res.push(this.parent.replace(option.header)); res.push(','); } if (option.body) { res.push('@Body() body: '); res.push(this.parent.replace(option.body)); if (option.bodyArray) res.push('[]'); res.push(','); } return res.join(' '); } paramControllerToService(option, access = false) { let res = []; if (access && !option.admin) { res.push(const_1.UserParam); res.push(','); } if (option.query) { res.push('query'); res.push(','); } if (option.param) { res.push('param'); res.push(','); } if (option.header) { res.push('header'); res.push(','); } if (option.body) { res.push('body '); res.push(','); } return res.join(' '); } paramService(option, access = false) { let res = []; if (access && !option.admin) { res.push(const_1.UserParamService); res.push(','); } if (option.query) { res.push((0, templates_1.parameterGenerator)('query', this.parent.replace(option.query))); res.push(','); } if (option.param) { res.push((0, templates_1.parameterGenerator)('param', this.parent.replace(option.param))); if (option.paramArray) res.push('[]'); res.push(','); } if (option.header) { res.push((0, templates_1.parameterGenerator)('header', this.parent.replace(option.header))); res.push(','); } if (option.body) { res.push((0, templates_1.parameterGenerator)('body ', this.parent.replace(option.body))); if (option.bodyArray) res.push('[]'); res.push(','); } return res.join(' '); } serviceClassDecorator() { let res = []; res.push('@Injectable()'); return res.join('\n'); } controllerClassDecorator() { let res = []; res.push(``); res.push(`@Controller('${this.parent.nameCamel}')`); res.push('@ApiBearerAuth()'); res.push(`@ApiTags("${this.parent.namePascal}")`); return res.join('\n'); } controllerFunctionComment(name) { let res = ['\n']; res.push('/********************************************************************'); res.push('* ' + interfaces_2.ReqNames[name]); res.push(' ********************************************************************/'); return res.join('\n'); } controllerFunctionBody(name, conf) { let res = []; const ENTITY = conf.responses.filter((r) => r.type == 'ENTITY').length >= 1; const ENTITYArray = conf.responses.filter((r) => r.type == '[ENTITY]').length >= 1; if (ENTITY || ENTITYArray) res.push(`return plainToInstance(${this.parent.namePascal}, (await this.${this.parent.nameCamel}Service.${name}(${this.paramControllerToService(conf, this.config.access)})))`); else res.push(`return await this.${this.parent.nameCamel}Service.${name}(${this.paramControllerToService(conf, this.config.access)})`); return res.join('\n'); } controllerFunction(name, conf, apiOperator, apiReq, apiResp) { let res = []; const optionalConf = this.config && this.config.functions && this.config.functions[name]; res.push(this.controllerFunctionComment(name)); res.push(this.functionControllerDecorator(interfaces_2.ReqType[interfaces_1.ReqNamesType[name]], conf, name)); if (apiOperator) res.push(this.apiOperationDecorator(name, conf)); if (apiResp) res.push(this.allApiResponseDecorators(conf)); if (apiReq) res.push(this.apiRequestDecorator(conf)); res.push((0, templates_1.functionPromiseGenerator)(interfaces_2.ReqNames[name], this.paramController(conf, this.config.access), this.parent.replace(conf.resp), this.parent.replace(this.controllerFunctionBody(name, conf)))); return res.join('\n'); } serviceFunction(name, conf) { let res = []; res.push((0, templates_1.functionPromiseGenerator)(interfaces_2.ReqNames[name], this.parent.replace(this.paramService(conf, this.config.access)), this.parent.replace(conf.resp), this.parent.replace(this.serviceFunctionBody(conf, name)))); return res.join('\n\n'); } serviceFunctionBody(conf, name) { let res = []; const service = this.config.access && !this.config.accessBlackList.includes(this.parent.namePascal) ? conf.serviceAccess : conf.service; let fix = service; if (this.parent.idsNoDefault.length > 0) { if (fix.includes('createMany') && conf.bodyArray) { fix = service.replace('...b ', ` ${this.parent.idsNoDefault .map((id) => { return `${id.name}:this.${id.name}Gen()`; }) .join(`,`)} , ...b `); } else if (fix.includes('create') && !conf.bodyArray) { fix = service.replace('...body', ` ${this.parent.idsNoDefault .map((id) => { return `${id.name}:this.${id.name}Gen()`; }) .join(`,`)} , ...body `); } } res.push(fix); return res.join('\n'); } controllerClassConstructor() { let res = []; res.push((0, templates_1.constructorGenerator)((0, templates_1.parameterPrivateGenerator)(this.parent.nameCamel + 'Service', this.parent.namePascal + 'Service'), '')); return res.join('\n'); } serviceClassConstructor() { let res = []; res.push((0, templates_1.constructorGenerator)((0, templates_1.parameterPrivateGenerator)('prismaService', 'PrismaService'), '')); return res.join('\n'); } controllerImport() { let res = []; if (this.config.additionalImport) { this.config.additionalImport.map((i) => { res.push(i); }); } res.push(`import { ${this.parent.namePascal} } from './${this.parent.nameCamel}.entity';`); res.push(`import { Find${this.parent.namePascal}Dto, Create${this.parent.namePascal}Dto, Update${this.parent.namePascal}Dto, Connect${this.parent.namePascal}Dto, Find${this.parent.namePascal}AdminDto, Create${this.parent.namePascal}AdminDto, Update${this.parent.namePascal}AdminDto, Connect${this.parent.namePascal}AdminDto, Access${this.parent.namePascal}Dto, Deleted${this.parent.namePascal}Dto, Pseudonymisation${this.parent.namePascal}Dto } from './${this.parent.nameCamel}.dto';`); res.push(`import { Body, Controller, Delete, Get, HttpCode, HttpStatus,Query, NotFoundException, Param, Post, Patch, Put, UnauthorizedException, ForbiddenException, ConflictException, Req,Injectable } from '@nestjs/common'; import { ApiBearerAuth, ApiBody, ApiConflictResponse, ApiConsumes, ApiCreatedResponse, ApiNotFoundResponse, ApiOkResponse, ApiOperation, ApiParam, ApiQuery, ApiResponse, ApiTags, ApiUnauthorizedResponse, } from '@nestjs/swagger';`, "import { Prisma } from '@prisma/client';"); res.push(`import { UserGeneralDto } from 'src/shared/dtos/user.dto';`); res.push(`import { plainToInstance } from 'class-transformer';`); res.push(`import { User as UserDecorator } from 'src/shared/decorators/user.decorator'; `); res.push(`import { ${this.parent.namePascal}Service } from './${this.parent.nameCamel}.service';`); return res.join('\n'); } serviceImport() { let res = []; if (this.config.additionalImport) { this.config.additionalImport.map((i) => { res.push(i); }); } res.push(`import { ${this.parent.namePascal} } from './${this.parent.nameCamel}.entity';`); res.push(`import { plainToInstance } from 'class-transformer';`); res.push(`import { PrismaService } from 'src/shared/services/prisma.service';`); res.push(`import { UserGeneralDto } from 'src/shared/dtos/user.dto';`); res.push(`import { User as UserDecorator } from 'src/shared/decorators/user.decorator'; `); res.push(`import { Find${this.parent.namePascal}Dto, Create${this.parent.namePascal}Dto, Update${this.parent.namePascal}Dto, Connect${this.parent.namePascal}Dto, Find${this.parent.namePascal}AdminDto, Create${this.parent.namePascal}AdminDto, Update${this.parent.namePascal}AdminDto, Connect${this.parent.namePascal}AdminDto, Access${this.parent.namePascal}Dto, Deleted${this.parent.namePascal}Dto, Pseudonymisation${this.parent.namePascal}Dto } from './${this.parent.nameCamel}.dto';`); res.push(`import { Body, Controller, Delete, Get, HttpCode, HttpStatus,Query, NotFoundException, Param, Post, Patch, Put, UnauthorizedException, ForbiddenException, ConflictException, Req,Injectable } from '@nestjs/common'; import { ApiBearerAuth, ApiBody, ApiConflictResponse, ApiConsumes, ApiCreatedResponse, ApiNotFoundResponse, ApiOkResponse, ApiOperation, ApiParam, ApiQuery, ApiResponse, ApiTags, ApiUnauthorizedResponse, } from '@nestjs/swagger';`, "import { Prisma } from '@prisma/client';"); let prismaImport = []; this.parent.enumFields.map((f) => { prismaImport.push(` ${f.type},`); }); res.push('import { ' + prismaImport.join('\n') + "} from '@prisma/client'"); return res.join('\n'); } controllerGenerator(body) { let res = []; res.push(this.controllerImport()); res.push((0, templates_1.classGenerator)(this.parent.namePascal + 'Controller', body, this.controllerClassDecorator())); return res.join('\n'); } serviceGenerator(body) { let res = []; res.push(this.serviceImport()); res.push((0, templates_1.classGenerator)(this.parent.namePascal + 'Service', body, this.serviceClassDecorator())); return res.join('\n'); } } exports.default = CRUD; //# sourceMappingURL=CRUD.js.map