Сохранить запрос / ответ в таблицу базы данных в NodeJS Express - PullRequest
0 голосов
/ 07 мая 2018

Я пытаюсь

для создания мини-Wireshark / отладочной площадки

Я хочу сохранить все requests & responses, которые проходят через мой API-интерфейс, чтобы я мог использовать их для отладки происходящего.

Основная цель - создать таблицу журналов на веб-странице с возможностью экспорта в формате JSON.

У меня есть

API, написанный на Node JS, использующий Express для соединения с базой данных Postgres через Sequelize

У меня много запросов через мой API.

Вот пример моих запросов

POST /api/login 
POST /api/getSessionTimeOut 
POST /api/checkIfGroupExist/25050-telenet 
POST /api/listUsersInGroup/25050-telenet 
POST /api/primary/createVxLan/ingress/103 
POST /api/primary/createVxLan/egress/103 
POST /api/primary/createSwitch/103 
POST /api/primary/createVxLan/ingress/104 
POST /api/primary/createVxLan/egress/104 
POST /api/primary/createSwitch/104 
POST /api/backup/createVxLan/ingress/103 
POST /api/backup/createVxLan/egress/103 
POST /api/backup/createSwitch/103 
POST /api/backup/createVxLan/ingress/104 
POST /api/backup/createVxLan/egress/104 
POST /api/backup/createSwitch/104 
POST /api/primary/installDevice 
POST /api/monitor/2724 
...
POST /api/monitor/2724 
POST /api/backup/installDevice 
POST /api/monitor/2725 
... 
POST /api/monitor/2725 
POST /api/createDynamicInterface/ingress/103 
POST /api/createDynamicInterface/egress/103 
POST /api/createDynamicInterface/ingress/104 
POST /api/createDynamicInterface/egress/104 
POST /api/createPolicyFirewall/v4/103/vpn 
POST /api/createPolicyFirewall/v4/104/inline 
POST /api/createPolicyFirewall/v4/103/inline 
POST /api/createPolicyFirewall/v4/103/inline

POST /api/createPolicyFirewall/v6/103/vpn 
POST /api/createPolicyFirewall/v6/103/inline 
POST /api/createPolicyFirewall/v6/104/inline 

POST /api/createPolicyFirewall/v6/103/inline

POST /api/installPackage/inline 

POST /api/monitor/2726 
... 
POST /api/monitor/2726 
POST /api/installPackage/vpn 
POST /api/monitor/2727 
... 
POST /api/monitor/2727

Я хотел бы сохранить каждый запрос в таблице журналов в моей базе данных.

Я пытался


Миграция

module.exports = {
    up: (queryInterface, Sequelize) =>
        queryInterface.sequelize.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
            .then(() => {
                queryInterface.createTable('Logs', {
                    id: {
                        allowNull: false,
                        primaryKey: true,
                        type: Sequelize.Sequelize.UUID,
                        defaultValue: Sequelize.literal('uuid_generate_v4()')
                    },
                    user: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    accountId: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    cpeMac: {
                        type: Sequelize.STRING,
                        allowNull: false
                    },
                    pHnsId: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    gHnsId: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    serviceType: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    securityCluster: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    method: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    portalUrl: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    apiUrl: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    data: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    response: {
                        type: Sequelize.STRING,
                        allowNull: true
                    },
                    createdAt: {
                        type: Sequelize.DATE,
                        allowNull: false
                    },
                    updatedAt: {
                        type: Sequelize.DATE,
                        allowNull: false
                    },
                    deletedAt: {
                        type: Sequelize.DATE,
                        allowNull: true
                    }
                })
            }),
    down: (queryInterface) => queryInterface.dropTable('Logs')
};

Модель

module.exports = (sequelize, DataTypes) => {
    const Log = sequelize.define('Log', {
        user: {
            type: DataTypes.STRING,
            allowNull: true
        },
        accountId: {
            type: DataTypes.STRING,
            allowNull: true
        },
        cpeMac: {
            type: DataTypes.STRING,
            allowNull: false
        },
        pHnsId: {
            type: DataTypes.STRING,
            allowNull: true
        },
        gHnsId: {
            type: DataTypes.STRING,
            allowNull: true
        },
        serviceType: {
            type: DataTypes.STRING,
            allowNull: true
        },
        securityCluster: {
            type: DataTypes.STRING,
            allowNull: true
        },
        method: {
            type: DataTypes.STRING,
            allowNull: true
        },
        portalUrl: {
            type: DataTypes.STRING,
            allowNull: true
        },
        apiUrl: {
            type: DataTypes.STRING,
            allowNull: true
        },
        data: {
            type: DataTypes.STRING,
            allowNull: true
        },
        response: {
            type: DataTypes.STRING,
            allowNull: true
        }
    });

    const schema = {
        user: "user",
        accountId: "accountId",
        cpeMac: "cpeMac",
        pHnsId: "pHnsId",
        gHnsId: "gHnsId",
        serviceType: "serviceType",
        securityCluster: "securityCluster",
        method: "method",
        portalUrl: "portalUrl",
        apiUrl: "apiUrl",
        data: "data",
        response: "response"
    };

    Log.list = (models) => new Transformer.List(models, schema).parse();
    Log.single = (model) => new Transformer.Single(model, schema).parse();

    return Log;
};

Контроллер

const Log = require('../models').Log;

module.exports = (config, jwtDecode, Op) => {
    let logs = {};

    /**
     * Create a Log
     *
     * @return {object} log
     */
    logs.create = async(req, res, next) => {
        try {

            let $body = {
                name: log.name,
                accountId: log.accountId,
                cpeMac: log.cpeMac,
                pHnsId: log.pHnsId,
                gHnsId: log.gHnsId,
                serviceType: log.serviceType,
                securityCluster: log.securityCluster,
                method: log.method,
                portalUrl: log.portalUrl,
                apiUrl: log.apiUrl,
                data: log.data,
                response: log.response
            };

            let response = await Log.create($body);
            res.status(200).send(JSON.parse(response));
        } catch (error) {
            next(error);
        }
    };

    return logs;
};

Услуги

module.exports = (config, request) => {
    let log = {};

    /*==============================
    =            create            =
    ==============================*/

    log.create = ($body) => {
        let $options = {
            method: "POST",
            uri: `/api/logs/create`,
            body: $body
        };

        return new Promise((resolve, reject) => {
            request($options)
                .then(data => resolve(JSON.stringify(data)))
                .catch(error => reject(error));
        });
    };

    return log;
};

Маршрут

app.post('/api/logs/create', controllers.logs.create);

Результат

Теперь, когда у меня есть все готовые к работе части, но я не уверен, как соединить их все, чтобы иметь возможность хранить все запросы / ответы в базе данных?

1 Ответ

0 голосов
/ 09 мая 2018

В качестве базовой схемы для создания этого промежуточного программного обеспечения вы должны сделать что-то вроде этого:

App.js

/* You're imports and setup */

/*
    any time a call is made, it will hit this function
    app.use accepts a function, which will give the parameters
    req, res, next.
        i.e. app.use((req, res, next) => { ... })
    so we'll pass in you're logs.create function
    and the request will have all the information on what
    endpoint is being given.
*/
app.use(controllers.logs.create)

/* the rest of your routes */

Если вы предоставите файл app.js, я могу дать вам лучшую версию того, что выше

Дайте мне знать, могу ли я что-нибудь еще сделать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...