-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.ts
46 lines (39 loc) · 1.36 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
import { Response, ServerRequest } from 'https://deno.land/[email protected]/http/server.ts';
export function formatNumber(n: number): string
{
if (n < 1e3) return n.toString();
if (n < 1e4) return (n/1e3).toFixed(1) + 'k';
if (n < 1e6) return (n/1e3).toFixed(0) + 'k';
if (n < 1e7) return (n/1e6).toFixed(1) + 'M';
else return (n/1e6).toFixed(0) + 'M';
}
export function makeResponder(req: ServerRequest, tStart: number)
{
return function respond(res: IResponse) {
if (!res.headers) res.headers = new Headers();
res.headers.set('Access-Control-Allow-Origin', '*');
let body: string | Uint8Array | undefined;
if (res.body) {
if (typeof res.body == 'object' && res.body.constructor.name == 'Object') {
body = JSON.stringify(res.body);
res.headers.set('Content-Type', 'application/json');
}
else if (typeof res.body == 'string' || res.body instanceof Uint8Array) {
body = res.body;
}
}
req.respond({
...res,
body,
});
const length = body ? formatNumber(body.length) : '0';
console.log(`${req.method} ${req.url} -> ${res.status ?? 200}, ${length}B, in ${Date.now() - tStart} ms`);
}
}
export interface IResponse extends Omit<Response, 'body'> {
body?: string | object
}
export function generateId(): string
{
return Math.floor(Math.random()*1e10).toString().padStart(10, '0');
}