api-health-middleware 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/middleware.js +19 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "api-health-middleware",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Express middleware to report per-request API health to a monitoring backend",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
package/src/middleware.js CHANGED
@@ -1,23 +1,26 @@
1
- const INGEST_ENDPOINT = "https://devops-lite-backend.onrender.com";
1
+ const INGEST_ENDPOINT =
2
+ "https://devops-lite-backend.onrender.com/logs/health";
2
3
 
3
4
  function apiHealth({ apiKey }) {
4
- if (!apiKey) throw new Error("apiKey is required");
5
+ if (!apiKey) {
6
+ throw new Error("apiKey is required");
7
+ }
5
8
 
6
9
  return function apiHealthMiddleware(req, res, next) {
7
10
  const start = process.hrtime.bigint();
8
11
 
9
12
  res.on("finish", () => {
10
13
  try {
11
- // Prevent self-logging
14
+ // Prevent self-logging loop
12
15
  if (req.originalUrl.includes("/logs/health")) return;
13
16
 
14
17
  const durationMs =
15
- Number(process.hrtime.bigint() - start) / 1_000_000;
18
+ Number(process.hrtime.bigint() - start) / 1e6;
16
19
 
17
20
  const payload = {
18
21
  timestamp: new Date().toISOString(),
19
22
  method: req.method,
20
- endpoint: req.route?.path || req.originalUrl,
23
+ endpoint: req.route?.path ?? req.path,
21
24
  fullUrl: req.originalUrl,
22
25
  statusCode: res.statusCode,
23
26
  responseTimeMs: Math.round(durationMs),
@@ -27,12 +30,13 @@ function apiHealth({ apiKey }) {
27
30
  ? res.statusMessage
28
31
  : null,
29
32
  ip: req.ip,
30
- userAgent: req.headers["user-agent"] || null,
33
+ userAgent: req.headers["user-agent"] ?? null,
31
34
  };
32
35
 
33
- // Timeout handling using AbortController
34
36
  const controller = new AbortController();
35
- const timeout = setTimeout(() => controller.abort(), 2000);
37
+ const timeout = setTimeout(() => {
38
+ controller.abort();
39
+ }, 2000);
36
40
 
37
41
  fetch(INGEST_ENDPOINT, {
38
42
  method: "POST",
@@ -43,11 +47,14 @@ function apiHealth({ apiKey }) {
43
47
  body: JSON.stringify(payload),
44
48
  signal: controller.signal,
45
49
  })
46
- .catch(() => {}) // Silent fail
47
- .finally(() => clearTimeout(timeout));
48
-
50
+ .catch(() => {
51
+ // Silent fail — never break main request
52
+ })
53
+ .finally(() => {
54
+ clearTimeout(timeout);
55
+ });
49
56
  } catch {
50
- // Never break main request
57
+ // Never break request lifecycle
51
58
  }
52
59
  });
53
60