-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
api_handler.ts
86 lines (74 loc) · 2.28 KB
/
api_handler.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
import { CustomURLSearchParams } from "./custom_url_search_params.ts";
import { Svg } from "./svg.ts";
import { W3C_COLOR_NAMES } from "./w3c_color_names.ts";
// cache two hours
const CACHE_MAX_AGE = 7200;
const MAX_STRING_LENGTH = 70;
export const errorMessages = {
noText: "'text' parameter is required. e.g. 'text=Hello%20world!'",
tooLongText:
`'text' parameter is too long. Fix it less than ${MAX_STRING_LENGTH} characters.`,
invalidColor: "invalid color is detected.",
tooLongComment:
`'comment' parameter is too long. Fix it less than ${MAX_STRING_LENGTH} characters.`,
};
const colorNames = Object.keys(W3C_COLOR_NAMES);
export function getValidColor(str: string): string | null {
return /^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(str)
? `#${str}`
: colorNames.includes(str) || str === "none"
? str
: null;
}
export const apiHeaders = new Headers({
"Content-Type": "image/svg+xml",
"Cache-Control": `public, max-age=${CACHE_MAX_AGE}`,
});
export function apiHandler(searchParams: URLSearchParams): Response {
const errorRes = (message: string): Response => {
return new Response(
Svg.error(message),
{
status: 400,
headers: apiHeaders,
},
);
};
const params = new CustomURLSearchParams(searchParams);
const text = params.get("text");
if (!text) {
return errorRes(errorMessages.noText);
} else if (text.length > MAX_STRING_LENGTH) {
return errorRes(errorMessages.tooLongText);
}
const colorParams = [
["bg", "ffffff"],
["frame", "000000"],
["l0", "ebedf0"],
["l1", "9be9a8"],
["l2", "40c463"],
["l3", "30a14e"],
["l4", "216e39"],
].map(([key, defaultValue]) =>
getValidColor(params.getString(key, defaultValue))
);
if (colorParams.some((item) => item === null)) {
return errorRes(errorMessages.invalidColor);
}
const speed = params.getNumber("speed", 200);
const comment = params.getString(
"comment",
"Generated by kawarimidoll/typograssy",
);
if (comment.length > MAX_STRING_LENGTH) {
return errorRes(errorMessages.tooLongComment);
}
const [bg, frame, ...colors] = colorParams as string[];
return new Response(
Svg.render({ text, colors, bg, frame, speed, comment }),
{
status: 200,
headers: apiHeaders,
},
);
}