This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmock_server.ts
79 lines (57 loc) · 2.25 KB
/
mock_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
77
78
79
/**
* This mock server exists to help with tests and serve as a potential foundation for a self-hosted server
*/
import { ClientSentEventData, ServerSentEventData } from './mod.ts';
import { VALID_TEST_AUTH } from './mod_test.ts';
export const abortController = new AbortController();
export const port = 5678;
const IN_MEMORY_LOCKS = new Map<string, boolean>();
Deno.serve({ port, signal: abortController.signal }, async (request) => {
if (request.method !== 'POST') {
return new Response('Not Implemented', { status: 501 });
}
const apiKey = request.headers.get('authorization')?.replace('Bearer ', '');
if (!apiKey || apiKey !== VALID_TEST_AUTH.apiKey) {
return new Response('Unauthorized', { status: 401 });
}
const data: ClientSentEventData = await request.json();
if (data.eventName === 'lock') {
const timeLimitInMs = new Date().getTime() + (data.waitForLockInMs || 500);
let isLocked = Boolean(IN_MEMORY_LOCKS.get(data.lockName));
let nowInMs = new Date().getTime();
// Wait for lock to become unlocked
while (isLocked && nowInMs < timeLimitInMs) {
// Wait another 50ms
await new Promise((resolve) => setTimeout(() => resolve(true), 50));
isLocked = Boolean(IN_MEMORY_LOCKS.get(data.lockName));
nowInMs = new Date().getTime();
}
if (nowInMs >= timeLimitInMs) {
return new Response('Request Timeout', { status: 408 });
}
IN_MEMORY_LOCKS.set(data.lockName, true);
const result: ServerSentEventData = {
eventName: 'lock',
lockName: data.lockName,
};
return new Response(JSON.stringify(result));
} else if (data.eventName === 'unlock') {
const wasLocked = Boolean(IN_MEMORY_LOCKS.get(data.lockName));
IN_MEMORY_LOCKS.set(data.lockName, false);
const result: ServerSentEventData = {
eventName: 'unlock',
lockName: data.lockName,
wasLocked,
};
return new Response(JSON.stringify(result));
} else if (data.eventName === 'check') {
const isLocked = Boolean(IN_MEMORY_LOCKS.get(data.lockName));
const result: ServerSentEventData = {
eventName: 'check',
lockName: data.lockName,
isLocked,
};
return new Response(JSON.stringify(result));
}
return new Response('Not Found', { status: 404 });
});