javascript - 在 expressjs 中创建模型

标签 javascript node.js express models

我有一个从外部 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/

相关文章:

javascript - 为什么我的自定义验证功能不起作用?

node.js - Express.js : naive technical inquiry

javascript - Node : Express. 如何延迟响应?

javascript - 在 vue js 函数期间显示加载动画

node.js - 在 mongoose 子文档中设置跳过和限制

node.js - ExpressJS : How to redirect a POST request with parameters

node.js - 在 Expres.io 中为 socket.io 调用禁用 CORS

javascript - 在响应式 slider 中设置高度(jQuery Cycle)

javascript - 在 Django CharFields 交互中应用条件

javascript - HTML 验证器返回 "document type does not allow element "脚本“此处”