database/mysql.js
const mysql = require('mysql')
const config = require('../../config')
const {database} = config
const pool = mysql.createPool({
host: database.HOST,
user: database.USERNAME,
password: database.PASSWORD,
database: database.DATABASE
})
let query = (sql, values) => {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if(err) reject(err)
connection.query(sql, values, (err, rows) => {
if(err) reject(err)
resolve(rows)
})
connection.release()
})
})
}
module.exports = query
复制代码
lib/decorator.js
const Router = require('koa-router')
const { resolve } = require('path')
const _ = require('lodash')
const glob = require('glob')
const prefixSymbol = Symbol('prefix')
const routerMap = new Map()
const isArray = c => _.isArray(c) ? c : [c]
export class Route{
constructor(app, apiPath){
this.app = app
this.apiPath = apiPath
this.router = new Router()
}
init(){
const routes = glob.sync(resolve(this.apiPath, '**/*.js'))
routes.forEach((n,i,arr) => (require(n)))
// console.log(routes);
// console.log(routes.forEach(require))
for(let [conf, controller] of routerMap){
//中间件数组 这里的controller指的就是
const controllers = isArray(controller)
//路由前缀
const prefixPath = conf.target[prefixSymbol]
if(prefixPath) prefixPath = normalizaPath(prefixPath)
//完整路径 = 前缀 + 后缀
const routerPath = prefixPath + conf.path
//router.get('/movie',...[中间件数组])
this.router[conf.method](routerPath, ...controllers)
}
this.app.use(this.router.routes())
.use(this.router.allowedMethods())
}
}
const normalizaPath = path => path.startsWith('/') ? path : `/${path}`
const router = conf => (target, key, descriptor) => {
conf.path = normalizaPath(conf.path)
routerMap.set({
target: target,
...conf
}, target[key])
// target: 类.prototype target[key] 类里面的某一个方法
}
export const controller = path => target => (
target.prototype[prefixSymbol] = path
)
//获取一条记录
export const get = path => router({
method: 'get',
path
})
//提交一条记录
export const post = path => router({
method: 'post',
path
})
//修改一条记录
export const put = path => router({
method: 'put',
path
})
//删除一条记录
export const del = path => router({
method: 'del',
path
})
//处理所有请求
export const all = path => router({
method: 'all',
path
})
//koa2使用中间件
export const use = path => router({
method: 'use',
path
})
复制代码
middlewares/router.js
const { Route } = require('../lib/decorator')
const { resolve } = require('path')
export const router = app => {
const apiPath = resolve(__dirname, '../routes')
const router = new Route(app, apiPath)
router.init()
}
//只要这个中间件被 koa引用了 ,就等于 初始化了 整个路由 中间层
复制代码
routes/**/*.js
const { controller, get, post, put, del } = require('../lib/decorator')
const { getMovieById } = require('../service/movie')
@controller('/movie')
export class movieController{
@get('/:id')
async getMovies(ctx, next){
console.log('111');
let result = await getMovieById(ctx.params.id)
ctx.type = 'application/json'
ctx.body = result
}
}
// router.get('/movies/:id', async (ctx, next) => {
// let id = ctx.params.id
// let sql = `select * from map_bonus_dict where id = ?`
// let result = await query(sql, id)
// ctx.type = 'application/json'
// ctx.body = result
// })
// module.exports = router
const Router = require('koa-router')
const router = new Router()
const { controller, get, post, put, del } = require('../lib/decorator')
const { getPictures } = require('../service/picture')
@controller('/picture')
export class pictureController {
@get('/')
async getPictures(ctx, next) {
let result = await getPictures()
ctx.type = 'application/json'
ctx.body = result
}
}
// router.get('/movies/all', async (ctx, next) => {
// let sql = 'select * from map_bonus_dict'
// let result = await query(sql)
// ctx.type = 'application/json'
// ctx.body = result
// })
// module.exports = router
复制代码
service/**.*.js
const query = require('../database/mysql')
export const getMovieById = async (id) => {
let sql = `select * from map_bonus_dict where id = ?`
let result = await query(sql, id)
console.log(result);
return result
}
const query = require('../database/mysql')
export const getPictures = async () => {
let sql = `select * from map_bonus_dict`
let result = await query(sql)
console.log(result)
return result
}
复制代码
index.js
const Koa = require('koa')
const { resolve } = require('path')
const R = require('ramda')
const MIDDLEWARES = ['router']
const useMiddleWares = (app) => {
R.map(
R.compose(
R.forEachObjIndexed(
initWith => initWith(app)
),
require,
name => resolve(__dirname, `./middlewares/${name}`)
)
)(MIDDLEWARES)
}
async function start(){
const app = new Koa()
await useMiddleWares(app)
app.listen(4455)
}
start()
复制代码
.babelrc
{
"presets": [
"env",
"stage-0",
"react"
],
"plugins": [
"transform-runtime",
"transform-decorators-legacy",
"transform-class-properties"
],
"comments": false,
"env": {
"test": {
"presets": ["env", "stage-0"],
"plugins": ["istanbul"]
}
}
}
复制代码
config.js
const config = {
//端口号
port: 3000,
//数据库配置
database: {
DATABASE: 'mapsit3',
USERNAME: 'selffabu',
PASSWORD: 'x8t57l8LBB',
PORT: '3306',
HOST: '10.47.142.40'
}
}
module.exports = config
复制代码
package.json
{
"name": "koa2-learning",
"version": "1.0.0",
"description": "",
"main": "index.js",
"keywords": [],
"author": "",
"license": "ISC",
"scripts": {
"start": "node server/index.js",
"build": "rm -rf parcel/dist && parcel build parcel/index.html --no-cache -d parcel/dist --public-url /dist/"
},
"dependencies": {
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"glob": "^7.1.3",
"koa": "^2.6.2",
"koa-bodyparser": "^4.2.1",
"koa-logger": "^3.2.0",
"koa-router": "^7.4.0",
"koa-static": "^5.0.0",
"lodash": "^4.17.11",
"mysql": "^2.16.0",
"ramda": "^0.26.1",
"react": "^16.6.3",
"react-dom": "^16.6.3"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-polyfill": "^6.26.0"
}
}
复制代码
start.js
require('babel-core/register')()
require('babel-polyfill')
require('./server/index.js')
复制代码