profile.js 1.7 KB
'use strict';
const Router = require('koa-router');
const SqlBuilder = require('../utils/sql-builder');
const request = require('superagent');
const _ = require('lodash');

const r = new Router;

const TABLE = {
    DURATION: 'api-duration',
    REPORT: 'error-report'
};

const profile_sql = {
    duration() {
        return SqlBuilder.of(TABLE.DURATION);
    },
    error() {
        return SqlBuilder.of(TABLE.REPORT);
    }
};

async function exec(sql) {
    console.log('influx sql =>', sql);
    return request.get('http://influxd.yoho.cn/query')
        .query({
            q: sql,
            db: 'web-apm'
        }).then(({body: result}) => {
            const series = _.get(result, 'results[0].series[0]', {});
            const col = _.get(series, 'columns', []);
            const values = _.get(series, "values", []);

            return values.map(v => {
                return _.zipObject(col, v)
            })
        });
}

const profile_service = {
    async time() {
        const model = profile_sql.duration().select('*');
        const rows = await exec(model.toSql());
        return {times: rows}
    },

    async error() {
        const model = profile_sql.error().select('*');
        const rows = await exec(model.toSql());
        return {errors: rows};
    }
};

const profile_controller = {
    async time_report(ctx) {
        const result = await profile_service.time();
        await ctx.render('action/profile_time', result);
    },
    async error_report(ctx) {
        const result = await profile_service.error();
        await ctx.render('action/profile_error', result);
    }
};

r.get('/time', profile_controller.time_report);
r.get('/error', profile_controller.error_report);

module.exports = r;