@@ -10,6 +10,7 @@ const debugSubscribe = createDebug('devframe:rpc:state:subscribe')
1010
1111export function createRpcSharedStateServerHost (
1212 rpc : RpcFunctionsHost ,
13+ resolveState ?: ( key : string ) => SharedState < any > | undefined ,
1314) : RpcSharedStateHost {
1415 const sharedState = new Map < string , SharedState < any > > ( )
1516 const stateDisposers = new Map < string , ( ) => void > ( )
@@ -46,24 +47,35 @@ export function createRpcSharedStateServerHost(
4647 }
4748 }
4849
50+ function addState ( key : string , state : SharedState < any > ) {
51+ debug ( 'new-state' , key )
52+ stateDisposers . set ( key , registerSharedState ( key , state ) )
53+ sharedState . set ( key , state )
54+ for ( const fn of keyAddedListeners )
55+ fn ( key )
56+ return state
57+ }
58+
59+ function resolve ( key : string ) {
60+ const existing = sharedState . get ( key )
61+ if ( existing )
62+ return existing
63+ const state = resolveState ?.( key )
64+ return state ? addState ( key , state ) : undefined
65+ }
66+
4967 const host : RpcSharedStateHost = {
5068 get : async < T extends object > ( key : string , options ?: RpcSharedStateGetOptions < T > ) => {
51- if ( sharedState . has ( key ) ) {
52- return sharedState . get ( key ) !
53- }
69+ const existing = resolve ( key )
70+ if ( existing )
71+ return existing
5472 if ( options ?. initialValue === undefined && options ?. sharedState === undefined ) {
5573 throw diagnostics . DF0013 ( { key } )
5674 }
57- debug ( 'new-state' , key )
58- const state = options . sharedState ?? createSharedState < T > ( {
75+ return addState ( key , options . sharedState ?? createSharedState < T > ( {
5976 initialValue : options . initialValue as T ,
6077 enablePatches : false ,
61- } )
62- stateDisposers . set ( key , registerSharedState ( key , state ) )
63- sharedState . set ( key , state )
64- for ( const fn of keyAddedListeners )
65- fn ( key )
66- return state
78+ } ) )
6779 } ,
6880 keys ( ) {
6981 return Array . from ( sharedState . keys ( ) )
@@ -106,10 +118,7 @@ export function createRpcSharedStateServerHost(
106118 name : 'devframe:rpc:server-state:get' ,
107119 type : 'query' ,
108120 handler : async ( key : string ) => {
109- if ( ! sharedState . has ( key ) )
110- return undefined
111- const state = await host . get ( key )
112- return state . value ( )
121+ return resolve ( key ) ?. value ( )
113122 } ,
114123 /**
115124 * Pre-compute snapshots for the build-mode static dump so the SPA
@@ -139,10 +148,7 @@ export function createRpcSharedStateServerHost(
139148 name : 'devframe:rpc:server-state:patch' ,
140149 type : 'query' ,
141150 handler : async ( key : string , patches : SharedStatePatch [ ] , syncId : string ) => {
142- if ( ! sharedState . has ( key ) )
143- return
144- const state = await host . get ( key )
145- state . patch ( patches , syncId )
151+ resolve ( key ) ?. patch ( patches , syncId )
146152 } ,
147153 } )
148154
0 commit comments