-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathunsafe.ts
62 lines (59 loc) · 1.18 KB
/
unsafe.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
import { Options } from './interface';
import { isDraftable } from './utils';
let readable = false;
export const checkReadable = (
value: any,
options: Options<any, any>,
ignoreCheckDraftable = false
) => {
if (
typeof value === 'object' &&
value !== null &&
(!isDraftable(value, options) || ignoreCheckDraftable) &&
!readable
) {
throw new Error(
`Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.`
);
}
};
/**
* `unsafe(callback)` to access mutable data directly in strict mode.
*
* ## Example
*
* ```ts
* import { create, unsafe } from '../index';
*
* class Foobar {
* bar = 1;
* }
*
* const baseState = { foobar: new Foobar() };
* const state = create(
* baseState,
* (draft) => {
* unsafe(() => {
* draft.foobar.bar = 2;
* });
* },
* {
* strict: true,
* }
* );
*
* expect(state).toBe(baseState);
* expect(state.foobar).toBe(baseState.foobar);
* expect(state.foobar.bar).toBe(2);
* ```
*/
export function unsafe<T>(callback: () => T): T {
readable = true;
let result: T;
try {
result = callback();
} finally {
readable = false;
}
return result;
}