Skip to content

Instantly share code, notes, and snippets.

@muuki88
Created September 14, 2018 08:29
Show Gist options
  • Save muuki88/e0adbd264eff03ec63d12819472ca31a to your computer and use it in GitHub Desktop.
Save muuki88/e0adbd264eff03ec63d12819472ca31a to your computer and use it in GitHub Desktop.
KeyValueStore Serialization
const deserializeBoolean = (value: string) => value === 'true';
const deserializeString = (value: string) => value;
const deserializeNumber = (value: string) => parseInt(value);
const serializeBoolean = (value: boolean) => value ? 'true' : 'false';
const serializeString = (value: string) => value;
const serializeNumber = (value: number) => number.toFixed();
/**
* Each key-value storage key needs a function to deserialize its string value
* from the database into its own type. Each type is specified in KeyValueStorage.
*/
const keyValueStorageDeserializers : { [key in KeyValueStorageKey]: (value: string) => KeyValueStorage[key] } = {
'setting1': deserializeBoolean,
'setting2': deserializeString,
'setting3': deserializeNumber
};
/**
* Each key-value storage key needs a function to serialize its value
* to a string that can be saved in the database.
*/
const keyValueStorageSerializers : { [key in KeyValueStorageKey]: (value: KeyValueStorage[key]) => string } = {
'setting1': serializeBoolean,
'setting2': serializeString,
'setting3': serializeNumber
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment