GlobalMetricsManager.mjs 1011 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { GlobalMetric } from '../../models/GlobalMetric.js'
  2. /**
  3. * A Generic collection used to track metrics shared across the entirety of the application
  4. * examples:
  5. * - a metric to measure how many signups we have for an expensive labs experiment, so we can end stop signups
  6. * - a metric to measure how many users have been added to a test, so we can stop adding more once a cap is reached
  7. *
  8. */
  9. async function getMetric(key, defaultValue = 0) {
  10. const metric = await GlobalMetric.findById(key)
  11. if (!metric) {
  12. return defaultValue
  13. }
  14. return metric.value
  15. }
  16. async function setMetric(key, value) {
  17. return await GlobalMetric.findOneAndUpdate(
  18. { _id: key },
  19. { $set: { value } },
  20. { new: true, upsert: true }
  21. )
  22. }
  23. async function incrementMetric(key, value = 1) {
  24. return await GlobalMetric.findOneAndUpdate(
  25. { _id: key },
  26. { $inc: { value } },
  27. { new: true, upsert: true, setDefaultsOnInsert: true }
  28. )
  29. }
  30. export default {
  31. getMetric,
  32. setMetric,
  33. incrementMetric,
  34. }