-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathadapter.ts
More file actions
53 lines (49 loc) · 1.28 KB
/
adapter.ts
File metadata and controls
53 lines (49 loc) · 1.28 KB
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
import { Value } from '@sinclair/typebox/value';
import {
OpaqueTransportMessage,
OpaqueTransportMessageSchema,
} from '../transport';
import { Codec } from './types';
import { DeserializeResult, SerializeResult } from '../transport/results';
import { coerceErrorString } from '../transport/stringifyError';
/**
* Adapts a {@link Codec} to the {@link OpaqueTransportMessage} format,
* accounting for fallibility of toBuffer and fromBuffer and wrapping
* it with a Result type.
*/
export class CodecMessageAdapter {
constructor(private readonly codec: Codec) {}
toBuffer(msg: OpaqueTransportMessage): SerializeResult {
try {
return {
ok: true,
value: this.codec.toBuffer(msg),
};
} catch (e) {
return {
ok: false,
reason: coerceErrorString(e),
};
}
}
fromBuffer(buf: Uint8Array): DeserializeResult {
try {
const parsedMsg = this.codec.fromBuffer(buf);
if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
return {
ok: false,
reason: 'transport message schema mismatch',
};
}
return {
ok: true,
value: parsedMsg,
};
} catch (e) {
return {
ok: false,
reason: coerceErrorString(e),
};
}
}
}