1 |
|
2 |
|
3 | import { isObject, hasKey } from './jsonrpc'
|
4 | import { undefined } from './constants'
|
5 | import type { Serialization } from '../types'
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | export const NoSerialization: Serialization = {
|
14 | serialization(from) {
|
15 | return from
|
16 | },
|
17 | deserialization(serialized) {
|
18 | return serialized
|
19 | },
|
20 | }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | export const JSONSerialization = (
|
39 | replacerAndReceiver: [((key: string, value: any) => any)?, ((key: string, value: any) => any)?] = [
|
40 | undefined,
|
41 | undefined,
|
42 | ],
|
43 | space?: string | number | undefined,
|
44 | undefinedKeepingBehavior: 'keep' | 'null' | false = 'null',
|
45 | ): Serialization => ({
|
46 | serialization(from) {
|
47 | if (undefinedKeepingBehavior && isObject(from) && hasKey(from, 'result') && from.result === undefined) {
|
48 | const alt = { ...from }
|
49 | alt.result = null
|
50 | if (undefinedKeepingBehavior === 'keep') (alt as any).undef = true
|
51 | from = alt
|
52 | }
|
53 | return JSON.stringify(from, replacerAndReceiver[0], space)
|
54 | },
|
55 | deserialization(serialized) {
|
56 | const result = JSON.parse(serialized as string, replacerAndReceiver[1])
|
57 | if (
|
58 | isObject(result) &&
|
59 | hasKey(result, 'result') &&
|
60 | result.result === null &&
|
61 | hasKey(result, 'undef') &&
|
62 | result.undef === true
|
63 | ) {
|
64 | result.result = undefined
|
65 | delete result.undef
|
66 | }
|
67 | return result
|
68 | },
|
69 | })
|
70 |
|