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) => {
export const DefaultEndpointOptions = Symbol.for('DefaultEndpointOptions')
export const astroEnhanceSlice = (apiSlice, options = {}) => {
const { util: { upsertQueryData } } = apiSlice
const { prefix, endpoints: endpointOptions = {} } = options
const { [ DefaultEndpointOptions ]: defaultEndpointOptions = {} } = endpointOptions
const _astro = apiSlice._astro || (apiSlice._astro = { upserts: {} })
const { upserts } = _astro
const enhanceSingleEndpoint = (endpointName) => (endpoint) => {
if (!_astro[ endpointName ]) {
const { endpoints: { [ endpointName ]: endpoint } } = apiSlice
const { initiate } = endpoint
const { [ endpointName ]: { forceRefetch = false } = defaultEndpointOptions } = endpointOptions
_astro[ endpointName ] = (Astro, arg) => {
return fixUnsubscribe(Astro.locals.store, initiate(arg, { forceRefetch, subscribe: true }))
}
}
if (!upserts[ endpointName ]) {
upserts[ endpointName ] = (Astro, arg, data) => {
return fixUnsubscribe(Astro.locals.store, upsertQueryData(endpointName, arg, data))
}
}
}
const endpoints = Object.keys(apiSlice.endpoints).reduce((result, endpointName) => (result[ endpointName ] = enhanceSingleEndpoint(endpointName), result), {})
return apiSlice.enhanceEndpoints({ endpoints })
}
export const createApiWrappers = (apiSlice, options = {}) => {
const { util: { upsertQueryData } } = apiSlice
const { prefix, endpoints: endpointOptions = {} } = options
......