【问题标题】:How to implement a class function for incrementing counter?如何实现递增计数器的类函数?
【发布时间】:2018-08-07 14:14:54
【问题描述】:

我将如何使用以下内容来创建 functionclass 以便我可以导入此模块以在我的应用程序中发生事件时增加计数。

每当我需要增加计数时,我不想在我的应用程序的任何地方输入这 3 行。

const metrics = request.server.app.metrics;
const metricName = 'user.additem.counter';
metrics.counter(metricName).inc();

这是我目前所拥有的,但它不起作用。

const hoek = require('hoek')
 const incrementCounter = (context, metricName) => {
    const appMetrics = hoek.reach(context, 'request.server.app.metrics');
    if (appMetrics) {
        appMetrics.counter(metricName).inc();
    }
 };

module.exports = { 
    incrementCounter
};

【问题讨论】:

  • 看起来还不错。您是否收到错误或什么不起作用?你怎么称呼你的模块?
  • context 参数由于某种原因无法正常工作。我已经导入了文件,当我尝试 incrementCounter(event, testName)
  • 但如果我尝试const metrics = request.server.app.metrics; const metricName = '_testName_'; metrics.counter(metricName).inc(); 会起作用@

标签: javascript node.js reactjs datadog


【解决方案1】:

所以现在您只需在需要时导入该函数。 (假设你的功能有效)。

假设您将函数保存为incrementCounterFile.js,您只需将文件包含在您想使用的任何位置即可。如果你使用 require 那么

const incrementCounter = require('incrementCounterFile').incrementCounter;
incrementCounter(..)

或者你也可以使用 ES6 import

import { incrementCounter } from './incrementCounterFile'
incrementCounter(..)

希望我能理解你的问题。

【讨论】:

  • 我已经导入并使用了所需的,但似乎该功能不起作用。
  • 如果我错了,请纠正我。当你使用require时,你不应该使用incrementCounterFile.incrementCounter(. .)吗?
猜你喜欢
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多