ts-template.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. const _ = require('lodash');
  2. const getModelType = (type) => {
  3. let modelType = 'string';
  4. if (type === 'Money' || type === 'money') modelType = 'Decimal128';
  5. else if (type === 'ObjectId') modelType = 'ObjectId';
  6. else if (type === 'Array') modelType = 'Array';
  7. else modelType = _.lowerFirst(type);
  8. return modelType;
  9. };
  10. const ModelContext = (data) => {
  11. const result = [];
  12. const { name: table_name, columns } = data;
  13. const prefix = _.upperFirst(table_name);
  14. let fc = [];
  15. fc.push(`import { modelOptions, prop } from '@typegoose/typegoose';`);
  16. fc.push(`import { BaseModel } from 'free-midway-component';`);
  17. const has_money = columns.find((f) => f.type === 'Money' || f.type === 'money');
  18. if (has_money) fc.push(`import { Decimal128 } from 'mongoose';`);
  19. fc.push(`@modelOptions({`);
  20. fc.push(` schemaOptions: { collection: '${table_name}' },`);
  21. fc.push(`})`);
  22. fc.push(`export class ${prefix} extends BaseModel {`);
  23. // 处理字段
  24. for (const col of columns) {
  25. const { type, required, index, title, zh } = col;
  26. const prop = { required, index, zh };
  27. const modelType = getModelType(type);
  28. fc.push(` @prop(${JSON.stringify(prop)})`);
  29. fc.push(` ${title}: ${modelType}`);
  30. }
  31. fc.push(`}`);
  32. // 最后换行转为字符串
  33. const fileContext = fc.join('\n');
  34. return fileContext;
  35. };
  36. const ServiceContext = (data) => {
  37. const fc = [];
  38. const { name: table_name } = data;
  39. const prefix = _.upperFirst(table_name);
  40. fc.push(`import { Provide } from '@midwayjs/decorator';`);
  41. fc.push(`import { InjectEntityModel } from '@midwayjs/typegoose';`);
  42. fc.push(`import { ReturnModelType } from '@typegoose/typegoose';`);
  43. fc.push(`import { BaseService } from 'free-midway-component';`);
  44. fc.push(`import { ${prefix} } from '../entity/${table_name}';`);
  45. fc.push(`type modelType = ReturnModelType<typeof ${prefix}>;`);
  46. fc.push(`@Provide()`);
  47. fc.push(`export class ${prefix}Service extends BaseService<modelType> {`);
  48. fc.push(` @InjectEntityModel(${prefix})`);
  49. fc.push(` model: modelType;`);
  50. fc.push(`}`);
  51. return fc.join('\n');
  52. };
  53. const ControllerContext = (data) => {
  54. const fc = [];
  55. const { name: table_name, zh } = data;
  56. const prefix = _.upperFirst(table_name);
  57. fc.push(`import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/decorator';`);
  58. fc.push(`import { BaseController } from 'free-midway-component';`);
  59. fc.push(`import { ${prefix}Service } from '../service/${table_name}.service';`);
  60. fc.push(`import { CreateDTO, CreateVO, FetchVO, QueryDTO, QueryVO, UpdateDTO, UpdateVO } from '../interface/${table_name}.interface';`);
  61. fc.push(`import { ApiResponse, ApiTags } from '@midwayjs/swagger';`);
  62. fc.push(`import { Validate } from '@midwayjs/validate';`);
  63. fc.push(`@ApiTags(['${zh}'])`);
  64. fc.push(`@Controller('/${prefix}')`);
  65. fc.push(`export class ${prefix}Controller extends BaseController {`);
  66. fc.push(` @Inject()`);
  67. fc.push(` service: ${prefix}Service;`);
  68. fc.push('\n');
  69. // create
  70. fc.push(`@Post('/') @Validate() @ApiResponse({ type: CreateVO })`);
  71. fc.push(` async create(@Body() data: CreateDTO) {`);
  72. fc.push(` const result = await this.service.create(data);`);
  73. fc.push(` return result;`);
  74. fc.push(` }`);
  75. // query
  76. fc.push(`@Get('/')@ApiResponse({ type: QueryVO })`);
  77. fc.push(` async query(@Query('filter') filter: QueryDTO, @Query('skip') skip: number,@Query('limit') limit: number){`);
  78. fc.push(` const data = await this.service.query(filter, { skip, limit });`);
  79. fc.push(` const total = await this.service.count(filter);`);
  80. fc.push(` return { data, total };`);
  81. fc.push(` }`);
  82. fc.push(`\n`);
  83. // fetch
  84. fc.push(`@Get('/:id')@ApiResponse({ type: FetchVO })`);
  85. fc.push(` async fetch(@Param('id') id: string) {`);
  86. fc.push(` const data = await this.service.fetch(id);`);
  87. fc.push(` const result = new FetchVO(data);`);
  88. fc.push(` return result;`);
  89. fc.push(` }`);
  90. fc.push(`\n`);
  91. // update
  92. fc.push(`@Post('/:id')@Validate()@ApiResponse({ type: UpdateVO })`);
  93. fc.push(` async update(@Param('id') id: string, @Body() body: UpdateDTO) {`);
  94. fc.push(` const result = await this.service.updateOne(id, body);`);
  95. fc.push(` return result;`);
  96. fc.push(` }`);
  97. fc.push(`\n`);
  98. // delete
  99. fc.push(`@Del('/:id')@Validate()`);
  100. fc.push(` async delete(@Param('id') id: string) {`);
  101. fc.push(` await this.service.delete(id);`);
  102. fc.push(` return 'ok';`);
  103. fc.push(` }`);
  104. // other bat deal
  105. fc.push(` async createMany(...args: any[]) {`);
  106. fc.push(` throw new Error('Method not implemented.');`);
  107. fc.push(` }`);
  108. fc.push(`\n`);
  109. fc.push(` async updateMany(...args: any[]) {`);
  110. fc.push(` throw new Error('Method not implemented.');`);
  111. fc.push(` }`);
  112. fc.push(`\n`);
  113. fc.push(` async deleteMany(...args: any[]) {`);
  114. fc.push(` throw new Error('Method not implemented.');`);
  115. fc.push(` }`);
  116. fc.push(`\n`);
  117. return fc.join(`\n`);
  118. };
  119. /**
  120. *
  121. * @param {Object} col 字段
  122. * @param {boolean} needReq 是否启用必须,针对post设置
  123. * @returns
  124. */
  125. const getInterfaceColumn = (col, needReq = false) => {
  126. const fc = [];
  127. const { type, zh, title, required } = col;
  128. const modelType = getModelType(type);
  129. fc.push(` @ApiProperty({ description: '${title}' })`);
  130. if (needReq && required) {
  131. const ruleStr = `@Rule(RuleType['${modelType}']().required().error(new ServiceError('缺少${zh}',FrameworkErrorEnum.${needReq ? 'NEED_BODY' : 'NEED_QUERY'})))`;
  132. fc.push(ruleStr);
  133. }
  134. fc.push(` '${title}': ${modelType} = undefined;`);
  135. return fc;
  136. };
  137. const interfaceContext = (data) => {
  138. const fc = [];
  139. const { columns = [] } = data;
  140. fc.push(`import { Rule, RuleType } from '@midwayjs/validate';`);
  141. fc.push(`import { ApiProperty } from '@midwayjs/swagger';`);
  142. fc.push(`import _ = require('lodash');`);
  143. fc.push(`import { FrameworkErrorEnum, SearchBase, ServiceError } from 'free-midway-component';`);
  144. fc.push(`export class FetchVO {`);
  145. fc.push(` constructor(data: object) {`);
  146. fc.push(` for (const key of Object.keys(this)) {`);
  147. fc.push(` this[key] = _.get(data, key);`);
  148. fc.push(` }`);
  149. fc.push(` }`);
  150. for (const col of columns) {
  151. const cfc = getInterfaceColumn(col);
  152. fc.push(...cfc);
  153. }
  154. fc.push(`}`);
  155. fc.push(`\n`);
  156. fc.push(`export class QueryDTO extends SearchBase {`);
  157. fc.push(` constructor() {`);
  158. fc.push(` const like_prop = [];`);
  159. fc.push(` super({ like_prop });`);
  160. fc.push(` }`);
  161. for (const col of columns.filter((f) => f.index)) {
  162. const cfc = getInterfaceColumn(col);
  163. fc.push(...cfc);
  164. }
  165. fc.push(`}`);
  166. fc.push(`\n`);
  167. fc.push(`export class QueryVO extends FetchVO {}`);
  168. fc.push(`\n`);
  169. fc.push(`export class CreateDTO {`);
  170. for (const col of columns) {
  171. const cfc = getInterfaceColumn(col, true);
  172. fc.push(...cfc);
  173. }
  174. fc.push(`}`);
  175. fc.push(`\n`);
  176. fc.push(`export class CreateVO extends FetchVO {}`);
  177. fc.push(`\n`);
  178. fc.push(`export class UpdateDTO extends CreateDTO {}`);
  179. fc.push(`\n`);
  180. fc.push(`export class UpdateVO extends FetchVO {}`);
  181. return fc.join('\n');
  182. };
  183. module.exports = (data) => {
  184. let result = `\n========== Model ==========\n`;
  185. result += ModelContext(data);
  186. result += `\n========== Service ==========\n`;
  187. result += ServiceContext(data);
  188. result += `\n========== Controller ==========\n`;
  189. result += ControllerContext(data);
  190. result += `\n========== interface ==========\n`;
  191. result += interfaceContext(data);
  192. return result;
  193. };