han*_*ome 5 javascript models node.js express
我有一个快速应用程序,从外部API获取其数据
api.com/companies (GET, POST)
api.com/companies/id (GET, PUT)
Run Code Online (Sandbox Code Playgroud)
我想创建一个模型来使代码更容易维护,因为你可以看到我在这里重复了很多代码.
router.get('/companies', function(req, res, next) {
http.get({
host: 'http://api.com',
path: '/companies'
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
});
res.render('companies', {data: body});
});
router.get('/companies/:id', function(req, res, next) {
http.get({
host: 'http://api.com',
path: '/companies/' + req.params.id
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
});
res.render('company', {data: body});
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
首先:
http.get 是异步的。经验法则:当您看到回调时,您正在处理异步函数。您无法判断当http.get()您使用 终止请求时 及其回调是否会完成res.render。这意味着 res.render 始终需要在回调中发生。
我在这个例子中使用ES6语法。
// request (https://github.com/request/request) is a module worthwhile installing.
const request = require('request');
// Note the ? after id - this is a conditional parameter
router.get('/companies/:id?', (req, res, next) => {
// Init some variables
let url = '';
let template = ''
// Distinguish between the two types of requests we want to handle
if(req.params.id) {
url = 'http://api.com/companies/' + req.params.id;
template = 'company';
} else {
url = 'http://api.com/companies';
template = 'companies';
}
request.get(url, (err, response, body) => {
// Terminate the request and pass the error on
// it will be handled by express error hander then
if(err) return next(err);
// Maybe also check for response.statusCode === 200
// Finally terminate the request
res.render(template, {data: body})
});
});
Run Code Online (Sandbox Code Playgroud)
关于你的“模型”问题。我宁愿称它们为“服务”,因为模型是一些数据的集合。服务是逻辑的集合。
要创建公司服务模块可以这样做:
// File companyService.js
const request = require('request');
// This is just one of many ways to encapsulate logic in JavaScript (e.g. classes)
// Pass in a config that contains your service base URIs
module.exports = function companyService(config) {
return {
getCompanies: (cb) => {
request.get(config.endpoints.company.many, (err, response, body) => {
return cb(err, body);
});
},
getCompany: (cb) => {
request.get(config.endpoints.company.one, (err, response, body) => {
return cb(err, body);
});
},
}
};
// Use this module like
const config = require('./path/to/config');
const companyService = require('./companyService')(config);
// In a route
companyService.getCompanies((err, body) => {
if(err) return next(err);
res.render(/*...*/)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5621 次 |
| 最近记录: |