-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession.ts
92 lines (80 loc) · 2.58 KB
/
session.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
90
91
92
import { getUserByUid } from "@/db/users";
import { NYLAS_SCHEDULER_API_URL, SESSION_TIME_TO_LIVE } from "@/lib/constants";
import type { NextApiRequest, NextApiResponse } from "next";
import { z } from "zod";
export const sessionRequestSchema = z.object({
contractor_id: z.string(),
duration: z.number(),
});
export type SessionRequestData = z.infer<typeof sessionRequestSchema>;
export default async function handler(
request: NextApiRequest,
response: NextApiResponse<any>
) {
const { method } = request;
switch (method) {
case "POST":
return createSession(request, response);
default:
response.setHeader("Allow", ["POST"]);
response.status(405).end(`Method ${method} Not Allowed`);
}
}
async function createSession(
request: NextApiRequest,
response: NextApiResponse<any>
) {
const { body } = request;
if (!body) {
return response.status(400).json({ message: "Missing session data" });
}
try {
const sessionRequestData = sessionRequestSchema.parse(body);
const duration = sessionRequestData.duration;
// Get user by id
const user = await getUserByUid(sessionRequestData.contractor_id);
if (!user) {
return response.status(400).json({ message: "Invalid contractor id" });
}
// Make sure the user is a contractor
if (!user.looking_for_work) {
return response
.status(400)
.json({ message: "Contractor is not looking for work" });
}
// Make sure contractor has a appropriate config
if (duration == 30 && !user.config_id) {
return response
.status(400)
.json({
message: "Contractor has not completed their profile for 30 minutes",
});
}
if (duration == 60 && !user.config_id_60) {
return response
.status(400)
.json({
message: "Contractor has not completed their profile for 60 minutes",
});
}
const configID = duration == 30 ? user.config_id : user.config_id_60;
const sessionResponse = await fetch(
`${NYLAS_SCHEDULER_API_URL}/v3/grants/${user.grant_id}/scheduling/session_token`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.NYLAS_API_KEY}`,
},
body: JSON.stringify({
time_to_live: SESSION_TIME_TO_LIVE,
config_id: configID,
}),
}
);
const responseData = await sessionResponse.json();
response.status(200).json(responseData);
} catch (error) {
return response.status(400).json({ message: "Invalid session data" });
}
}