conf.js
module.exports = { db: { url: 'mongodb://127.0.0.1:27017/local', options: { useNewUrlParser: true, } } }
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'); })
./model/user.js
module.exports = { schema: { mobile: { type: String, required: true, }, realName: { type: String, required: true, }, } }
./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數據庫中的數據模型,接下來是將數據模型和接口對應mongodb
./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();
./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數據庫