-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaby-buddy-update.js
More file actions
102 lines (85 loc) · 2.74 KB
/
baby-buddy-update.js
File metadata and controls
102 lines (85 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { SpanStatusCode, trace, metrics } from '@opentelemetry/api';
const tracer = trace.getTracer(
'ble-mqtt-scale-baby-buddy-updater',
'1',
);
const myMeter = metrics.getMeter('ble-mqtt-scale-baby-buddy-meter', '1');
import pThrottle from 'p-throttle';
const throttle = pThrottle({
limit: 5,
interval: 5e3,
});
const weightMeter = myMeter.createHistogram('weight', {
description: 'Weights measured',
unit: 'g',
});
const { BABY_BUDDY_API_URL, BABY_BUDDY_API_TOKEN } = process.env;
import TTLCache from "@isaacs/ttlcache";
const oneDay = String(1000 * 60 * 60 * 24);
const cache = new TTLCache({
max: parseInt(process.env.MAX_CACHE ?? '1000'),
ttl: parseInt(process.env.TTL ?? oneDay)
});
/**
*
* @param {import("./parsePayload.js").ScaleData} parsed
*/
const updateBabyBuddy = (parsed) => {
tracer.startActiveSpan('update-baby-buddy', async (span) => {
const date = new Date().toISOString().slice(0, 16);
weightMeter.record(parsed.weight);
updateCache(date, parsed);
await sendRequest(date, parsed, span);
span.end();
});
}
export const throttledUpdateBabyBuddy = throttle(updateBabyBuddy);
const sendRequest = async (
/** @type {string} */ date,
/** @type {import("./parsePayload.js").ScaleData} */ parsed,
/** @type {import("@opentelemetry/api").Span} */ span
) => {
if (BABY_BUDDY_API_URL === undefined || BABY_BUDDY_API_TOKEN === undefined) {
span.recordException(new Error("BABY_BUDDY_API_URL or BABY_BUDDY_API_TOKEN not set"));
span.setStatus({ code: SpanStatusCode.ERROR });
return;
}
let options = {
method: 'PATCH',
headers: {
'content-type': 'application/json',
Authorization: `Token ${BABY_BUDDY_API_TOKEN}`,
},
body: JSON.stringify({
note: JSON.stringify({
date,
cache: [...cache.entries()].map(x => (
{
date: x[0],
weights: [...x[1]]
}
)).reverse(),
...parsed,
}, null, 2)
})
};
await fetch(BABY_BUDDY_API_URL, options)
.then(res => res.json())
.then(json => span.addEvent("updated-baby-buddy", json))
.catch(err => {
span.recordException(err);
span.setStatus({ code: SpanStatusCode.ERROR });
});
}
function updateCache(
/** @type {string} */ date,
/** @type {import("./parsePayload.js").ScaleData} */ parsed,
) {
if (cache.has(date)) {
let cachedSet = cache.get(date);
cachedSet.add(parsed.weight);
cache.set(date, cachedSet);
} else {
cache.set(date, new Set([parsed.weight]));
}
}