koa 模拟KeystoneJS 的前端自动生成代码框架(mongoose+api)

481 阅读1分钟

代码结构

image.png

代码

//安装npm i koa-bodyparser koa koa-static mongoose -S

//index.js 主程序入口
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}`)
})

//model/user.js
module.exports = {
    schema: {
        mobile: { type: String, required: false },
        realName: { type: String, required: false },
    }
}

//conf.js
module.exports = {
    db: {
        url:"mongodb://xxxx:xxx@81.71.143.209:xxxx/test?authSource=admin",
        options: { useNewUrlParser: true }
    }
}

//framework/api.js api生成模板
module.exports = {
    async init(ctx, next) {
        console.log(ctx.params)
        const model = ctx.app.$model[ctx.params.modelname]//注意这里使用通配符变量modelname 获取url上使用的 模块名称
        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({})/*  */
    },
}

//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 => 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
}

//framework/router.js 路由生成模板
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()