Write a provider
Use this procedure to get the settings from a source that the built-in providers do not support. The example provider uses sessionStorage.
Procedure
Write a function that returns an object of the type
ConfigProvider.Give the object a unique
name.Write a
loadfunction that returns a configuration document ornull.Optional: write a
savefunction that writes the document.Optional: write a
subscribefunction that sends changes from the source. Send each error of a change to the second argument ofsubscribe.Give the provider to
createWandin theprovidersoption:tscreateWand({ providers: [sessionStorageProvider('my-site-wand')] });
Example
This provider has a load function and a save function:
import { type ConfigDocument, type ConfigProvider, createWand } from 'magic-cursor-wand';
export function sessionStorageProvider(key: string): ConfigProvider {
return {
name: 'session',
async load() {
try {
const raw = sessionStorage.getItem(key);
return raw ? (JSON.parse(raw) as ConfigDocument) : null;
} catch {
return null;
}
},
async save(document) {
try {
sessionStorage.setItem(key, JSON.stringify(document));
} catch {
return;
}
},
};
}Result
The wand calls load one time and puts the result in the slot of the provider. If the provider has a save function and is the last writable provider, autosave writes to it.
Rules for providers
- Return
nullfromloadwhen the source has no document. - Use the
AbortSignalargument ofloadfor network requests. The wand stops the signal ondestroy. - Do not throw an error for an unavailable source. Return
null, or let the wand catch the error and emit aprovidererror. - Send an error of a change, for example a poll that fails, to the error function of
subscribe. The wand emits aprovidererror. - Return the full document from each change. The wand replaces the slot, so a lost change does not cause a permanent difference.