egg-xc-base
Version:
a base framework with egg.js
300 lines (289 loc) • 11.4 kB
JavaScript
/**
* Created by ThinkPad on 2019/12/16.
*/
const config = require('../config/config.default')({name:'apiInit'})
const rds = require('ali-rds');
const path = require('path');
const fs = require('fs');
const mysql = require('mysql')
module.exports = {
doIt : async (info)=>{
const {_table,_module,_ctx} = info
const prefix = _module
const csName = _ctx?_ctx:prefix
const csUrl = _ctx? `/${_ctx}`:''
const group = _ctx? `${_module}_${_ctx}`:_module
const _db = info._db?info._db:'db1'
if(!config || !config.mysql || !config.mysql.clients || !config.mysql.clients[_db] ){
throw new Error("数据库配置文件不存在!-->"+path.resolve('../config/config.default.js') + ".mysql.clients."+[_db])
}
if(!config || !config.static || !config.static.prefix){
throw new Error("项目上下文根配置文件不存在!-->"+path.resolve('../config/config.default.js') + ".static.prefix")
}
const basePrefix = config.static.prefix
console.log("数据库链接:",JSON.stringify(config.mysql.clients[_db],2,2))
const _database = config.mysql.clients[_db].database
let db = rds(config.mysql.clients.db1)
const to = (params)=>{
return mysql.escape(params)
}
const doQueryError =async (_sql)=> {
return await db.query(_sql)
}
const tableInfo = await doQueryError(`
SELECT TABLE_COMMENT FROM information_schema.TABLES
WHERE table_schema=${to(_database)} AND TABLE_NAME = ${to(_table)}
`);
if (tableInfo.length == 0) {
db.end()
throw new Error(`表不存在!-->database=${_database} table=${_table}`);
}
const tableDesc = tableInfo[0].TABLE_COMMENT;
const cols = await doQueryError(`SELECT COLUMN_NAME,IS_NULLABLE,DATA_TYPE,COLUMN_COMMENT,COLUMN_KEY
FROM
information_schema. COLUMNS
WHERE
TABLE_SCHEMA = ${to(_database)}
AND TABLE_NAME = ${to(_table)}
`);
db.end()
let apiParams = '';
let apiParamsCreate = '';
let apiListRes = '* @apiSuccess {array[object]} Error0.content \n';
const validate = {};
let insert = '';
let createP = '';
let insertValues = '';
let duplicate = '';
let updateValues = '';
for (const col of cols) {
apiParams += `\t * @apiParam {${[ 'int', 'integer', 'bigint','tinyint' ].includes(col.DATA_TYPE) ? 'number' : 'string'}} ${col.IS_NULLABLE == 'YES' ? '[' : ''}${col.COLUMN_NAME}${col.IS_NULLABLE == 'YES' ? ']' : ''} ${col.COLUMN_COMMENT}`;
apiParams += '\n';
apiListRes += `\t * @apiSuccess {${[ 'int', 'integer', 'bigint','tinyint' ].includes(col.DATA_TYPE) ? 'number' : 'string'}} Error0.content.${col.COLUMN_NAME} ${col.COLUMN_COMMENT}`;
apiListRes += '\n';
if (col.COLUMN_KEY != 'PRI') {
apiParamsCreate += `\t * @apiParam {${[ 'int', 'integer', 'bigint' ,'tinyint'].includes(col.DATA_TYPE) ? 'number' : 'string'}} ${col.IS_NULLABLE == 'YES' ? '[' : ''}${col.COLUMN_NAME}${col.IS_NULLABLE == 'YES' ? ']' : ''} ${col.COLUMN_COMMENT}`;
apiParamsCreate += '\n';
insert += ',';
insert += col.COLUMN_NAME;
insertValues += ',';
insertValues += `\${this.to(info.${col.COLUMN_NAME})}`;
updateValues += `,${col.COLUMN_NAME}=\${this.to(info.${col.COLUMN_NAME})}`;
if (col.IS_NULLABLE == 'NO') {
validate[col.COLUMN_NAME] = { type: [ 'int', 'integer', 'bigint' ].includes(col.DATA_TYPE) ? 'number' : 'string' };
} else {
createP += `\t\tinfo.${col.COLUMN_NAME} = info.${col.COLUMN_NAME} || null\n`;
}
}
if ([ 'MUL', 'UNI' ].includes(col.COLUMN_KEY)) {
duplicate += `\t\t\tif(error && error.info && error.info.indexOf('Duplicate')>-1 && error.info.indexOf('${col.COLUMN_NAME}')>-1){
throw new this.app.dbError('${col.COLUMN_COMMENT}已存在!');
}\n`;
}
}
apiParams = apiParams.replace(/(^\s*)|(\s*$)/g, '');
apiParamsCreate = apiParamsCreate.replace(/(^\s*)|(\s*$)/g, '');
apiListRes = apiListRes.replace(/(^\s*)|(\s*$)/g, '');
createP = createP.replace(/(^\s*)|(\s*$)/g, '');
updateValues = updateValues.replace(/(^\s*)|(\s*$)/g, '');
duplicate = duplicate.replace(/(^\s*)|(\s*$)/g, '');
insert = insert.substr(1);
updateValues = updateValues.substr(1);
insertValues = insertValues.substr(1);
let controllerInfo =
`'use strict';
const Controller = require('egg-xc-base').BaseController;
class ${csName.charAt(0).toUpperCase() + csName.substr(1)}Controller extends Controller {
/**@apiIgnore
* @api {POST} ${basePrefix + '/v1.0.0/' + prefix +csUrl} 01创建${tableDesc}
* @apiName 01创建${tableDesc}
*
${apiParamsCreate}
*
* @apiGroup ${group}
* @apiVersion 1.0.0
*
* @apiUse Error0
* @apiUse Error1
* */
async create(){
this.validate(${JSON.stringify(validate, 2, 0)})
try{
const result = await this.ctx.service.${csName}.create(this.ctx.request.body)
if(result.affectedRows === 0){
throw new this.app.serverError('添加失败!');
}
this.success(result.insertId)
}catch(error){
${duplicate}
throw(error);
}
}
/**@apiIgnore
* @api {GET} ${basePrefix + '/v1.0.0/' + prefix+csUrl} 02查找${tableDesc}
* @apiName 02查找${tableDesc}
*
*
* @apiGroup ${group}
* @apiVersion 1.0.0
*
* @apiUse Error0
${apiListRes}
* @apiUse Error1
* */
async list(){
this.success(await this.ctx.service.${csName}.list())
}
/**@apiIgnore
* @api {PUT} ${basePrefix + '/v1.0.0/' + prefix+csUrl} 03更新${tableDesc}
* @apiName 03更新${tableDesc}
*
${apiParams}
*
* @apiGroup ${group}
* @apiVersion 1.0.0
*
* @apiUse Error0
* @apiUse Error1
* */
async update(){
this.validate(${JSON.stringify(validate, 2, 0)})
try{
const result = await this.ctx.service.${prefix}.update(this.ctx.request.body)
if(result.affectedRows === 0){
throw new this.app.serverError('更新失败!');
}
this.success([])
}catch(error){
${duplicate}
throw(error);
}
}
/**@apiIgnore
* @api {DELETE} ${basePrefix + '/v1.0.0/' + prefix+csUrl}/:id 04删除${tableDesc}
* @apiName 04删除${tableDesc}
*
* @apiParam {string} id id
*
* @apiGroup ${group}
* @apiVersion 1.0.0
*
* @apiUse Error0
* @apiUse Error1
* */
async del(){
this.validate(
{
id : {type:"string"}
},this.ctx.params
)
await this.ctx.service.${prefix}.del(this.ctx.params.id)
this.success([])
}
}
module.exports = ${csName.charAt(0).toUpperCase() + csName.substr(1)}Controller; `;
controllerInfo = controllerInfo.replace(/@apiIgnore/g, '');
const serviceInfo =
`'use strict';
const Service = require('egg-xc-base').DbService;
class ${csName.charAt(0).toUpperCase() + csName.substr(1)}Service extends Service {
/**
* @apiIgnore
* 创建${tableDesc}
* @returns {Promise.<*>}
*/
async create(info){
${createP}
return await this.doQueryError(
\`insert into ${_table}(${insert})
values(${insertValues})\`
)
}
/**
* @apiIgnore
* 查询${tableDesc}
* @returns {Promise.<*>}
*/
async list(){
return await this.doQuery(
\`select * from ${_table}\`
)
}
/**
* @apiIgnore
* 更新${tableDesc}
* @returns {Promise.<*>}
*/
async update(info){
${createP}
return await this.doQueryError(
\`update ${_table} set ${updateValues} where id=\${this.to(info.id)}\`
)
}
/**
* @apiIgnore
* 删除${tableDesc}
* @returns {Promise.<*>}
*/
async del(id){
return await this.doQueryError(
\`delete from ${_table} where id=\${this.to(id)}\`
)
}
}
module.exports = ${csName.charAt(0).toUpperCase() + csName.substr(1)}Service;`;
let router = fs.readFileSync(path.join(__dirname,`../api/${_module}/router.js`)).toString();
router = router.replace(/(^\s*)|(\s*$)/g, '');
router = router.substr(0, router.lastIndexOf('}'));
router =
`${router}
//创建${tableDesc}
router.post(config.static.prefix + '${ '/v1.0.0/' + prefix + csUrl}', controller.${csName}.create)
//查找${tableDesc}
router.get(config.static.prefix + '${ '/v1.0.0/' + prefix + csUrl}', controller.${csName}.list)
//更新${tableDesc}
router.put(config.static.prefix + '${ '/v1.0.0/' + prefix + csUrl}', controller.${csName}.update)
//删除${tableDesc}
router.delete(config.static.prefix + '${ '/v1.0.0/' + prefix + csUrl + '/:id'}', controller.${csName}.del)
};`;
fs.writeFileSync(path.join(__dirname,`../api/${_module}/router.js`), router);
fs.writeFileSync(path.join(__dirname,`../api/${_module}/controller/${csName}.js`), controllerInfo);
fs.writeFileSync(path.join(__dirname,`../api/${_module}/service/${csName}.js`), serviceInfo);
return {
name:tableDesc,
db:_database,
table:_table,
api_num: 4,
apis: [
{
id : "01",
fun : "create",
method : "POST",
url : `${'/v1.0.0/' + prefix+ csUrl}`,
name : "创建"+tableDesc
},
{
id : "02",
fun : "list",
method : "GET",
url : `${'/v1.0.0/' + prefix+ csUrl}`,
name : "查找"+tableDesc
},
{
id : "03",
fun : "update",
method : "PUT",
url : `${'/v1.0.0/' + prefix+ csUrl}`,
name : "更新"+tableDesc
},
{
id : "04",
fun : "del",
method : "DELETE",
url : `${'/v1.0.0/' + prefix+ csUrl}/:id`,
name : "删除"+tableDesc
},
]
}
}
}