Nodejs Express从控制器到服务的外包逻辑

时间:2019-05-02 17:52:54

标签: javascript node.js express async-await

我有一个从API获取数据的功能。我现在想将程序逻辑外包给服务,以保持控制器的整洁。

我获得了有关Async / Await的数据,很不幸,我不知道如何将其外包给服务?

有人有主意吗?

这是我的homeController.js:

const ispwrapper = require('../lib/ispwrapper');
require('dotenv').config();


const BASE_URL = process.env.API_BASE_URL;

const OPTIONS = {
    username: process.env.API_USERNAME,
    password: process.env.API_PASSWORD
};

const renderHome = async (req, res) => {
    let domain = [],
        message = '';
    try {
        let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS);
        const response = await a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' });

        for (let i = 0; i < response.length; i++){
            domain.push(response[i].domain);
        }
    } catch(err) {
        message = 'Error when retriving domains from API';
    } finally {
        res.render('home', {
            title: 'ISPConfig',
            heading: 'Welcome to my ISPConfig Dashboard',
            homeActive: true,
            domain,
            message
        });
    }
};

module.exports = {
    renderHome
};

我的homeService.js:

const
    ispwrapper = require('../lib/ispwrapper');
require('dotenv').config();

const BASE_URL = process.env.API_BASE_URL;

const OPTIONS = {
    username: process.env.API_USERNAME,
    password: process.env.API_PASSWORD
};

const getDomains = async () => {

// i have no idea how use my renderHome() logic here
};
module.exports = {
    getDomains
};

1 个答案:

答案 0 :(得分:0)

这是我的解决方法。

domainService.js:

const
    ispwrapper = require('../lib/ispwrapper');
require('dotenv').config();

const BASE_URL = process.env.API_BASE_URL;

const OPTIONS = {
    username: process.env.API_USERNAME,
    password: process.env.API_PASSWORD
};

const getDomains = async () => {
    let data = [];
    try {
        let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS);
        let response = await a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' });

        for (let i = 0; i < response.length; i++){
            data.push(response[i].domain);
        }
        return data;
    } catch(err) {
        console.log(err);
    }
};

module.exports = {
    getDomains
};

homeController:

const homeService = require('../services/domainService');

const renderHome = async (req, res) => {
    let message = '',
        domain = [];
    try {
        let response = await homeService.getDomains();

        for (let i = 0; i < response.length; i++){
            domain.push(response[i]);
        }
    } catch(err) {
        message = 'Error when retriving domains from API';
    } finally {
        res.render('home', {
            title: 'ISPConfig',
            heading: 'Welcome to my ISPConfig Dashboard',
            homeActive: true,
            domain,
            message
        });
    }
};

module.exports = {
    renderHome
};