node使用Koa2搭建web项目的方法(2)
自动扫描controller包实现方法如下
const fs = require('fs'); const router = require('koa-router')(); function addMapping(router, mapping) { for (var url in mapping) { if (url.startsWith('GET ')) { var path = url.substring(4); router.get(path, mapping[url]); console.log(`register URL mapping: GET ${path}`); } else if (url.startsWith('POST ')) { var path = url.substring(5); router.post(path, mapping[url]); console.log(`register URL mapping: POST ${path}`); } else if (url.startsWith('PUT ')) { var path = url.substring(4); router.put(path, mapping[url]); console.log(`register URL mapping: PUT ${path}`); } else if (url.startsWith('DELETE ')) { var path = url.substring(7); router.del(path, mapping[url]); console.log(`register URL mapping: DELETE ${path}`); } else { console.log(`invalid URL: ${url}`); } } } function addControllers(router, dir) { fs.readdirSync(__dirname + '/' + dir).filter((f) => { return f.endsWith('.js'); }).forEach((f) => { console.log(`process controller: ${f}...`); let mapping = require(__dirname + '/' + dir + '/' + f); addMapping(router, mapping); }); } module.exports = function (dir) { var controllersDir = dir || 'controller'; addControllers(router, controllersDir); return router.routes(); };
2.4. 控制器
[userController.js]
***Controller.js是用来处理具体请求信息以及返回数据的,userController.js中处理了GET请求获取用户信息,POST请求保存用户信息
const userService = require('./../service/userService.js'); var getUserinfo = (ctx, next) => { let query = ctx.query; let userId = query.id; let userInfo = userService.getUserById(userId); let html = '<html><body>' + '<div> userinfo: ' + userInfo + '</div>' + '</body></html>'; ctx.response.type ='text/html'; ctx.response.body = html; }; var saveUserinfo = (ctx, next) => { const requestString = ctx.data; //TODO数据处理 Console.log(requestString); }; module.exports = { 'GET /getUserinfo': getUserinfo, 'POST /saveUserinfo': saveUserinfo };
2.5. 数据处理
[userService.js]
处理封装从***Dao.js获取到的数据返回给Controller
const userDao = require('./../dao/userDao.js'); var getUserById = async (userId) => { var users = userDao.getUserById(userId); var responseContent = ''; for(let user of users) { reaponseContent += '姓名:' + user.name + ' |'; reaponseContent += '年龄:' + user.age + ' |'; reaponseContent += '身高:' + user.height + '<br />'; } return responseContent; } module.exports = { getUserById : getUserById };
2.6. 数据获取