我有一个快速应用程序,从外部API获取其数据
api.com/companies (GET, POST)
api.com/companies/id (GET, PUT)
我想创建一个模型来使代码更容易维护,因为你可以看到我在这里重复了很多代码.
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});
});
我怎样才能做到这一点?
解决方法:
首先:
http.get是异步的.经验法则:当您看到回调时,您正在处理异步函数.您无法判断,当您使用res.render终止请求时,是否将完成http.get()及其回调.
这意味着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})
});
});
关于你的“模特”问题.
我宁愿称它们为“服务”,因为模型是一些数据集合.服务是逻辑的集合.
要创建公司服务模块,请执行以下操作:
// 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(/*...*/)
});
原文地址:https://codeday.me/bug/20190519/1134322.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。