gpt4 book ai didi

javascript - 在 expressjs 中创建模型

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:02 24 4
gpt4 key购买 nike

我有一个从外部 API 获取数据的 Express 应用

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(/*...*/)
});

关于javascript - 在 expressjs 中创建模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40122056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com