1
- import { wrapZodFetch } from "@trigger.dev/core/v3/zodfetch" ;
1
+ import { type ApiResult , wrapZodFetch } from "@trigger.dev/core/v3/zodfetch" ;
2
+ import { createCache , DefaultStatefulContext , Namespace } from "@unkey/cache" ;
3
+ import { MemoryStore } from "@unkey/cache/stores" ;
2
4
import { z } from "zod" ;
3
5
import { env } from "~/env.server" ;
4
6
@@ -14,6 +16,17 @@ const IncidentSchema = z.object({
14
16
15
17
export type Incident = z . infer < typeof IncidentSchema > ;
16
18
19
+ const ctx = new DefaultStatefulContext ( ) ;
20
+ const memory = new MemoryStore ( { persistentMap : new Map ( ) } ) ;
21
+
22
+ const cache = createCache ( {
23
+ query : new Namespace < ApiResult < Incident > > ( ctx , {
24
+ stores : [ memory ] ,
25
+ fresh : 15_000 ,
26
+ stale : 30_000 ,
27
+ } ) ,
28
+ } ) ;
29
+
17
30
export class BetterStackClient {
18
31
private readonly baseUrl = "https://uptime.betterstack.com/api/v2" ;
19
32
@@ -28,27 +41,48 @@ export class BetterStackClient {
28
41
return { success : false as const , error : "BETTERSTACK_STATUS_PAGE_ID is not set" } ;
29
42
}
30
43
31
- try {
32
- return await wrapZodFetch (
33
- IncidentSchema ,
34
- `${ this . baseUrl } /status-pages/${ statusPageId } ` ,
35
- {
36
- headers : {
37
- Authorization : `Bearer ${ apiKey } ` ,
38
- "Content-Type" : "application/json" ,
39
- } ,
40
- } ,
41
- {
42
- retry : {
43
- maxAttempts : 3 ,
44
- minTimeoutInMs : 1000 ,
45
- maxTimeoutInMs : 5000 ,
44
+ const cachedResult = await cache . query . swr ( "betterstack" , async ( ) => {
45
+ try {
46
+ const result = await wrapZodFetch (
47
+ IncidentSchema ,
48
+ `${ this . baseUrl } /status-pages/${ statusPageId } ` ,
49
+ {
50
+ headers : {
51
+ Authorization : `Bearer ${ apiKey } ` ,
52
+ "Content-Type" : "application/json" ,
53
+ } ,
46
54
} ,
47
- }
48
- ) ;
49
- } catch ( error ) {
50
- console . error ( "Failed to fetch incidents from BetterStack:" , error ) ;
51
- return { success : false as const , error } ;
55
+ {
56
+ retry : {
57
+ maxAttempts : 3 ,
58
+ minTimeoutInMs : 1000 ,
59
+ maxTimeoutInMs : 5000 ,
60
+ } ,
61
+ }
62
+ ) ;
63
+
64
+ return result ;
65
+ } catch ( error ) {
66
+ console . error ( "Failed to fetch incidents from BetterStack:" , error ) ;
67
+ return {
68
+ success : false as const ,
69
+ error : error instanceof Error ? error . message : "Unknown error" ,
70
+ } ;
71
+ }
72
+ } ) ;
73
+
74
+ if ( cachedResult . err ) {
75
+ return { success : false as const , error : cachedResult . err } ;
76
+ }
77
+
78
+ if ( ! cachedResult . val ) {
79
+ return { success : false as const , error : "No result from BetterStack" } ;
52
80
}
81
+
82
+ if ( ! cachedResult . val . success ) {
83
+ return { success : false as const , error : cachedResult . val . error } ;
84
+ }
85
+
86
+ return { success : true as const , data : cachedResult . val . data . data } ;
53
87
}
54
88
}
0 commit comments