-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.ts
64 lines (51 loc) · 1.33 KB
/
conn.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
class StringConn implements AsyncIterable<string> {
readonly #conn: Deno.Conn;
constructor(conn: Deno.Conn) {
this.#conn = conn;
}
write(str: string) {
this.#conn.write(new TextEncoder().encode(str));
}
writeWithHeader(header: string, str: string) {
this.write(`${header}${str}\n`);
}
async* [Symbol.asyncIterator]() {
const decoder = new TextDecoder()
for await (const chunk of Deno.iter(this.#conn)) {
const str = decoder.decode(chunk);
yield str;
}
}
close() {
this.#conn.close();
}
}
class JSONConn<T = unknown> implements AsyncIterable<string> {
readonly #conn: StringConn;
constructor(conn: StringConn | Deno.Conn) {
if (!(conn instanceof StringConn))
conn = new StringConn(conn);
this.#conn = conn;
}
write(o: any) {
this.#conn.write(JSON.stringify(o) + '\n');
}
writeWithHeader(header: string, o: any) {
this.#conn.write(`${header}${JSON.stringify(o)}\n`);
}
public get conn() {
return this.#conn;
}
async* [Symbol.asyncIterator]() {
for await (const chunk of this.#conn) {
yield JSON.parse(chunk);
}
}
close() {
this.#conn.close();
}
}
export {
StringConn,
JSONConn
}