forked from calcom/synclinear.com
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsave.ts
90 lines (82 loc) · 2.73 KB
/
save.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
89
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../prisma";
import { encrypt } from "../../utils";
// POST /api/save
export default async function handle(
req: NextApiRequest,
res: NextApiResponse
) {
if (!req.body)
return res.status(400).send({ message: "Request is missing body" });
if (req.method !== "POST") {
return res.status(405).send({
message: "Only POST requests are accepted."
});
}
const { github, linear } = JSON.parse(req.body);
// Check for each required field
if (!github?.userId) {
return res
.status(404)
.send({ error: "Failed to save sync: missing GH user ID" });
} else if (!github?.repoId) {
return res
.status(404)
.send({ error: "Failed to save sync: missing GH repo ID" });
} else if (!linear?.userId) {
return res
.status(404)
.send({ error: "Failed to save sync: missing Linear user ID" });
} else if (!linear?.teamId) {
return res
.status(404)
.send({ error: "Failed to save sync: missing Linear team ID" });
} else if (!linear?.apiKey || !github?.apiKey) {
return res
.status(404)
.send({ error: "Failed to save sync: missing API key" });
}
// Encrypt the API keys
const { hash: linearApiKey, initVector: linearApiKeyIV } = encrypt(
linear.apiKey
);
const { hash: githubApiKey, initVector: githubApiKeyIV } = encrypt(
github.apiKey
);
try {
await prisma.sync.upsert({
where: {
githubUserId_linearUserId_githubRepoId_linearTeamId: {
githubUserId: github.userId,
githubRepoId: github.repoId,
linearUserId: linear.userId,
linearTeamId: linear.teamId
}
},
update: {
githubApiKey,
githubApiKeyIV,
linearApiKey,
linearApiKeyIV
},
create: {
// GitHub
githubUserId: github.userId,
githubRepoId: github.repoId,
githubApiKey,
githubApiKeyIV,
// Linear
linearUserId: linear.userId,
linearTeamId: linear.teamId,
linearApiKey,
linearApiKeyIV
}
});
return res.status(200).send({ message: "Saved successfully" });
} catch (err) {
console.log("Error saving sync:", err.message);
return res.status(404).send({
error: `Failed to save sync with error: ${err.message || ""}`
});
}
}