UNPKG

2.25 kBPlain TextView Raw
1//#region Serialization
2
3import { isObject, hasKey } from './jsonrpc'
4import { undefined } from './constants'
5import type { Serialization } from '../types'
6
7
8/**
9 * Serialization implementation that do nothing
10 * @remarks {@link Serialization}
11 * @public
12 */
13export const NoSerialization: Serialization = {
14 serialization(from) {
15 return from
16 },
17 deserialization(serialized) {
18 return serialized
19 },
20}
21
22/**
23 * Create a serialization by JSON.parse/stringify
24 *
25 * @param replacerAndReceiver - Replacer and receiver of JSON.parse/stringify
26 * @param space - Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
27 * @param undefinedKeepingBehavior - How to keep "undefined" in result of SuccessResponse?
28 *
29 * If it is not handled properly, JSON.stringify will emit an invalid JSON RPC object.
30 *
31 * Options:
32 * - `"null"`(**default**): convert it to null.
33 * - `"keep"`: try to keep it by additional property "undef".
34 * - `false`: Don't keep it, let it break.
35 * @remarks {@link Serialization}
36 * @public
37 */
38export 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//#endregion