-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
88 lines (79 loc) · 2.62 KB
/
index.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
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
// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.
import { decode, serve } from "./deps.ts";
import { pull } from "./endpoints/pull.ts";
import { createSpace } from "./endpoints/create-space.ts";
import { push } from "./endpoints/push.ts";
import { mutators } from "../_shared/mutators.ts";
import { spaceExists } from "./endpoints/space-exists.ts";
serve(async (req: Request) => {
const { searchParams: query, pathname: action } = new URL(req.url);
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, x-replicache-requestid, content-type",
};
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
const spaceId = query.get("spaceID");
if (spaceId === null) {
return new Response("Missing 'spaceID' parameter", {
headers: corsHeaders,
status: 400,
});
}
const authorization = req.headers.get("authorization")?.split(" ")[1]!;
const { payload: claims } = decode(authorization);
try {
switch (action.split("/").at(-1)) {
case "pull": {
const json = await req.json();
return new Response(JSON.stringify(await pull(spaceId, json, claims)), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}
case "push": {
const json = await req.json();
await push(spaceId, json, mutators, claims);
return new Response(JSON.stringify({}), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
status: 200,
});
}
case "create-space": {
await createSpace(spaceId, claims);
return new Response(`Space '${spaceId}' created`, {
headers: { ...corsHeaders },
});
}
case "space-exists": {
return new Response(
String({ spaceExists: await spaceExists(spaceId, claims) }),
{
headers: { ...corsHeaders },
}
);
}
default: {
return new Response("Invalid Action - " + String(action), {
headers: corsHeaders,
status: 400,
});
}
}
} catch (e) {
console.error(e.toString());
if (e.toString().includes("Broken pipe")) {
return new Response("Connection Error - Please try again", {
headers: corsHeaders,
status: 400,
});
}
return new Response(e.toString(), {
headers: { ...corsHeaders },
status: 500,
});
}
});