travelers
Advanced tools
Comparing version 2.0.0 to 2.0.1
{ | ||
"name": "travelers", | ||
"version": "2.0.0", | ||
"version": "2.0.1", | ||
"description": "I wanna write code like travelers", | ||
@@ -40,6 +40,9 @@ "main": "dist/index.js", | ||
"devDependencies": { | ||
"@typescript-eslint/eslint-plugin": "^2.8.0", | ||
"@typescript-eslint/parser": "^2.8.0", | ||
"eslint": "^6.6.0", | ||
"nodemon": "^1.19.4", | ||
"ts-node": "^8.4.1", | ||
"typescript": "^3.6.4" | ||
"typescript": "^3.7.2" | ||
} | ||
} |
@@ -1,6 +0,4 @@ | ||
import { SwaggerDefalut, apiManage, travelersApis, swagger } from './lib/api' | ||
import * as chalk from 'chalk'; | ||
import { srvsCode, Code } from './lib/code' | ||
import { SwaggerDefalut, apiManage, travelersApis, swagger } from "./lib/api"; | ||
import * as chalk from "chalk"; | ||
import { srvsCode, Code } from "./lib/code"; | ||
import { Request, Response, NextFunction, RequestHandler, Express, ErrorRequestHandler } from "express"; | ||
@@ -12,6 +10,6 @@ import * as express from "express"; | ||
port: number, | ||
} & T | ||
} & T; | ||
type Args = { | ||
interface Args { | ||
apis: { | ||
@@ -25,3 +23,3 @@ [key: string]: travelersApis | ||
type travelersOption = { | ||
interface travelersOption { | ||
config: travelersConfig<any>, | ||
@@ -39,22 +37,22 @@ before?: (app: Express) => void, | ||
export async function travelers(option: travelersOption) { | ||
const app = express() | ||
const app = express(); | ||
let { config, before, args, swaggerDefalut, after, srvs } = option | ||
const { host = '0.0.0.0', port = '3000' } = config | ||
const { apis, controllers } = args | ||
let { config, before, args, swaggerDefalut, after, srvs } = option; | ||
const { host = "0.0.0.0", port = "3000" } = config; | ||
const { apis, controllers } = args; | ||
srvs = srvsCode(srvs) | ||
if (before) before(app) | ||
srvs = srvsCode(srvs); | ||
if (before) before(app); | ||
app.use(express.json()); | ||
app.use(express.urlencoded({ extended: false })); | ||
app.use((req: Request, res: Response, next: NextFunction) => { | ||
req["srvs"] = srvs | ||
next() | ||
}) | ||
await apiManage(app, apis, controllers, swaggerDefalut, config) | ||
if (after) after(app, { swagger }) | ||
req["srvs"] = srvs; | ||
next(); | ||
}); | ||
await apiManage(app, apis, controllers, swaggerDefalut, config); | ||
if (after) after(app, { swagger }); | ||
app.listen(port, `${host}`) | ||
app.listen(port, `${host}`); | ||
console.log(chalk.bold.red(`travelers start host:${host} prot:${port}`)) | ||
console.log(chalk.bold.red(`travelers start host:${host} prot:${port}`)); | ||
@@ -88,3 +86,3 @@ } | ||
export { Request, Response, NextFunction, RequestHandler, Express, ErrorRequestHandler, travelersApis, travelersOption, Code, App } | ||
export { Request, Response, NextFunction, RequestHandler, Express, ErrorRequestHandler, travelersApis, travelersOption, Code, App }; | ||
import * as joi from "joi"; | ||
import * as convert from 'joi-to-json-schema' | ||
import { join } from 'path'; | ||
import * as path from 'path'; | ||
import * as convert from "joi-to-json-schema"; | ||
import { join } from "path"; | ||
import * as path from "path"; | ||
import { Request, Response, Express, NextFunction } from "../index"; | ||
import * as chalk from 'chalk'; | ||
import * as chalk from "chalk"; | ||
import * as verify from "./verify"; | ||
@@ -13,12 +13,12 @@ import * as express from "express"; | ||
const swaggerDefalutSwagger = { | ||
swagger: '2.0', | ||
swagger: "2.0", | ||
info: { | ||
title: '接口文档', | ||
description: 'swagger defalut', | ||
version: '1.0.0' | ||
title: "接口文档", | ||
description: "swagger defalut", | ||
version: "1.0.0" | ||
}, | ||
host: '127.0.0.1:3000', | ||
basePath: '/v1', | ||
schemes: ['http', 'https'], | ||
produces: ['application/json'], | ||
host: "127.0.0.1:3000", | ||
basePath: "/v1", | ||
schemes: ["http", "https"], | ||
produces: ["application/json"], | ||
security: [ | ||
@@ -29,5 +29,5 @@ { | ||
], | ||
} | ||
}; | ||
type Info = { | ||
interface Info { | ||
title: string, | ||
@@ -38,3 +38,3 @@ description: string, | ||
type SwaggerDefalut = { | ||
interface SwaggerDefalut { | ||
swagger?: string, | ||
@@ -79,9 +79,9 @@ info?: Info, | ||
paths: {} | ||
} | ||
}; | ||
type ManageApis = { | ||
interface ManageApis { | ||
[key: string]: travelersApis | ||
} | ||
type ManageControllers = { | ||
interface ManageControllers { | ||
[key: string]: (req: Request, res: Response) => Promise<any> | ||
@@ -96,13 +96,13 @@ } | ||
config) { | ||
const { port = '3000' } = config | ||
const host = '127.0.0.1' | ||
verify.apiVerify(apis, controllers) | ||
const { port = "3000" } = config; | ||
const host = "127.0.0.1"; | ||
verify.apiVerify(apis, controllers); | ||
Object.keys(apis).forEach(apiItem => { | ||
const items: travelersApis = apis[apiItem] | ||
const items: travelersApis = apis[apiItem]; | ||
items.forEach(item => { | ||
const { path, method, summary = '默认', tags = [apiItem], description, operationId, req, res } = item | ||
const { query, body, params } = req | ||
const resBody = res.body | ||
const { path, method, summary = "默认", tags = [apiItem], description, operationId, req, res } = item; | ||
const { query, body, params } = req; | ||
const resBody = res.body; | ||
if (!swagger.paths[path]) { | ||
swagger.paths[path] = {} | ||
swagger.paths[path] = {}; | ||
} | ||
@@ -120,11 +120,11 @@ swagger.paths[path][method] = { | ||
} | ||
} | ||
}; | ||
if (params) { | ||
Object.keys(params).forEach(key => { | ||
const s = convert(params[key]) | ||
s['in'] = "path" | ||
s["name"] = key | ||
swagger.paths[path][method].parameters.push(s) | ||
}) | ||
const s = convert(params[key]); | ||
s["in"] = "path"; | ||
s["name"] = key; | ||
swagger.paths[path][method].parameters.push(s); | ||
}); | ||
} | ||
@@ -134,11 +134,11 @@ | ||
Object.keys(query).forEach(key => { | ||
const s = convert(query[key]) | ||
s['in'] = "query" | ||
s["name"] = key | ||
swagger.paths[path][method].parameters.push(s) | ||
}) | ||
const s = convert(query[key]); | ||
s["in"] = "query"; | ||
s["name"] = key; | ||
swagger.paths[path][method].parameters.push(s); | ||
}); | ||
} | ||
if (body) { | ||
const s = convert(body) | ||
const s = convert(body); | ||
swagger.paths[path][method].parameters.push({ | ||
@@ -148,32 +148,32 @@ in: "body", | ||
schema: s | ||
}) | ||
}); | ||
} | ||
if (resBody) { | ||
const s = convert(resBody) | ||
swagger.paths[path][method].responses['200']["schema"] = s | ||
const s = convert(resBody); | ||
swagger.paths[path][method].responses["200"]["schema"] = s; | ||
} | ||
let koaPath = path.replace(/}/g, '') | ||
koaPath = koaPath.replace(/{/g, ':') | ||
let koaPath = path.replace(/}/g, ""); | ||
koaPath = koaPath.replace(/{/g, ":"); | ||
app[method](koaPath, (req: Request, res: Response, next: NextFunction) => { | ||
(async function () { | ||
// 验证 | ||
const _query = item.req.query || {} | ||
const _body = item.req.body || {} | ||
const _params = item.req.params || {} | ||
let { params, query, body } = req | ||
const _query = item.req.query || {}; | ||
const _body = item.req.body || {}; | ||
const _params = item.req.params || {}; | ||
let { params, query, body } = req; | ||
try { | ||
let queryKeys = Object.keys(_query) | ||
let queryKeys = Object.keys(_query); | ||
for (const queryKey of queryKeys) { | ||
await joi.validate(query[queryKey], _query[queryKey]) | ||
await joi.validate(query[queryKey], _query[queryKey]); | ||
} | ||
let paramsKeys = Object.keys(_params) | ||
let paramsKeys = Object.keys(_params); | ||
for (const paramsKey of paramsKeys) { | ||
await joi.validate(params[paramsKey], _params[paramsKey]) | ||
await joi.validate(params[paramsKey], _params[paramsKey]); | ||
} | ||
if (_body) await joi.validate(body, _body) | ||
if (_body) await joi.validate(body, _body); | ||
} catch (error) { | ||
res.status(400).send(error) | ||
return | ||
res.status(400).send(error); | ||
return; | ||
} | ||
@@ -183,26 +183,26 @@ | ||
if (controllers[item.operationId]) { | ||
const result = await controllers[item.operationId](req,res) | ||
if (result) res.json(result) | ||
const result = await controllers[item.operationId](req, res); | ||
if (result) res.json(result); | ||
} else { | ||
next() | ||
next(); | ||
} | ||
} catch (error) { | ||
res.status(error.code || 500).send(error) | ||
res.status(error.code || 500).send(error); | ||
} | ||
})() | ||
}) | ||
}) | ||
}) | ||
})(); | ||
}); | ||
}); | ||
}); | ||
swaggerDefalut.host = `${host}:${port}` | ||
swagger = { ...swagger, ...swaggerDefalut } | ||
app.use('/document', express.static(path.join(__dirname, '../../swagger'))); | ||
swaggerDefalut.host = `${host}:${port}`; | ||
swagger = { ...swagger, ...swaggerDefalut }; | ||
app.use("/document", express.static(path.join(__dirname, "../../swagger"))); | ||
console.log(chalk.bold.red(`document you can click: http://${host}:${port}/document`)) | ||
app.get('/swagger', (req, res, next) => { | ||
res.send(swagger) | ||
}) | ||
console.log(chalk.bold.red(`document you can click: http://${host}:${port}/document`)); | ||
app.get("/swagger", (req, res, next) => { | ||
res.send(swagger); | ||
}); | ||
} | ||
export { SwaggerDefalut, apiManage, travelersApis, swagger, ManageApis, ManageControllers } | ||
export { SwaggerDefalut, apiManage, travelersApis, swagger, ManageApis, ManageControllers }; |
const Code = { | ||
ok: { | ||
code: 200, | ||
msg: 'success' | ||
msg: "success" | ||
}, | ||
paramsErr: { | ||
code: 400, | ||
msg: 'params err' | ||
msg: "params err" | ||
}, | ||
notAuthorization: { | ||
code: 401, | ||
msg: 'not authorization' | ||
msg: "not authorization" | ||
}, | ||
rejectVisit: { | ||
code: 403, | ||
msg: 'reject visit' | ||
msg: "reject visit" | ||
}, | ||
notfind: { | ||
code: 404, | ||
msg: 'not find' | ||
msg: "not find" | ||
}, | ||
serverErr: { | ||
code: 500, | ||
msg: 'server err' | ||
msg: "server err" | ||
}, | ||
$message: { | ||
code: 400, | ||
msg: '$message' | ||
msg: "$message" | ||
} | ||
} | ||
}; | ||
import { Request, Response, Express, NextFunction } from "../index"; | ||
type CodeType = { [key: string]: { code: number, msg: string } } | ||
interface CodeType { [key: string]: { code: number, msg: string } } | ||
type Result = { | ||
interface Result { | ||
[key: string]: { | ||
@@ -44,36 +44,36 @@ resJson: (res: Response, args?: { [key: string]: string }) => void | ||
} | ||
}; | ||
Object.keys(codeAll).forEach(key => { | ||
if (!key.includes('$')) { | ||
if (!key.includes("$")) { | ||
result[key] = { | ||
resJson: function (res) { | ||
res.status(codeAll[key].code).send(codeAll[key]) | ||
res.status(codeAll[key].code).send(codeAll[key]); | ||
} | ||
} | ||
}; | ||
} else { | ||
result[key] = { | ||
resJson: function (res, args) { | ||
let obj = codeAll[key] | ||
let obj = codeAll[key]; | ||
Object.keys(args).forEach(objKey => { | ||
let replaceObj = `$${objKey}` | ||
obj.msg = obj.msg.replace(replaceObj, args[objKey]) | ||
}) | ||
res.status(codeAll[key].code).send(obj) | ||
let replaceObj = `$${objKey}`; | ||
obj.msg = obj.msg.replace(replaceObj, args[objKey]); | ||
}); | ||
res.status(codeAll[key].code).send(obj); | ||
} | ||
} | ||
}; | ||
} | ||
}) | ||
return result | ||
}); | ||
return result; | ||
} | ||
function srvsCode(srvs) { | ||
let { code = {} } = srvs | ||
let { code = {} } = srvs; | ||
const codeAll = { | ||
...code, | ||
...Code | ||
} | ||
srvs.codes = HttpCode(codeAll) | ||
return srvs | ||
}; | ||
srvs.codes = HttpCode(codeAll); | ||
return srvs; | ||
} | ||
export { srvsCode, Code } | ||
export { srvsCode, Code }; |
import { ManageApis, ManageControllers, travelersApis } from './api' | ||
import { ManageApis, ManageControllers, travelersApis } from "./api"; | ||
export function apiVerify(apis: ManageApis, controllers: ManageControllers) { | ||
let verifyPath = {} | ||
let verifyOperationId = {} | ||
let verifyPath = {}; | ||
let verifyOperationId = {}; | ||
Object.keys(apis).forEach(apiItem => { | ||
const items: travelersApis = apis[apiItem] | ||
const items: travelersApis = apis[apiItem]; | ||
items.forEach(item => { | ||
const { path, method, operationId } = item | ||
const { path, method, operationId } = item; | ||
if (!verifyPath[path]) { | ||
verifyPath[path] = {} | ||
verifyPath[path] = {}; | ||
} | ||
if (!verifyPath[path][method]) { | ||
verifyPath[path][method] = operationId | ||
verifyPath[path][method] = operationId; | ||
} else { | ||
throw `apis path and method: ${path},${method} already exist` | ||
throw `apis path and method: ${path},${method} already exist`; | ||
} | ||
}) | ||
}) | ||
}); | ||
}); | ||
Object.keys(controllers).forEach(data => { | ||
if (!verifyOperationId[data]) { | ||
verifyOperationId[data] = controllers[data] | ||
verifyOperationId[data] = controllers[data]; | ||
} else { | ||
throw `controllers operationId:${data} already exist` | ||
throw `controllers operationId:${data} already exist`; | ||
} | ||
}) | ||
}); | ||
} |
1472211
29
6364
6