代码结构

代码
const Koa = require('koa')
const app = new Koa()
const config = require('./conf')
const { loadModel } = require('./framework/loader')
loadModel(config)(app)
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
app.use(require('koa-static')(__dirname + '/'))
const restful = require('./framework/router')
app.use(restful)
const port = 3000
app.listen(port, () => {
console.log(`app started at port ${port}`)
})
module.exports = {
schema: {
mobile: { type: String, required: false },
realName: { type: String, required: false },
}
}
module.exports = {
db: {
url:"mongodb://xxxx:xxx@81.71.143.209:xxxx/test?authSource=admin",
options: { useNewUrlParser: true }
}
}
module.exports = {
async init(ctx, next) {
console.log(ctx.params)
const model = ctx.app.$model[ctx.params.modelname]
if (model) {
ctx._model = model
await next()
} else {
ctx.body = 'no this model'
}
},
async list(ctx) {
ctx.body = await ctx._model.find({})
},
async get(ctx) {
ctx.body = await ctx._model.findOne({ _id: ctx.params.id })
},
async create(ctx) {
const res = await ctx._model.create(ctx.request.body)
ctx.body = res
},
async update(ctx) {
const res = await ctx._model.updateOne({ _id: ctx.params.id }, ctx.request.body)
ctx.body = res
},
async del(ctx) {
const res = await ctx._model.deleteOne({ _id: ctx.params.id })
ctx.body = res
},
async page(ctx) {
console.log('page...', ctx.params.page)
ctx.body = await ctx.list.find({})
},
}
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 => 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
}
const router = require('koa-router')()
const {
init, get, create, update, del,list
} = require('./api')
router.get('/api/:modelname/:id', init, get)
router.get('/api/:modelname', init, list)
router.post('/api/:modelname', init,create)
router.put('/api/:modelname/:id', init, update)
router.delete('/api/:modelname/:id', init, del)
module.exports = router.routes()