1.配置
conf.js
module.exports = {
db: {
url: 'mongodb://127.0.0.1:27017/local',
options: {
useNewUrlParser: true,
}
}
}
2.入口
index.js
const Koa = require('koa');
const app = new Koa();
const config = require('./conf')
const {loadModel} = require('./framework/loader')
// 加载model的配置对应字段
loadModel(config)(app)
// 引入动态配置的api
const rest = require('./framework/router');
// 自动将传入的body字符串转换对象值,cxt.request.body
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
app.use(rest);
const port = 3000;
app.listen(port, () => {
console.log('link 3000');
})
3.定义Schema
./model/user.js
module.exports = {
schema: {
mobile: {
type: String,
required: true,
},
realName: {
type: String,
required: true,
},
}
}
4.加载定义的Schema文件,并读取配置到mongo
./framework/loader.js
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');
function load (dir, cb) {
// 获取绝对路径
const url = path.resolve(__dirname, dir);
const files = fs.readdirSync(url);
files.forEach(filename => {
filename = filename.replace('.js', '');
const file = require(url + '/' + filename);
cb(filename, file);
})
}
const loadModel = (config) => {
return (app) => {
mongoose.connect(config.db.url, config.db.options);
const conn = mongoose.connection;
conn.on('error', () => {
console.error('连接失败')
})
app.$model = {
}
load('../model', (filename, {schema}) => {
console.log('load model '+ filename, schema)
app.$model[filename] = mongoose.model(filename, schema)
})
}
}
module.exports = {
loadModel
}
以上步骤,即可定义在mongo数据库中的数据模型,接下来是将数据模型和接口对应
5.定义接口名称
./framework/router.js
const router = require('koa-router')();
const {
init, get, create, update, del,
} = require('./api');
router.get('/api/:listname', init, get);
router.post('/api/:listname', init, create);
router.put('/api/:listname/:id', init, update);
router.delete('/api/:listname/:id', init, del);
module.exports = router.routes();
6.接口的具体处理
./framework/api.js
module.exports = {
async init (ctx, next) {
console.log('init', ctx.params);
const model = ctx.app.$model[ctx.params.listname];
if (model) {
ctx.listname = model;
await next();
} else {
ctx.body = 'no this model'
}
},
async get (ctx) {
ctx.body = await ctx.listname.find({})
},
async create (ctx) {
const req = await ctx.listname.create(ctx.request.body)
console.log('req', req);
console.log('ctx', ctx.listname);
ctx.body = req;
},
async update (ctx) {
const res = await ctx.listname.updateOne({
_id: ctx.params.id
}, ctx.request.body);
ctx.body = res;
console.log('res', res);
},
async del (ctx) {
const res = await ctx.listname.deleteOne({
_id: ctx.params.id
})
ctx.body = res;
},
async page (ctx) {
console.log('page...', ctx.params.page);
ctx.body = await ctx.listname.find({})
},
}
至此,用postman去访问接口即可看到对应效果
http://localhost:3000/api/user