Skip to content

Commit

Permalink
Generate function without external dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
doochik committed May 17, 2020
1 parent 8687cc7 commit 5bf5779
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 20 deletions.
39 changes: 20 additions & 19 deletions lib/formatter.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
'use strict';

const generateFunction = require('generate-function');

function getFormatter(metric, defaultLabels) {
const defaultLabelNames = Object.keys(defaultLabels);
const name = metric.name;
const help = escapeString(metric.help);
const type = metric.type;
const labelsCode = getLabelsCode(metric, defaultLabelNames, defaultLabels);

const gen = generateFunction();
gen(`
function format(item, escapeLabelValue, getValueAsString) {
const info = '# HELP ${name} ${help}\\n# TYPE ${name} ${type}\\n';
let values = '';
for (const val of item.values || []) {
val.labels = val.labels || {};
let metricName = val.metricName || '${name}';
const labels = \`${labelsCode}\`;
const hasLabels = labels.length > 0;
metricName += \`\${hasLabels ? '{' : ''}\${labels}\${hasLabels ? '}' : ''}\`;
let line = \`\${metricName} \${getValueAsString(val.value)}\`;
values += \`\${line}\\n\`;
}
return info + values;
}`);
return gen.toFunction();
// eslint-disable-next-line no-new-func
return new Function(
'item',
'escapeLabelValue',
'getValueAsString',
`
const info = '# HELP ${name} ${help}\\n# TYPE ${name} ${type}\\n';
let values = '';
for (const val of item.values || []) {
val.labels = val.labels || {};
let metricName = val.metricName || '${name}';
const labels = \`${labelsCode}\`;
const hasLabels = labels.length > 0;
metricName += \`\${hasLabels ? '{' : ''}\${labels}\${hasLabels ? '}' : ''}\`;
let line = \`\${metricName} \${getValueAsString(val.value)}\`;
values += \`\${line}\\n\`;
}
return info + values;
`,
);
}

function getLabelsCode(metric, defaultLabelNames, defaultLabels) {
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
"typescript": "^3.0.3"
},
"dependencies": {
"generate-function": "^2.3.1",
"tdigest": "^0.1.1"
},
"types": "./index.d.ts",
Expand Down

0 comments on commit 5bf5779

Please sign in to comment.