(endpointId: string)
| 46 | constructor(private apiKey: string, private url: string) {} |
| 47 | |
| 48 | async ping(endpointId: string): Promise<PongResponse> { |
| 49 | const response = await safeFetch(this.url, { |
| 50 | method: "POST", |
| 51 | headers: { |
| 52 | "x-trigger-api-key": this.apiKey, |
| 53 | "x-trigger-endpoint-id": endpointId, |
| 54 | "x-trigger-action": "PING", |
| 55 | }, |
| 56 | }); |
| 57 | |
| 58 | if (!response) { |
| 59 | return { |
| 60 | ok: false, |
| 61 | error: `Could not connect to endpoint ${this.url}`, |
| 62 | }; |
| 63 | } |
| 64 | |
| 65 | if (response.status === 401) { |
| 66 | const body = await safeBodyFromResponse(response, ErrorWithStackSchema); |
| 67 | |
| 68 | if (body) { |
| 69 | return { |
| 70 | ok: false, |
| 71 | error: body.message, |
| 72 | } as const; |
| 73 | } |
| 74 | |
| 75 | return { |
| 76 | ok: false, |
| 77 | error: `Trigger API key is invalid`, |
| 78 | } as const; |
| 79 | } |
| 80 | |
| 81 | if (!response.ok) { |
| 82 | return { |
| 83 | ok: false, |
| 84 | error: `Could not connect to endpoint ${this.url}. Status code: ${response.status}`, |
| 85 | }; |
| 86 | } |
| 87 | |
| 88 | const pongResponse = await safeParseBodyFromResponse(response, PongResponseSchema); |
| 89 | |
| 90 | if (!pongResponse) { |
| 91 | return { |
| 92 | ok: false, |
| 93 | error: `Could not parse response from endpoint. Make sure it points to the correct URL (you might be missing /api/trigger)`, |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | if (!pongResponse.success) { |
| 98 | return { |
| 99 | ok: false, |
| 100 | error: `Endpoint ${this.url} responded with error: ${pongResponse.error.message}`, |
| 101 | }; |
| 102 | } |
| 103 | |
| 104 | const headers = EndpointHeadersSchema.safeParse(Object.fromEntries(response.headers.entries())); |
| 105 |
no test coverage detected