ts-template.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 dbData = await this.service.create(data);`);
  75. fc.push(` const result = new CVO_activitys(dbData);`);
  76. fc.push(` return result;`);
  77. fc.push(` }`);
  78. // query
  79. fc.push(`@Get('/')@ApiQuery({name:'query'})@ApiResponse({ type: QVO_${name} })`);
  80. fc.push(` async query(@Query() filter:QDTO_${name}, @Query('skip') skip: number,@Query('limit') limit: number){`);
  81. fc.push(` const list = await this.service.query(filter, { skip, limit });`);
  82. fc.push(` const data = [];`);
  83. fc.push(` for (const i of list) {`);
  84. fc.push(` const newData = new QVO_activitys(i);`);
  85. fc.push(` data.push(newData);`);
  86. fc.push(` }`);
  87. fc.push(` const total = await this.service.count(filter);`);
  88. fc.push(` return { data, total };`);
  89. fc.push(` }`);
  90. fc.push(`\n`);
  91. // fetch
  92. fc.push(`@Get('/:id')@ApiResponse({ type: FVO_${name} })`);
  93. fc.push(` async fetch(@Param('id') id: string) {`);
  94. fc.push(` const data = await this.service.fetch(id);`);
  95. fc.push(` const result = new FVO_${name}(data);`);
  96. fc.push(` return result;`);
  97. fc.push(` }`);
  98. fc.push(`\n`);
  99. // update
  100. fc.push(`@Post('/:id')@Validate()@ApiResponse({ type: UVAO_${name} })`);
  101. fc.push(` async update(@Param('id') id: string, @Body() body: UDTO_${name}) {`);
  102. fc.push(` const result = await this.service.updateOne(id, body);`);
  103. fc.push(` return result;`);
  104. fc.push(` }`);
  105. fc.push(`\n`);
  106. // delete
  107. fc.push(`@Del('/:id')@Validate()`);
  108. fc.push(` async delete(@Param('id') id: string) {`);
  109. fc.push(` await this.service.delete(id);`);
  110. fc.push(` return 'ok';`);
  111. fc.push(` }`);
  112. // other bat deal
  113. fc.push(` async createMany(...args: any[]) {`);
  114. fc.push(` throw new Error('Method not implemented.');`);
  115. fc.push(` }`);
  116. fc.push(`\n`);
  117. fc.push(` async updateMany(...args: any[]) {`);
  118. fc.push(` throw new Error('Method not implemented.');`);
  119. fc.push(` }`);
  120. fc.push(`\n`);
  121. fc.push(` async deleteMany(...args: any[]) {`);
  122. fc.push(` throw new Error('Method not implemented.');`);
  123. fc.push(` }`);
  124. fc.push(`}`);
  125. fc.push(`\n`);
  126. return fc.join(`\n`);
  127. };
  128. /**
  129. *
  130. * @param {Object} col 字段
  131. * @param {boolean} needReq 是否启用必须,针对post设置
  132. * @returns
  133. */
  134. const getInterfaceColumn = (col, needReq = false) => {
  135. const fc = [];
  136. const { type, zh, title, required } = col;
  137. const modelType = getModelType(type, true);
  138. fc.push(` @ApiProperty({ description: '${zh}' })`);
  139. if (needReq) {
  140. let ruleStr = '';
  141. let rt = '';
  142. if (type === 'Money' || type === 'money') rt = 'number';
  143. else rt = _.lowerFirst(type);
  144. if (required) ruleStr = `@Rule(RuleType['${rt}']().required().error(new ServiceError('缺少${zh}',FrameworkErrorEnum.${needReq ? 'NEED_BODY' : 'NEED_QUERY'})))`;
  145. else ruleStr = `@Rule(RuleType['${rt}']().empty(''))`;
  146. fc.push(ruleStr);
  147. }
  148. fc.push(` '${title}': ${modelType} = undefined;`);
  149. return fc;
  150. };
  151. const interfaceContext = (data) => {
  152. const fc = [];
  153. const { columns = [], name } = data;
  154. const have_required = columns.find((f) => f.required);
  155. fc.push(`import { Rule, RuleType } from '@midwayjs/validate';`);
  156. fc.push(`import { ApiProperty } from '@midwayjs/swagger';`);
  157. if (have_required) fc.push(`import { FrameworkErrorEnum, SearchBase, ServiceError } from 'free-midway-component';`);
  158. else fc.push(`import { SearchBase } from 'free-midway-component';`);
  159. fc.push(`import get = require('lodash/get');`);
  160. fc.push(`const dealVO = (cla, data) => {`);
  161. fc.push(` for (const key in cla) {`);
  162. fc.push(` const val = get(data, key);`);
  163. fc.push(` if (val || val === 0) cla[key] = val;`);
  164. fc.push(` }`);
  165. fc.push(`};`);
  166. fc.push(`export class FVO_${name} {`);
  167. fc.push(` constructor(data: object) {`);
  168. fc.push(` dealVO(this, data);`);
  169. fc.push(` }`);
  170. fc.push(` @ApiProperty({ description: '数据id' })`);
  171. fc.push(` _id: string = undefined;`);
  172. for (const col of columns) {
  173. const cfc = getInterfaceColumn(col);
  174. fc.push(...cfc);
  175. }
  176. fc.push(`}`);
  177. fc.push(`\n`);
  178. const indexs = columns.filter((f) => f.index);
  179. const props = indexs.map((i) => `'${i.title}'`).join(', ');
  180. fc.push(`export class QDTO_${name} extends SearchBase {`);
  181. fc.push(` constructor() {`);
  182. fc.push(` const like_prop = [];`);
  183. fc.push(` const props = [${props}];`);
  184. fc.push(` const mapping = [];`);
  185. fc.push(` super({ like_prop, props, mapping });`);
  186. fc.push(` }`);
  187. for (const col of indexs) {
  188. const cfc = getInterfaceColumn(col);
  189. fc.push(...cfc);
  190. }
  191. fc.push(`}`);
  192. fc.push(`\n`);
  193. fc.push(`export class QVO_${name} extends FVO_${name} {`);
  194. fc.push(` constructor(data: object) {`);
  195. fc.push(` super(data);`);
  196. fc.push(` dealVO(this, data);`);
  197. fc.push(` }`);
  198. fc.push(`}`);
  199. fc.push(`\n`);
  200. fc.push(`export class CDTO_${name} {`);
  201. for (const col of columns) {
  202. const cfc = getInterfaceColumn(col, true);
  203. fc.push(...cfc);
  204. }
  205. fc.push(`}`);
  206. fc.push(`\n`);
  207. fc.push(`export class CVO_${name} extends FVO_${name} {`);
  208. fc.push(` constructor(data: object) {`);
  209. fc.push(` super(data);`);
  210. fc.push(` dealVO(this, data);`);
  211. fc.push(` }`);
  212. fc.push(`}`);
  213. fc.push(`\n`);
  214. fc.push(`export class UDTO_${name} extends CDTO_${name} {
  215. @ApiProperty({ description: '数据id' })
  216. @Rule(RuleType['string']().empty(''))
  217. _id: string = undefined;
  218. }`);
  219. fc.push(`\n`);
  220. fc.push(`export class UVAO_${name} extends FVO_${name} {`);
  221. fc.push(` constructor(data: object) {`);
  222. fc.push(` super(data);`);
  223. fc.push(` dealVO(this, data);`);
  224. fc.push(` }`);
  225. fc.push(`}`);
  226. return fc.join('\n');
  227. };
  228. module.exports = (data) => {
  229. let result = `\n========== Model ==========\n`;
  230. result += ModelContext(data);
  231. result += `\n========== Service ==========\n`;
  232. result += ServiceContext(data);
  233. result += `\n========== Controller ==========\n`;
  234. result += ControllerContext(data);
  235. result += `\n========== interface ==========\n`;
  236. result += interfaceContext(data);
  237. return result;
  238. };