注册接口添加,swagger文档完善

This commit is contained in:
zhangyiming 2020-11-30 20:00:45 +08:00
parent ef15fa71ba
commit 7eee57e11f
10 changed files with 451 additions and 230 deletions

View File

@ -1,5 +1,8 @@
# Port
PORT=3000
# JWT_SECRET
JWT_SECRET = '708DD1DC5BC5A169'
# Debug
LOG_LEVEL='debug'

File diff suppressed because it is too large Load Diff

View File

@ -22,7 +22,10 @@
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-swagger-generator": "^1.1.17",
"jsonwebtoken": "^8.5.1",
"md5-node": "^1.0.1",
"mysql2": "^2.2.5",
"svg-captcha": "^1.4.0",
"winston": "^3.3.3"
}
}

View File

@ -1,31 +1,31 @@
import * as express from "express";
import * as bodyParser from "body-parser";
import * as express from "express"
import * as bodyParser from "body-parser"
class App {
public app: express.Application;
public app: express.Application
constructor() {
this.app = express();
this.config();
this.app = express()
this.config()
}
private config(): void {
// 支持json编码的主体
this.app.use(bodyParser.json());
this.app.use(bodyParser.json())
// 支持编码的主体
this.app.use(bodyParser.urlencoded({
extended: true,
}));
}))
// 设置静态访问目录(Swagger)
this.app.use(express.static('public'));
this.app.use(express.static('public'))
// 设置跨域访问
this.app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
res.header('X-Powered-By', ' 3.2.1');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'content-type')
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
res.header('X-Powered-By', ' 3.2.1')
res.header('Content-Type', 'application/json;charset=utf-8')
next()
})
}
}
export default new App().app;
export default new App().app

View File

@ -1,11 +1,11 @@
import * as dotenv from "dotenv";
import * as dotenv from "dotenv"
process.env.NODE_ENV = process.env.NODE_ENV || "development";
process.env.NODE_ENV = process.env.NODE_ENV || "development"
const envFound = dotenv.config();
const envFound = dotenv.config()
if (envFound.error) {
throw new Error("⚠️ Couldn't find .env file ⚠️");
throw new Error("⚠️ Couldn't find .env file ⚠️")
}
export default {
@ -52,10 +52,10 @@ export default {
host: 'localhost',
charset: 'utf8_general_ci',
user: 'root',
password: '123456789'
password: 'admin'
},
mongodb:{},
sqlite:{},
mongodb: {},
sqlite: {},
api: {
prefix: '/api',
},
@ -63,4 +63,4 @@ export default {
apiKey: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN
}
};
}

View File

@ -1,9 +1,9 @@
import config from "../config";
import * as winston from "winston";
import config from "../config"
import * as winston from "winston"
const transports = [];
if(process.env.NODE_ENV !== 'development') {
const transports = []
if (process.env.NODE_ENV !== 'development') {
transports.push(
new winston.transports.Console()
)
@ -30,6 +30,6 @@ const LoggerInstance = winston.createLogger({
winston.format.json()
),
transports
});
})
export default LoggerInstance;
export default LoggerInstance

View File

@ -1,5 +1,5 @@
// 创建用户表
const user = 'CREATE TABLE if not EXISTS users(id int PRIMARY key auto_increment,account varchar(32),psw varchar(32))'
const user = 'CREATE TABLE if not EXISTS users(id int PRIMARY key auto_increment,username varchar(32),password varchar(32))'
export {
user

View File

@ -1,86 +1,182 @@
import md5 from 'md5-node'
import jwt from "jsonwebtoken"
import jwtSecret from "../../config"
import Logger from "../../loaders/logger"
import { Request, Response } from "express"
import { createMathExpr } from "svg-captcha"
import { connection } from '../../utils/initMysql'
export interface dataModel {
length: number
}
// 保存验证码
let verify: number | string
/**
*
* @route GET /login/
* @summary
* @group login -
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
* @typedef Point
* @property {string} username.required -
* @property {string} password.required -
* @property {string} verify.required -
*/
const login =async (req: Request, res: Response) => {
res.json({code:1 , msg: "成功"})
/**
* @typedef Error
* @property {string} code.required
*/
/**
* @typedef Response
* @property {[integer]} code
*/
/**
*
* @route POST /login
* @param {Point.model} point.body.required - the new point
* @produces application/json application/xml
* @consumes application/json application/xml
* @returns {Response.model} 200
* @returns {Array.<Point>} Point
* @headers {integer} 200.X-Rate-Limit
* @headers {string} 200.X-Expires-After
* @security JWT
*/
const login = async (req: Request, res: Response) => {
console.log(req.body)
// if (verify !== req.query.verify) return res.json({
// code: -1,
// info: "请输入正确的验证码"
// })
//生成jwt(token令牌) {expiresIn:3600}为token的过期时间这里设置的是1小时
// const accessToken = jwt.sign({
// accountId: account.id
// }, settings.accessTokenSecret, { expiresIn: 3600 })
// const idToken = jwt.sign({
// sub: account.id,
// preferred_username: account.username
// }, "some secret that doesn't matter")
// //返回token
// response.status(200).json({
// access_token: accessToken,
// id_token: idToken
// })
// accessToken
}
/**
*
* @route GET /register/
* @route POST /register
* @summary
* @group register -
* @param {string} username.query.required - username
* @param {string} password.query.required - password
* @param {string} verify.query.required - verify
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
*/
const register =async (req: Request, res: Response) => {
res.json({code:1 , msg: "成功"})
const register = async (req: Request, res: Response) => {
if (verify !== req.query.verify) return res.json({
code: -1,
info: "请输入正确的验证码"
})
let sql: string = 'select * from users where username=' + "'" + req.query.username + "'"
connection.query(sql, async (err, data: dataModel) => {
if (data.length > 0) {
await res.json({
code: -1,
info: "账号已被注册"
})
} else {
let sql: string = 'insert into users (username,password) value(' + "'" + req.query.username + "'" + ',' + "'" + req.query.password +
"'" + ')'
connection.query(sql, async function (err) {
if (err) {
Logger.error(err)
} else {
await res.json({
code: 0,
info: "账号注册成功"
})
}
})
}
})
}
/**
*
* @route GET /updateList/
* @route GET /updateList
* @summary
* @group updateList -
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
*/
const updateList =async (req: Request, res: Response) => {
res.json({code:1 , msg: "成功"})
const updateList = async (req: Request, res: Response) => {
res.json({ code: 1, msg: "成功" })
}
/**
*
* @route GET /deleteList/
* @route GET /deleteList
* @summary
* @group deleteList -
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
*/
const deleteList =async (req: Request, res: Response) => {
res.json({code:1 , msg: "成功"})
const deleteList = async (req: Request, res: Response) => {
res.json({ code: 1, msg: "成功" })
}
/**
*
* @route GET /searchPage/
* @summary
* @group searchPage -
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
*/
/**
*
* @route GET /searchPage
* @summary
* @group searchPage -
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
*/
const searchPage =async (req: Request, res: Response) => {
res.json({code:1 , msg: "成功"})
const searchPage = async (req: Request, res: Response) => {
res.json({ code: 1, msg: "成功" })
}
/**
*
* @route GET /searchVague/
* @route GET /searchVague
* @summary
* @group searchVague -
* @returns {object} 200
* @security JWT
* @returns {Error} default - Unexpected error
*/
const searchVague =async (req: Request, res: Response) => {
res.json({code:1 , msg: "成功"})
const searchVague = async (req: Request, res: Response) => {
res.json({ code: 1, msg: "成功" })
}
/**
*
* @route GET /captcha
* @summary
* @group captcha -
* @returns {object} 200
* @security JWT
*/
const captcha = async (req: Request, res: Response) => {
const create = createMathExpr({
mathMin: 1,
mathMax: 4,
mathOperator: "+"
})
verify = create.text
res.type('svg') // 响应的类型
res.json({ code: 1, msg: create.text, svg: create.data })
}
export {
@ -90,4 +186,5 @@ export {
deleteList,
searchPage,
searchVague,
captcha,
}

View File

@ -1,29 +1,30 @@
import app from "./app";
import * as open from "open";
import config from './config';
import { user } from "./models/mysql";
import Logger from './loaders/logger';
import { queryTable } from "./utils/initMysql";
const expressSwagger = require('express-swagger-generator')(app);
import app from "./app"
import * as open from "open"
import config from './config'
import { user } from "./models/mysql"
import Logger from './loaders/logger'
import { queryTable } from "./utils/initMysql"
const expressSwagger = require('express-swagger-generator')(app)
expressSwagger(config.options)
queryTable(user)
// 引入测试数据
import {
import {
login,
register,
updateList,
deleteList,
searchPage,
searchVague,
captcha,
} from "./router/api/mysql"
app.get('/login', (req, res) => {
app.post('/login', (req, res) => {
login(req, res)
})
app.get('/register', (req, res) => {
app.post('/register', (req, res) => {
register(req, res)
})
@ -43,15 +44,19 @@ app.get('/searchVague', (req, res) => {
searchVague(req, res)
})
app.get('/captcha', (req, res) => {
captcha(req, res)
})
app.listen(config.port, () => {
Logger.info(`
################################################
🛡 Swagger文档地址: http://localhost:${config.port} 🛡️
################################################
`);
`)
}).on('error', err => {
Logger.error(err);
process.exit(1);
});
Logger.error(err)
process.exit(1)
})
open(`http://localhost:${config.port}`); // 自动打开默认浏览器
open(`http://localhost:${config.port}`) // 自动打开默认浏览器

View File

@ -1,14 +1,13 @@
import * as mysql from "mysql2";
import mysqlConfig from "../config";
import Logger from "../loaders/logger";
import * as mysql from "mysql2"
import mysqlConfig from "../config"
import Logger from "../loaders/logger"
//user数据库
const connection = mysql.createConnection(Object.assign({ database: 'user' }, mysqlConfig.mysql))
export const connection = mysql.createConnection(Object.assign({ database: 'user' }, mysqlConfig.mysql))
export function queryTable(s: string):void {
connection.query(s, (err) => {
err ? Logger.error(err) : Logger.info(`${s}表创建成功`)
})
}
export function queryTable(s: string): void {
connection.query(s, (err) => {
err ? Logger.error(err) : Logger.info(`${s}表创建成功`)
})
}