UNPKG

2.07 kBTypeScriptView Raw
1import { IType, IAnyType } from "../../internal";
2/** @hidden */
3declare const $mstNotCustomized: unique symbol;
4/** @hidden */
5export interface _NotCustomized {
6 readonly [$mstNotCustomized]: undefined;
7}
8/** @hidden */
9export declare type _CustomOrOther<Custom, Other> = Custom extends _NotCustomized ? Other : Custom;
10/**
11 * A type that has its snapshots processed.
12 */
13export interface ISnapshotProcessor<IT extends IAnyType, CustomC, CustomS> extends IType<_CustomOrOther<CustomC, IT["CreationType"]>, _CustomOrOther<CustomS, IT["SnapshotType"]>, IT["TypeWithoutSTN"]> {
14}
15/**
16 * Snapshot processors.
17 */
18export interface ISnapshotProcessors<C, CustomC, S, CustomS> {
19 /**
20 * Function that transforms an input snapshot.
21 */
22 preProcessor?(snapshot: CustomC): C;
23 /**
24 * Function that transforms an output snapshot.
25 * @param snapshot
26 */
27 postProcessor?(snapshot: S): CustomS;
28}
29/**
30 * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type.
31 *
32 * Example:
33 * ```ts
34 * const Todo1 = types.model({ text: types.string })
35 * // in the backend the text type must be null when empty
36 * interface BackendTodo {
37 * text: string | null
38 * }
39 * const Todo2 = types.snapshotProcessor(Todo1, {
40 * // from snapshot to instance
41 * preProcessor(sn: BackendTodo) {
42 * return {
43 * text: sn.text || "";
44 * }
45 * },
46 * // from instance to snapshot
47 * postProcessor(sn): BackendTodo {
48 * return {
49 * text: !sn.text ? null : sn.text
50 * }
51 * }
52 * })
53 * ```
54 *
55 * @param type Type to run the processors over.
56 * @param processors Processors to run.
57 * @param name Type name, or undefined to inherit the inner type one.
58 * @returns
59 */
60export declare function snapshotProcessor<IT extends IAnyType, CustomC = _NotCustomized, CustomS = _NotCustomized>(type: IT, processors: ISnapshotProcessors<IT["CreationType"], CustomC, IT["SnapshotType"], CustomS>, name?: string): ISnapshotProcessor<IT, CustomC, CustomS>;
61export {};