forked from GTBitsOfGood/gen-soln
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.ts
62 lines (53 loc) · 1.65 KB
/
util.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
import { NextApiRequest, NextApiResponse } from "next";
import fetch from "isomorphic-unfetch";
import errors from "utils/errors";
interface APISuccessResponse<T> {
success: true;
payload: T;
}
interface APIFailureResponse {
success: false;
message: string;
}
// Use this function on server side to handle incoming API requests:
export const handleRequestWithPayloadResponse = async <T>(
req: NextApiRequest,
res: NextApiResponse,
callback: (body: NextApiRequest["body"]) => Promise<T>,
bodyHasProperties: string[] = []
): Promise<void> => {
try {
if (bodyHasProperties.some(property => !(property in req.body))) {
res.status(400).json({
success: false,
message: `One or more of the following properties was missing in req.body: [${bodyHasProperties.toString()}]`
});
return;
}
const response: APISuccessResponse<T> = {
success: true,
payload: await callback(req.body)
};
res.status(200).json(response);
} catch (error) {
const response: APIFailureResponse = {
success: false,
message: (error instanceof Error && error.message) || errors.GENERIC_TEXT
};
res.status(400).json(response);
}
};
// Use this function on client side to make API requests
export const fetchRequestWithPayloadResponse = async <T>(
url: RequestInfo,
options: RequestInit = {}
): Promise<T> => {
const res = await fetch(url, {
mode: "same-origin",
...options
});
const json = (await res.json()) as APISuccessResponse<T> | APIFailureResponse;
if (!json) throw new Error("Couldn't connect to API.");
if (!json.success) throw new Error(json.message);
return json.payload;
};