-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
69 lines (58 loc) · 1.94 KB
/
server.ts
File metadata and controls
69 lines (58 loc) · 1.94 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
import { LinearClient } from "@linear/sdk";
import { serve } from "bun";
import { Data, Effect } from "effect";
import z from "zod";
// const apiKey = process.env.API_KEY!; // todo: validate
// const teamId = process.env.TEAM_ID!;
class InvalidSchemaError extends Data.TaggedError("InvalidSchemaError")<{
readonly problem: string;
}> {}
class LinearError extends Data.TaggedError("LinearError")<{}> {}
const teamIdSchema = z.uuid();
const bodySchema = z.object({
title: z.string().min(3).max(1000),
});
const validateTeamId = (teamId: string) =>
Effect.suspend(() =>
teamIdSchema.safeParse(teamId).success
? Effect.succeed(teamId)
: Effect.fail(new InvalidSchemaError({ problem: "Invalid team ID" }))
);
const validateBody = (body: unknown) =>
Effect.try({
try: () => bodySchema.parse(body),
catch: () => new InvalidSchemaError({ problem: "Invalid body" }),
});
const createClient = (apiKey: string) =>
Effect.sync(() => new LinearClient({ apiKey }));
const createIssue = (client: LinearClient, teamId: string, title: string) =>
Effect.tryPromise({
try: () => client.createIssue({ title, teamId }),
catch: () => new LinearError(),
});
// todo: automatically check environment
export type Options = {
apiKey: string;
teamId: string;
};
export const createHandler = (opts: Options) => async (req: Request) =>
Effect.runPromise(
Effect.all([
createClient(opts.apiKey),
validateTeamId(opts.teamId),
validateBody(await req.json()),
]).pipe(
Effect.andThen(([client, teamId, body]) =>
createIssue(client, teamId, body.title)
),
Effect.andThen(() => Effect.succeed(new Response("Ok!"))),
Effect.catchTags({
InvalidSchemaError: (e) =>
Effect.succeed(new Response(e.problem, { status: 400 })),
LinearError: (e) =>
Effect.succeed(
new Response("Internal server error", { status: 500 })
),
})
)
);