ts-template.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. const _ = require('lodash');
  2. const getModelType = (type, interf = false) => {
  3. let modelType = 'string';
  4. if (type === 'Money' || type === 'money') {
  5. if (!interf) modelType = 'Decimal128';
  6. else modelType = 'number';
  7. } else if (type === 'ObjectId') modelType = 'ObjectId';
  8. else if (type === 'Array') modelType = 'Array<any>';
  9. else modelType = _.lowerFirst(type);
  10. return modelType;
  11. };
  12. const ModelContext = (data) => {
  13. const { name: table_name, columns } = data;
  14. const prefix = _.upperFirst(table_name);
  15. let fc = [];
  16. fc.push(`import { modelOptions, prop } from '@typegoose/typegoose';`);
  17. fc.push(`import { BaseModel } from 'free-midway-component';`);
  18. const has_money = columns.find((f) => f.type === 'Money' || f.type === 'money');
  19. if (has_money) fc.push(`import { Decimal128 } from 'mongoose';`);
  20. fc.push(`@modelOptions({`);
  21. fc.push(` schemaOptions: { collection: '${table_name}' },`);
  22. fc.push(`})`);
  23. fc.push(`export class ${prefix} extends BaseModel {`);
  24. // 处理字段
  25. for (const col of columns) {
  26. const { type, title, def } = col;
  27. const prop = _.pick(col, ['required', 'index', 'zh', 'ref', 'remark']);
  28. if (def) prop.default = def;
  29. const modelType = getModelType(type);
  30. fc.push(` @prop(${JSON.stringify(prop)})`);
  31. fc.push(` ${title}: ${modelType}`);
  32. }
  33. fc.push(`}`);
  34. // 最后换行转为字符串
  35. const fileContext = fc.join('\n');
  36. return fileContext;
  37. };
  38. const ServiceContext = (data) => {
  39. const fc = [];
  40. const { name: table_name } = data;
  41. const prefix = _.upperFirst(table_name);
  42. fc.push(`import { Provide } from '@midwayjs/decorator';`);
  43. fc.push(`import { InjectEntityModel } from '@midwayjs/typegoose';`);
  44. fc.push(`import { ReturnModelType } from '@typegoose/typegoose';`);
  45. fc.push(`import { BaseService } from 'free-midway-component';`);
  46. fc.push(`import { ${prefix} } from '../entity/${_.lowerFirst(table_name)}.entity';`);
  47. fc.push(`type modelType = ReturnModelType<typeof ${prefix}>;`);
  48. fc.push(`@Provide()`);
  49. fc.push(`export class ${prefix}Service extends BaseService<modelType> {`);
  50. fc.push(` @InjectEntityModel(${prefix})`);
  51. fc.push(` model: modelType;`);
  52. fc.push(`}`);
  53. return fc.join('\n');
  54. };
  55. const ControllerContext = (data) => {
  56. const fc = [];
  57. const { name, name_zh } = data;
  58. const prefix = _.upperFirst(name);
  59. fc.push(`import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/decorator';`);
  60. fc.push(`import { BaseController } from 'free-midway-component';`);
  61. fc.push(`import { ${prefix}Service } from '../service/${_.lowerFirst(name)}.service';`);
  62. fc.push(`import { CDTO_${name}, CVO_${name}, FVO_${name},QDTO_${name}, QVO_${name}, UDTO_${name}, UVAO_${name} } from '../interface/${_.lowerFirst(name)}.interface';`);
  63. fc.push(`import { ApiResponse, ApiTags, ApiQuery } from '@midwayjs/swagger';`);
  64. fc.push(`import { Validate } from '@midwayjs/validate';`);
  65. fc.push(`@ApiTags(['${name_zh}'])`);
  66. fc.push(`@Controller('/${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: CVO_${name} })`);
  73. fc.push(` async create(@Body() data: CDTO_${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('/')@ApiQuery({name:'query'})@ApiResponse({ type: QVO_${name} })`);
  79. fc.push(` async query(@Query() filter:QDTO_${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: FVO_${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 FVO_${name}(data);`);
  90. fc.push(` return result;`);
  91. fc.push(` }`);
  92. fc.push(`\n`);
  93. // update
  94. fc.push(`@Post('/:id')@Validate()@ApiResponse({ type: UVAO_${name} })`);
  95. fc.push(` async update(@Param('id') id: string, @Body() body: UDTO_${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, true);
  132. fc.push(` @ApiProperty({ description: '${zh}' })`);
  133. if (needReq) {
  134. let ruleStr = '';
  135. let rt = '';
  136. if (type === 'Money' || type === 'money') rt = 'number';
  137. else rt = _.lowerFirst(type);
  138. if (required) ruleStr = `@Rule(RuleType['${rt}']().required().error(new ServiceError('缺少${zh}',FrameworkErrorEnum.${needReq ? 'NEED_BODY' : 'NEED_QUERY'})))`;
  139. else ruleStr = `@Rule(RuleType['${rt}']().empty(''))`;
  140. fc.push(ruleStr);
  141. }
  142. fc.push(` '${title}': ${modelType} = undefined;`);
  143. return fc;
  144. };
  145. const interfaceContext = (data) => {
  146. const fc = [];
  147. const { columns = [], name } = data;
  148. const have_required = columns.find((f) => f.required);
  149. fc.push(`import { Rule, RuleType } from '@midwayjs/validate';`);
  150. fc.push(`import { ApiProperty } from '@midwayjs/swagger';`);
  151. if (have_required) fc.push(`import { FrameworkErrorEnum, SearchBase, ServiceError } from 'free-midway-component';`);
  152. else fc.push(`import { SearchBase } from 'free-midway-component';`);
  153. fc.push(`import get = require('lodash/get');`);
  154. fc.push(`const dealVO = (cla, data) => {`);
  155. fc.push(` for (const key in cla) {`);
  156. fc.push(` const val = get(data, key);`);
  157. fc.push(` if (val || val === 0) cla[key] = val;`);
  158. fc.push(` }`);
  159. fc.push(`};`);
  160. fc.push(`export class FVO_${name} {`);
  161. fc.push(` constructor(data: object) {`);
  162. fc.push(` dealVO(this, data);`);
  163. fc.push(` }`);
  164. fc.push(` @ApiProperty({ description: '数据id' })`);
  165. fc.push(` _id: string = undefined;`);
  166. for (const col of columns) {
  167. const cfc = getInterfaceColumn(col);
  168. fc.push(...cfc);
  169. }
  170. fc.push(`}`);
  171. fc.push(`\n`);
  172. const indexs = columns.filter((f) => f.index);
  173. const props = indexs.map((i) => `'${i.title}'`).join(', ');
  174. fc.push(`export class QDTO_${name} extends SearchBase {`);
  175. fc.push(` constructor() {`);
  176. fc.push(` const like_prop = [];`);
  177. fc.push(` const props = [${props}];`);
  178. fc.push(` const mapping = [];`);
  179. fc.push(` super({ like_prop, props, mapping });`);
  180. fc.push(` }`);
  181. for (const col of indexs) {
  182. const cfc = getInterfaceColumn(col);
  183. fc.push(...cfc);
  184. }
  185. fc.push(`}`);
  186. fc.push(`\n`);
  187. fc.push(`export class QVO_${name} extends FVO_${name} {`);
  188. fc.push(` constructor(data: object) {`);
  189. fc.push(` super(data);`);
  190. fc.push(` dealVO(this, data);`);
  191. fc.push(` }`);
  192. fc.push(`}`);
  193. fc.push(`\n`);
  194. fc.push(`export class CDTO_${name} {`);
  195. for (const col of columns) {
  196. const cfc = getInterfaceColumn(col, true);
  197. fc.push(...cfc);
  198. }
  199. fc.push(`}`);
  200. fc.push(`\n`);
  201. fc.push(`export class CVO_${name} extends FVO_${name} {`);
  202. fc.push(` constructor(data: object) {`);
  203. fc.push(` super(data);`);
  204. fc.push(` dealVO(this, data);`);
  205. fc.push(` }`);
  206. fc.push(`}`);
  207. fc.push(`\n`);
  208. fc.push(`export class UDTO_${name} extends CDTO_${name} {
  209. @ApiProperty({ description: '数据id' })
  210. @Rule(RuleType['string']().empty(''))
  211. _id: string = undefined;
  212. }`);
  213. fc.push(`\n`);
  214. fc.push(`export class UVAO_${name} extends FVO_${name} {`);
  215. fc.push(` constructor(data: object) {`);
  216. fc.push(` super(data);`);
  217. fc.push(` dealVO(this, data);`);
  218. fc.push(` }`);
  219. fc.push(`}`);
  220. return fc.join('\n');
  221. };
  222. module.exports = (data) => {
  223. let result = `\n========== Model ==========\n`;
  224. result += ModelContext(data);
  225. result += `\n========== Service ==========\n`;
  226. result += ServiceContext(data);
  227. result += `\n========== Controller ==========\n`;
  228. result += ControllerContext(data);
  229. result += `\n========== interface ==========\n`;
  230. result += interfaceContext(data);
  231. return result;
  232. };