-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathbetterstack.server.ts
More file actions
88 lines (75 loc) · 2.4 KB
/
betterstack.server.ts
File metadata and controls
88 lines (75 loc) · 2.4 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
import { type ApiResult, wrapZodFetch } from "@trigger.dev/core/v3/zodfetch";
import { createCache, DefaultStatefulContext, Namespace } from "@unkey/cache";
import { MemoryStore } from "@unkey/cache/stores";
import { z } from "zod";
import { env } from "~/env.server";
const IncidentSchema = z.object({
data: z.object({
id: z.string(),
type: z.string(),
attributes: z.object({
aggregate_state: z.string(),
}),
}),
});
export type Incident = z.infer<typeof IncidentSchema>;
const ctx = new DefaultStatefulContext();
const memory = new MemoryStore({ persistentMap: new Map() });
const cache = createCache({
query: new Namespace<ApiResult<Incident>>(ctx, {
stores: [memory],
fresh: 15_000,
stale: 30_000,
}),
});
export class BetterStackClient {
private readonly baseUrl = "https://uptime.betterstack.com/api/v2";
async getIncidents() {
const apiKey = env.BETTERSTACK_API_KEY;
if (!apiKey) {
return { success: false as const, error: "BETTERSTACK_API_KEY is not set" };
}
const statusPageId = env.BETTERSTACK_STATUS_PAGE_ID;
if (!statusPageId) {
return { success: false as const, error: "BETTERSTACK_STATUS_PAGE_ID is not set" };
}
const cachedResult = await cache.query.swr("betterstack", async () => {
try {
const result = await wrapZodFetch(
IncidentSchema,
`${this.baseUrl}/status-pages/${statusPageId}`,
{
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
},
{
retry: {
maxAttempts: 3,
minTimeoutInMs: 1000,
maxTimeoutInMs: 5000,
},
}
);
return result;
} catch (error) {
console.error("Failed to fetch incidents from BetterStack:", error);
return {
success: false as const,
error: error instanceof Error ? error.message : "Unknown error",
};
}
});
if (cachedResult.err) {
return { success: false as const, error: cachedResult.err };
}
if (!cachedResult.val) {
return { success: false as const, error: "No result from BetterStack" };
}
if (!cachedResult.val.success) {
return { success: false as const, error: cachedResult.val.error };
}
return { success: true as const, data: cachedResult.val.data.data };
}
}