ts-template.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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, title } = col;
  26. const prop = _.pick(col, ['required', 'index', 'zh', 'remark']);
  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, 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(
  61. `import { CreateDTO_${name}, CreateVO_${name}, FetchVO_${name}, QueryDTO_${name}, QueryVO_${name}, UpdateDTO_${name}, UpdateVO_${name} } from '../interface/${table_name}.interface';`
  62. );
  63. fc.push(`import { ApiResponse, ApiTags } from '@midwayjs/swagger';`);
  64. fc.push(`import { Validate } from '@midwayjs/validate';`);
  65. fc.push(`@ApiTags(['${name_zh}'])`);
  66. fc.push(`@Controller('/${table_name}')`);
  67. fc.push(`export class ${prefix}Controller extends BaseController {`);
  68. fc.push(` @Inject()`);
  69. fc.push(` service: ${prefix}Service;`);
  70. fc.push('\n');
  71. // create
  72. fc.push(`@Post('/') @Validate() @ApiResponse({ type: CreateVO_${name} })`);
  73. fc.push(` async create(@Body() data: CreateDTO_${name}) {`);
  74. fc.push(` const result = await this.service.create(data);`);
  75. fc.push(` return result;`);
  76. fc.push(` }`);
  77. // query
  78. fc.push(`@Get('/')@ApiResponse({ type: QueryVO_${name} })`);
  79. fc.push(` async query(@Query('filter') filter: QueryDTO_${name}, @Query('skip') skip: number,@Query('limit') limit: number){`);
  80. fc.push(` const data = await this.service.query(filter, { skip, limit });`);
  81. fc.push(` const total = await this.service.count(filter);`);
  82. fc.push(` return { data, total };`);
  83. fc.push(` }`);
  84. fc.push(`\n`);
  85. // fetch
  86. fc.push(`@Get('/:id')@ApiResponse({ type: FetchVO_${name} })`);
  87. fc.push(` async fetch(@Param('id') id: string) {`);
  88. fc.push(` const data = await this.service.fetch(id);`);
  89. fc.push(` const result = new FetchVO_${name}(data);`);
  90. fc.push(` return result;`);
  91. fc.push(` }`);
  92. fc.push(`\n`);
  93. // update
  94. fc.push(`@Post('/:id')@Validate()@ApiResponse({ type: UpdateVO_${name} })`);
  95. fc.push(` async update(@Param('id') id: string, @Body() body: UpdateDTO_${name}) {`);
  96. fc.push(` const result = await this.service.updateOne(id, body);`);
  97. fc.push(` return result;`);
  98. fc.push(` }`);
  99. fc.push(`\n`);
  100. // delete
  101. fc.push(`@Del('/:id')@Validate()`);
  102. fc.push(` async delete(@Param('id') id: string) {`);
  103. fc.push(` await this.service.delete(id);`);
  104. fc.push(` return 'ok';`);
  105. fc.push(` }`);
  106. // other bat deal
  107. fc.push(` async createMany(...args: any[]) {`);
  108. fc.push(` throw new Error('Method not implemented.');`);
  109. fc.push(` }`);
  110. fc.push(`\n`);
  111. fc.push(` async updateMany(...args: any[]) {`);
  112. fc.push(` throw new Error('Method not implemented.');`);
  113. fc.push(` }`);
  114. fc.push(`\n`);
  115. fc.push(` async deleteMany(...args: any[]) {`);
  116. fc.push(` throw new Error('Method not implemented.');`);
  117. fc.push(` }`);
  118. fc.push(`}`);
  119. fc.push(`\n`);
  120. return fc.join(`\n`);
  121. };
  122. /**
  123. *
  124. * @param {Object} col 字段
  125. * @param {boolean} needReq 是否启用必须,针对post设置
  126. * @returns
  127. */
  128. const getInterfaceColumn = (col, needReq = false) => {
  129. const fc = [];
  130. const { type, zh, title, required } = col;
  131. const modelType = getModelType(type);
  132. fc.push(` @ApiProperty({ description: '${title}' })`);
  133. if (needReq && required) {
  134. const ruleStr = `@Rule(RuleType['${modelType}']().required().error(new ServiceError('缺少${zh}',FrameworkErrorEnum.${needReq ? 'NEED_BODY' : 'NEED_QUERY'})))`;
  135. fc.push(ruleStr);
  136. }
  137. fc.push(` '${title}': ${modelType} = undefined;`);
  138. return fc;
  139. };
  140. const interfaceContext = (data) => {
  141. const fc = [];
  142. const { columns = [],name } = data;
  143. fc.push(`import { Rule, RuleType } from '@midwayjs/validate';`);
  144. fc.push(`import { ApiProperty } from '@midwayjs/swagger';`);
  145. fc.push(`import _ = require('lodash');`);
  146. fc.push(`import { FrameworkErrorEnum, SearchBase, ServiceError } from 'free-midway-component';`);
  147. fc.push(`export class FetchVO_${name} {`);
  148. fc.push(` constructor(data: object) {`);
  149. fc.push(` for (const key of Object.keys(this)) {`);
  150. fc.push(` this[key] = _.get(data, key);`);
  151. fc.push(` }`);
  152. fc.push(` }`);
  153. for (const col of columns) {
  154. const cfc = getInterfaceColumn(col);
  155. fc.push(...cfc);
  156. }
  157. fc.push(`}`);
  158. fc.push(`\n`);
  159. fc.push(`export class QueryDTO extends SearchBase {`);
  160. fc.push(` constructor() {`);
  161. fc.push(` const like_prop = [];`);
  162. fc.push(` super({ like_prop });`);
  163. fc.push(` }`);
  164. for (const col of columns.filter((f) => f.index)) {
  165. const cfc = getInterfaceColumn(col);
  166. fc.push(...cfc);
  167. }
  168. fc.push(`}`);
  169. fc.push(`\n`);
  170. fc.push(`export class QueryVO_${name} extends FetchVO_${name} {}`);
  171. fc.push(`\n`);
  172. fc.push(`export class CreateDTO_${name} {`);
  173. for (const col of columns) {
  174. const cfc = getInterfaceColumn(col, true);
  175. fc.push(...cfc);
  176. }
  177. fc.push(`}`);
  178. fc.push(`\n`);
  179. fc.push(`export class CreateVO_${name} extends FetchVO_${name} {}`);
  180. fc.push(`\n`);
  181. fc.push(`export class UpdateDTO_${name} extends CreateDTO_${name} {}`);
  182. fc.push(`\n`);
  183. fc.push(`export class UpdateVO_${name} extends FetchVO_${name} {}`);
  184. return fc.join('\n');
  185. };
  186. module.exports = (data) => {
  187. let result = `\n========== Model ==========\n`;
  188. result += ModelContext(data);
  189. result += `\n========== Service ==========\n`;
  190. result += ServiceContext(data);
  191. result += `\n========== Controller ==========\n`;
  192. result += ControllerContext(data);
  193. result += `\n========== interface ==========\n`;
  194. result += interfaceContext(data);
  195. return result;
  196. };