UNPKG

@trusthab/composable-resources

Version:

migrating https://github.com/knetikmedia/hab-api/tree/integration/app/resources/composable

107 lines (86 loc) 2.8 kB
const _ = require("lodash"); const axios = require("axios"); const Mustache = require("mustache"); const composer = require("../mixin_loader"); // move this into an initializer const CUSTOMER_ALIASES = { "hab-ucf2": "hab-ucf,hab-knightslanding,hab-knightscircle" }; module.exports = (App) => { const prometheusClient = axios.create({ // timeout: 500, baseURL: process.env.PROMETHEUS_API_HOST, headers: { "Content-Type": "application/json" }, auth: { username: process.env.PROMETHEUS_API_USER, password: process.env.PROMETHEUS_API_PASSWORD } }); class PrometheusHooksResource { static afterList(result) { const { content } = result; const promises = content.map(object => processObject.call(this, object)); return Promise.all(promises).then(content => ({ content })); } static afterFind(result) { return processObject.call(this, result); } } function processObject(result) { const promConfig = getPromConfig.call(this); const promises = promConfig.map((key) => { const config = this.mapping[key]; return customAggregation(config.promExp, result) .then(promResult => config.promEval(result, promResult)); }); return Promise.all(promises).then(() => result); } function getPromConfig() { return _.filter(Object.keys(this.mapping), (key) => { const config = this.mapping[key]; if (config.promExp && config.promEval) { return true; } return false; }); } function customAggregation(exp, obj) { exp = _.isFunction(exp) ? exp(obj) : exp; App.Logger.info( `PrometheusHooks: Custom aggregation query:`, exp, _.get(obj, "constructor.name"), obj.id ); const templateVars = { app_id: getAppId(), ...obj.serialize() }; const query = Mustache.render(exp, templateVars); const params = { query }; App.Logger.info(`PrometheusHooks: Query`, params); return prometheusClient .get("query", { params }) .then(response => response.data) .then((response) => { const { status, data, error } = response; if (status !== "success") { return handleError(`custom aggregation (${exp})`, error); } return data; }) .catch(error => handleError(`custom aggregation (${exp})`, error)); } function getAppId() { let { app_id } = App; Object.keys(CUSTOMER_ALIASES).forEach((key) => { const list = CUSTOMER_ALIASES[key]; if (list.match(app_id)) { app_id = key; } }); return app_id; } function handleError(message, error) { App.Logger.error(`PrometheusHooks: ${message} error`, error); throw new Error(error); } return composer(PrometheusHooksResource, App); };