forked from yurkth/sprator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
76 lines (67 loc) · 2 KB
/
server.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
import express from 'express';
import { ParsedQs } from 'qs';
import { generate } from '.';
const app = express();
app.get('*', (req, res) => {
try {
const { background, border, dot, fill, ppd, seed } = validate(req.query);
console.log({ background, border, dot, fill, ppd, seed });
try {
const buffer = generate(seed, dot, ppd, fill, border, background, 2);
res.type('png');
res.send(buffer);
} catch (error) {
// Unexpected error was occured.
console.error(error);
res.sendStatus(500);
}
} catch (error) {
res.status(400).send(error.message);
}
});
if (process.env.NODE_ENV !== 'test') {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
}
export function validate(query: ParsedQs) {
const str = (key: string, defaultValue: string) => {
const rawValue = query[key];
return rawValue === undefined
? defaultValue
: Array.isArray(rawValue)
? rawValue[0] + ''
: rawValue + '';
};
const int = (key: string, defaultValue: number) => {
const rawValue = query[key];
const value =
rawValue === undefined
? defaultValue
: parseInt(
Array.isArray(rawValue) ? rawValue[0] + '' : rawValue + '',
10
);
if (Number.isNaN(value)) {
throw new Error(`${key} must be number but given ${value}`);
}
return value;
};
const seed = str('seed', '');
const dot = int('dot', 10);
if (dot < 6 || dot > 12) {
throw new Error(`dot must be between 6 and 12 but given ${dot}`);
}
if (dot % 2 !== 0) {
throw new Error(`dot must be even number but given ${dot}`);
}
const ppd = int('ppd', 16);
if (ppd < 1 || ppd > 1024) {
throw new Error(`ppd must be between 1 and 1024 but given ${ppd}`);
}
const fill = str('fill', '#228b22');
const border = str('border', '#2f4f4f');
const background = str('background', '#000000');
return { seed, dot, ppd, fill, border, background };
}