Commit 02308ab5 authored by qinhaitao's avatar qinhaitao

feat: 🎸 删除complieServer

parent 94294d15
This diff is collapsed.
/** @format */
const fs = require('fs-extra')
const config = require('./config.json')
const { getDecorators, getPreChecks, getPreUpdates } = require('./utils/formatConfg')
const serverTemplatePath = 'templates'
const controllerImport = (controller = {}) => {
const result = {
services: {}
}
for (let fn in controller) {
for (let main of controller[fn].main) {
if (!result.services[main.type]) {
result.services[main.type] = {}
}
result.services[main.type][main.service] = true
}
}
return result
}
const customFileMap = (controllers = {}) => {
const result = {
decorators: {},
utils: {},
services: {}
}
for (let controllerType in controllers) {
for (let controller in controllers[controllerType]) {
for (let fn in controllers[controllerType][controller]) {
for (let decorator of controllers[controllerType][controller][fn].decorators) {
if (decorator.type === 'custom') {
result.decorators[decorator.name] = true
}
for (let util of decorator.params || []) {
if (util.type && util.type === 'custom') {
result.utils[util.name] = true
}
}
}
for (let main of controllers[controllerType][controller][fn].main) {
if (main.type === 'custom') {
if (!result.services[main.service]) {
result.services[main.service] = {}
}
result.services[main.service][main.function] = main.params
}
}
}
}
}
return result
}
const run = async (gulp, nunjucksRender, rename, nunjucksRenderConfig) => {
//编译自定义文件
const { decorators, utils, services } = customFileMap(config.controllers)
for (let decorator in decorators) {
await gulp
.src(`${serverTemplatePath}/decorator.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: decorator
}
})
)
.pipe(rename(`${decorator}.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/decorator/custom'))
}
await gulp
.src(`${serverTemplatePath}/decorator.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
decorators
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/decorator/custom'))
for (let util in utils) {
await gulp
.src(`${serverTemplatePath}/util.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: util
}
})
)
.pipe(rename(`${util}.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/utils/custom'))
}
await gulp
.src(`${serverTemplatePath}/util.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
utils
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/utils/custom'))
for (let service in services) {
await gulp
.src(`${serverTemplatePath}/service.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: service,
fns: services[service]
}
})
)
.pipe(rename(`${service}.service.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/service/custom'))
}
await gulp
.src(`${serverTemplatePath}/service.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
services
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/service/custom'))
//编译controller.common
for (let commonController in config.controllers.common) {
const controller = config.controllers.common[commonController]
await gulp
.src(`${serverTemplatePath}/controller.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: commonController,
model: controller,
...controllerImport(controller),
commmonDecorators: getDecorators(controller, 'common'),
customDecorators: getDecorators(controller, 'custom'),
commonPreChecks: getPreChecks(controller, 'common'),
customPreChecks: getPreChecks(controller, 'custom'),
commonPreUpdates: getPreUpdates(controller, 'common'),
customPreUpdates: getPreUpdates(controller, 'custom')
}
})
)
.pipe(rename(`${commonController}.controller.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/controller/common'))
}
//编译controller.custom
for (let customController in config.controllers.custom) {
const controller = config.controllers.custom[customController]
await gulp
.src(`${serverTemplatePath}/controller.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: customController,
model: controller,
...controllerImport(controller),
commmonDecorators: getDecorators(controller, 'common'),
customDecorators: getDecorators(controller, 'custom'),
commonPreChecks: getPreChecks(controller, 'common'),
customPreChecks: getPreChecks(controller, 'custom'),
commonPreUpdates: getPreUpdates(controller, 'common'),
customPreUpdates: getPreUpdates(controller, 'custom')
}
})
)
.pipe(rename(`${customController}.controller.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/controller/custom'))
}
//接口导出
await gulp
.src(`${serverTemplatePath}/controller.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
controllers: config.controllers
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath))
//编译constants.njk
await gulp
.src(`${serverTemplatePath}/constants.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
appId: config.appId,
sellerId: config.sellerId
}
})
)
.pipe(rename(`constants.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath))
}
module.exports = {
run
}
/** @format */
const gulp = require('gulp')
const rename = require('gulp-rename')
const nunjucksRender = require('gulp-nunjucks-render')
const prettier = require('gulp-prettier')
const codeGenerate = require('./generate')
var jsScript = 'node'
if (process.env.npm_config_argv !== undefined && process.env.npm_config_argv.indexOf('debug') > 0) {
jsScript = 'node debug'
}
const ServerFullPath = '../src'
const prettierConfig = {
printWidth: 120,
semi: false,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
arrowParens: 'avoid',
insertPragma: true,
tabWidth: 2,
useTabs: false
}
const nunjucksRenderConfig = {
path: 'templates',
ext: '.ts',
manageEnv: environment => {
environment.addFilter('firstToCapital', str => {
return str.charAt(0).toUpperCase() + str.slice(1)
})
environment.addFilter('groupByTypeAndService', value => {
const res = {}
for (let main of value) {
if (!res[main.type]) {
res[main.type] = {}
}
res[main.type][main.service] = true
}
return res
})
},
ServerFullPath
}
gulp.task('build', function () {
require('events').EventEmitter.defaultMaxListeners = 0
return codeGenerate.run(gulp, nunjucksRender, rename, nunjucksRenderConfig)
})
console.log(nunjucksRenderConfig.ServerFullPath + '/**/*.ts')
gulp.task('format', () => {
return gulp
.src(nunjucksRenderConfig.ServerFullPath + '/**/*.ts')
.pipe(prettier(prettierConfig))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/'))
})
gulp.task('code', gulp.series('build', 'format'))
{
"name": "nunjucks-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"complile": "gulp code"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@typescript-eslint/parser": "^4.8.1",
"eslint": "^7.13.0",
"gulp": "^4.0.2",
"gulp-nunjucks-render": "^2.2.3",
"gulp-prettier": "^3.0.0",
"gulp-rename": "^2.0.0",
"typescript": "^4.0.5"
},
"dependencies": {
"fs-extra": "^9.0.1"
}
}
/** @format */
export * from './errorCode'
// tb 接口返回部分错误
export const TBERROR = {
USER_PERMISSION_EXCEED_MAX_RIGHT_COUNT_IN_DAY: '今日领取达到上限,明日再来领取哦',
COUPON_INVALID_OR_DELETED: '权益无效或者被删除,请联系商家',
APPLY_OWNSELF_COUPON: '不能领取自己家店铺权益',
APPLY_SINGLE_COUPON_COUNT_EXCEED_LIMIT: '请至卡券包删除无用权益再领取',
NO_RIGHT_QUANTITY: '权益库存不足,请联系商家',
ERRORA_3_567: '领取失败,为风险用户',
'Invalid session': '订购应用已过期,请联系商家处理'
}
// 领取奖品状态
export const DRAW_STATUS = {
// 待领取
WAITAWARD: 1,
// 处理中
PROCESSING: 2,
// 领取成功
SUCCESS: 3,
// 领取失败
FAIL: 4,
// 已过期
EXPIRED: 5,
// 重新领取
RETRY: 6
}
// 订单状态
export const TAOBAO_SUCCESS_ORDER_STATUS: string[] = [
'WAIT_SELLER_SEND_GOODS',
'SELLER_CONSIGNED_PART',
'WAIT_BUYER_CONFIRM_GOODS',
'TRADE_BUYER_SIGNED',
'TRADE_FINISHED',
'PAID_FORBID_CONSIGN'
]
export const ACTIVITY_OPEN_PRIZE_STATUS = {
//开奖状态
AWAIT: 1,
OPENING: 2,
SUCCESS: 3,
FAIL: 4
}
// 活动状态
export const enum ACTIVITY_STATUS {
NORMAL = 1,
DELETE = 2
}
// 奖品状态
export const enum DELETE_STATUS {
NORMAL = 1,
DELETE = 2
}
//任务频率类型常量
export const TASK_RATE_TYPE = {
FOREVER: 1,
EVERYDAY: 2,
NOLIMIT: 3
}
//任务状态
export const TASK_STATUS = {
WAIT_DO: 1, // 未完成
WAIT_RECEIVE: 2, // 待领取
DONE: 3 // 已完成
}
// 奖品类型
export const PRIZE_TYPE = {
ENAME: 1,
CREDITS: 2,
OBJECT: 3,
THANKS: 5,
CARD: 6
}
// 奖品分类
export const PRIZE_DATA_TYPE = {
RANKING: 1, // 排行榜
PROBABILITY: 2, // 概率
CARD: 6, // 卡牌
CARD_TYPE_AWARD: 7,
JOIN_TIMES: 8
}
// 奖品是否限制库存
export enum SWICH_TOCK {
LIMIT = 1,
NO_LIMIT = 2
}
//物流状态
export const SHIP_STATUS = {
NO_ADDRESS: 1,
NO_SHIP: 2,
HAS_SHIP: 3
}
// 记录数据
export enum STAT_TYPE {
INITE_SUCCESS
}
// 每次参与消耗次数
export const JOIN_NEED_TIMES = 1
export const appId = '{{appId}}'
// 商铺id 拼接vip链接用
export const sellerId = '{{sellerId}}'
// C端的APP NAME
export const C_APP_NAME: string = `promotioncenter-${appId}`
/** @format */
{%- for type, type_item in controllers -%}
{%- for controller, controller_item in type_item %}
import {{type | capitalize}}{{controller | capitalize}}Controller from './controller/{{type}}/{{controller}}.controller'
const {{type | capitalize}}{{controller | capitalize}}ControllerInstance = new {{type | capitalize}}{{controller | capitalize}}Controller()
{%- endfor -%}
{%- endfor %}
export default {
{%- for type, type_item in controllers -%}
{%- for controller, controller_item in type_item -%}
{%- for function, fucntion_item in controller_item %}
{{function}}: {{type | capitalize}}{{controller | capitalize}}ControllerInstance.{{function}}
{%-if loop.last-%}{%else%},{%-endif-%}
{%- endfor -%}
{%-if loop.last-%}{%else%},{%-endif-%}
{%- endfor -%}
{%-if loop.last-%}{%else%},{%-endif-%}
{%- endfor %}
}
/** @format */
{% import "macro.njk" as macro -%}
import { {{ commmonDecorators }} } from '../../decorator/common'
{%if commonPreChecks and commonPreChecks.length -%}
import { {{commonPreChecks}} } from '../../utils/common/check'
{% endif -%}
{%if commonPreUpdates and commonPreUpdates.length -%}
import { {{commonPreUpdates}} } from '../../utils/common/update'
{% endif -%}
{%if customDecorators.length -%}
import { {{customDecorators}} } from '../../decorator/custom'
{% endif -%}
import customUtil from '../../utils/custom'
import { resultsModel } from '../../sdk'
{{macro.genControllerService(services)}}
{# import commonService from '../../service/common'
import customService from '../../service/custom' #}
export default class {{name | capitalize}}Controller {
{%- for fn, item in model %}
/**
* {{item.desc}}
*/
{{-macro.genDecorator(model[fn].decorators)}}
@services([{{-macro.genServicesDecorator(model[fn].main)}}])
{{-macro.genPreDecorator(model[fn].decorators)}}
async {{fn}}(
context: IContext<IParams>,
{ activityInfo, userInfo{{-macro.genRegisteInfosParams(model[fn].decorators)}} }: IControllerInfos,
{{-macro.genServicesParams(model[fn].main)-}},
{{-macro.genPreCheckDataParams(model[fn].decorators)-}}
) {
{{-macro.genMain(model[fn].main)}}
{{-macro.genReturn(model[fn].main)}}
}
{%- endfor %}
}
/** @format */
{%for decorator, decorator_item in decorators-%}
import {{decorator}} from './{{decorator}}'
{%-endfor%}
const custom = {
{%-for decorator, decorator_item in decorators%}
{{decorator}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
export default custom
export {
{%-for decorator, decorator_item in decorators%}
{{decorator}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
/** @format */
import { resultsModel } from '../../sdk'
import { CODE_TYPES } from '../../constants'
export default function {{name}}(params) {
return function (target: Object, name: string, descriptor: PropertyDescriptor) {
const method = descriptor.value
descriptor.value = function (...args: any[]) {
const [context, otherArgs = {}] = args
return method.apply(target, [context, { ...otherArgs }])
}
}
}
{# 生成控制器引用的服务 #}
{% macro genControllerService(services)%}
{%- for type, type_item in services -%}
import { {%for service, service_item in type_item %}{{type|capitalize}}{{service|capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}{% endfor %} } from '../../service/{{type}}'
{% endfor%}
{% endmacro %}
{# 生成装饰器 #}
{% macro genDecorator(decorators) %}
{%- for decorator in decorators %}
{%- if decorator.name != 'preCheck' and decorator.name != 'preUpdate' %}
@{{ decorator.name }}
{%- if decorator.name == 'noCatch' or decorator.name == 'noCheckUser' -%}
{%- else -%}
([{%- for param in decorator.params -%}'{{ param }}'{%- if loop.last %}{% else %}, {% endif %}{%- endfor -%}])
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{% endmacro %}
{# 生成装饰器 #}
{% macro genPreDecorator(decorators) %}
{%- for decorator in decorators %}
{%- if decorator.name == 'preCheck' or decorator.name == 'preUpdate' %}
@{{ decorator.name }}([{%- for param in decorator.params -%}{{param.name}}{%- if param.params %}({%- for utilParam in param.params -%}{{utilParam}}{%- if loop.last %}{% else %}, {% endif %}{%- endfor -%}){% endif %}{%- if loop.last %}{% else %}, {% endif %}{%- endfor -%}])
{%- endif -%}
{%- endfor -%}
{% endmacro %}
{# 生成services装饰器 #}
{% macro genServicesDecorator(mains) %}
{%- for type, type_item in mains | groupByTypeAndService -%}
{%- for service, service_item in type_item -%}
{{type|capitalize}}{{service|capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- endmacro %}
{# 生成services参数 #}
{% macro genServicesParams(mains) %}
[
{%- for type, type_item in mains | groupByTypeAndService -%}
{%- for service, service_item in type_item -%}
{{ type }}{{service | capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
]: [
{%- for type, type_item in mains | groupByTypeAndService -%}
{%- for service, service_item in type_item -%}
{{type|capitalize}}{{service|capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
]
{%- endmacro %}
{# 生成注入参数 #}
{% macro genRegisteInfosParams(decorators) %}
{%- for decorator in decorators -%}
{% if decorator.type == 'common' and decorator.name == 'registeInfos' %}
{%- for param in decorator.params -%}
{%- if loop.first %}, {% else %}{% endif %}{{ param }}{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{% endif %}
{%- endfor -%}
{%- endmacro %}
{# 生成common preCheck返回数据 #}
{% macro genPreCheckDataParams(decorators) %}
{% set preChecks = {'checkInviteId':'inviteUserInfo','checkValidObjectPrize':'awardInfo','checkValidEnamePrize':'awardInfo', 'checkJoinId': 'joinInfo'} -%}
{%- set preCheckData = [] -%}
{% for decorator in decorators -%}
{%- if decorator.type == 'common' and decorator.name== 'preCheck' -%}
{%- for param in decorator.params -%}
{%- for key, data in preChecks -%}
{%- if key === param.name%} {% set preCheckData = preCheckData.concat(data)%} {% endif %}
{%- endfor -%}
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{%- if preCheckData.length -%}
{ {{preCheckData | join(',')}} }: IPreCheckData
{% endif %}
{%- endmacro %}
{# 生成函数体 #}
{% macro genMain(mains) %}
{%- for main in mains %}
const {{main.type}}{{main.service|capitalize}}{{main.function|firstToCapital}}Result{{loop.index}} = {% if main.async %}{% else %}await {% endif %}{{main.type}}{{main.service | capitalize}}Service.{{main.function}}(
{%- for param in main.params -%}
{% if param.type == 'var' %}{{param.value}}{% else %}'{{param.value}}'{% endif %}{% if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
)
{%- endfor -%}
{%- endmacro %}
{# 生成return结果 #}
{% macro genReturn(mains) %}
return resultsModel.success({
{%- for main in mains -%}
{% if main.return %}
...{{main.type}}{{main.service|capitalize}}{{main.function|firstToCapital}}Result{{loop.index}}{% if loop.last %}{% else %},{% endif %}
{%- endif -%}
{%- endfor %}
})
{%- endmacro%}
\ No newline at end of file
/** @format */
{%- for service, service_item in services %}
import Custom{{ service | capitalize }}Service from './{{ service }}.service'
{%- endfor %}
const custom = {
{%- for service, service_item in services %}
Custom{{ service | capitalize }}Service{% if loop.last %}{%else%},{% endif %}
{%- endfor %}
}
export default custom
export {
{%- for service, service_item in services %}
Custom{{ service | capitalize }}Service{% if loop.last %}{%else%},{% endif %}
{%- endfor %}
}
/**
* 基本信息
*
* @format
*/
import { BaseDao, TBAPIS } from '../../sdk'
import { ACTIVITY_STATUS } from '../../constants'
import { getToday } from '../../utils'
export default class {{ name | capitalize }}Service {
context: IContext<IParams>
joindao: IBaseDao
constructor(context: IContext<IParams>) {
this.context = context
}
{% for fn, fn_item in fns -%}
async {{ fn }}({%- for param in fn_item -%}param{{loop.index}}{% if loop.last %}{% else %},{% endif %}{%- endfor -%}) {
const { openId, data } = this.context
return {}
}
{%- endfor %}
}
/** @format */
{%for util, util_item in utils-%}
import {{util}} from './{{util}}'
{%-endfor%}
const custom = {
{%-for util, util_item in utils%}
{{util}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
export default custom
export {
{%-for util, util_item in utils%}
{{util}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
/** @format */
import { resultsModel } from '../../sdk'
import { CODE_TYPES } from '../../errorCode'
export default async function {{name}}(context: IContext<IParams>, { activityInfo }: IControllerInfos) {
// TO DO
}
/** @format */
// 获取去重后的装饰器
function getDecorators(controller, decoratorType) {
let decorators = decoratorType === 'common' ? [{ type: 'common', name: 'services' }] : []
decorators = [...decorators, ...Object.values(controller).map(v => v.decorators)].flat()
return [...new Set(decorators.filter(v => v.type === (decoratorType || 'common')).map(v => v.name))]
}
function getPreChecks(controller, checkType) {
checkType = checkType || 'common'
let decorators = []
decorators = [...decorators, ...Object.values(controller).map(v => v.decorators)].flat()
const preChecks = [...decorators.filter(v => v.type === 'common' && v.name === 'preCheck').map(v => v.params)].flat()
return [...new Set(preChecks.filter(v => v.type === checkType && v.behave === 'check').map(v => v.name))]
}
function getPreUpdates(controller, updateType) {
updateType = updateType || 'common'
let decorators = []
decorators = [...decorators, ...Object.values(controller).map(v => v.decorators)].flat()
const preUpdates = [
...decorators.filter(v => v.type === 'common' && v.name === 'preUpdate').map(v => v.params)
].flat()
return [...new Set(preUpdates.filter(v => v.type === updateType && v.behave === 'update').map(v => v.name))]
}
module.exports = {
getDecorators,
getPreChecks,
getPreUpdates
}
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment