d8eb67ce by Adam Heath

Add astroEnhanceSlice, which works with code splitting, and is meant to

be called directly where it is used.
1 parent cd508183
...@@ -11,6 +11,32 @@ export const fixUnsubscribe = async (store, action) => { ...@@ -11,6 +11,32 @@ export const fixUnsubscribe = async (store, action) => {
11 11
12 export const DefaultEndpointOptions = Symbol.for('DefaultEndpointOptions') 12 export const DefaultEndpointOptions = Symbol.for('DefaultEndpointOptions')
13 13
14 export const astroEnhanceSlice = (apiSlice, options = {}) => {
15 const { util: { upsertQueryData } } = apiSlice
16 const { prefix, endpoints: endpointOptions = {} } = options
17 const { [ DefaultEndpointOptions ]: defaultEndpointOptions = {} } = endpointOptions
18
19 const _astro = apiSlice._astro || (apiSlice._astro = { upserts: {} })
20 const { upserts } = _astro
21 const enhanceSingleEndpoint = (endpointName) => (endpoint) => {
22 if (!_astro[ endpointName ]) {
23 const { endpoints: { [ endpointName ]: endpoint } } = apiSlice
24 const { initiate } = endpoint
25 const { [ endpointName ]: { forceRefetch = false } = defaultEndpointOptions } = endpointOptions
26 _astro[ endpointName ] = (Astro, arg) => {
27 return fixUnsubscribe(Astro.locals.store, initiate(arg, { forceRefetch, subscribe: true }))
28 }
29 }
30 if (!upserts[ endpointName ]) {
31 upserts[ endpointName ] = (Astro, arg, data) => {
32 return fixUnsubscribe(Astro.locals.store, upsertQueryData(endpointName, arg, data))
33 }
34 }
35 }
36 const endpoints = Object.keys(apiSlice.endpoints).reduce((result, endpointName) => (result[ endpointName ] = enhanceSingleEndpoint(endpointName), result), {})
37 return apiSlice.enhanceEndpoints({ endpoints })
38 }
39
14 export const createApiWrappers = (apiSlice, options = {}) => { 40 export const createApiWrappers = (apiSlice, options = {}) => {
15 const { util: { upsertQueryData } } = apiSlice 41 const { util: { upsertQueryData } } = apiSlice
16 const { prefix, endpoints: endpointOptions = {} } = options 42 const { prefix, endpoints: endpointOptions = {} } = options
......