forked from benvinegar/counterscale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load-context.ts
41 lines (34 loc) · 1.15 KB
/
load-context.ts
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
import { type AppLoadContext } from "@remix-run/cloudflare";
import { type PlatformProxy } from "wrangler";
import { AnalyticsEngineAPI } from "./app/analytics/query";
interface ExtendedEnv extends Env {
CF_PAGES_COMMIT_SHA: string;
}
type Cloudflare = Omit<PlatformProxy<ExtendedEnv>, "dispose">;
declare module "@remix-run/cloudflare" {
interface AppLoadContext {
cloudflare: Cloudflare;
analyticsEngine: AnalyticsEngineAPI;
}
}
type GetLoadContext = (args: {
request: Request;
context: { cloudflare: Cloudflare }; // load context _before_ augmentation
}) => AppLoadContext;
// Shared implementation compatible with Vite, Wrangler, and Cloudflare Pages
export const getLoadContext: GetLoadContext = ({ context }) => {
if (
!context.cloudflare.env.CF_BEARER_TOKEN ||
!context.cloudflare.env.CF_ACCOUNT_ID
) {
throw new Error("Missing Cloudflare credentials");
}
const analyticsEngine = new AnalyticsEngineAPI(
context.cloudflare.env.CF_ACCOUNT_ID,
context.cloudflare.env.CF_BEARER_TOKEN,
);
return {
...context,
analyticsEngine: analyticsEngine,
};
};