1+ import assign from './es-utils/assign'
2+
3+ interface MetadataDelegate {
4+ add : ( state : { [ key : string ] : any } , section : string , keyOrObj ?: object | string , maybeVal ?: any ) => any
5+ get : ( state : { [ key : string ] : any } , section : string , key ?: string ) => any
6+ clear : ( state : { [ key : string ] : any } , section : string , key ?: string ) => any
7+ }
8+
9+ const metadataDelegate : MetadataDelegate = {
10+ add : ( state , section , keyOrObj , maybeVal ) => {
11+ if ( ! section ) return
12+ let updates
13+
14+ // addMetadata("section", null) -> clears section
15+ if ( keyOrObj === null ) return metadataDelegate . clear ( state , section ) ;
16+
17+ // normalise the two supported input types into object form
18+ if ( typeof keyOrObj === 'object' ) updates = keyOrObj
19+ if ( typeof keyOrObj === 'string' ) updates = { [ keyOrObj ] : maybeVal }
20+
21+ // exit if we don't have an updates object at this point
22+ if ( ! updates ) return
23+
24+ // preventing the __proto__ property from being used as a key
25+ if ( section === '__proto__' || section === 'constructor' || section === 'prototype' ) {
26+ return
27+ }
28+
29+ // ensure a section with this name exists
30+ if ( ! state [ section ] ) state [ section ] = { }
31+
32+ // merge the updates with the existing section
33+ state [ section ] = assign ( { } , state [ section ] , updates )
34+ } ,
35+
36+ get : ( state , section , key ) => {
37+ if ( typeof section !== 'string' ) return undefined
38+ if ( ! key ) {
39+ return state [ section ]
40+ }
41+ if ( state [ section ] ) {
42+ return state [ section ] [ key ]
43+ }
44+ return undefined
45+ } ,
46+
47+ clear : ( state , section , key ) => {
48+ if ( typeof section !== 'string' ) return
49+
50+ // clear an entire section
51+ if ( ! key ) {
52+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
53+ delete state [ section ]
54+ return
55+ }
56+
57+ // preventing the __proto__ property from being used as a key
58+ if ( section === '__proto__' || section === 'constructor' || section === 'prototype' ) {
59+ return
60+ }
61+
62+ // clear a single value from a section
63+ if ( state [ section ] ) {
64+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
65+ delete state [ section ] [ key ]
66+ }
67+ }
68+ }
69+
70+ export default metadataDelegate ;
0 commit comments