Skip to content

Commit

Permalink
(types): be more specific in various places
Browse files Browse the repository at this point in the history
- IStateTreeNode is the type passed to onSnapshot and applySnapshot
- snapshot from onSnapshot _should_ always have string keys
- Storage.getItem should always return a string or object
  - add a typeguard here to properly ensure behavior similar to
    pattern-matching
    - my first typeguard woo!
    - be more general than just checking `jsonify` as we can't have
      a string snapshot anyway (though checking `jsonify` might be more
      efficient than `isString`)
  • Loading branch information
agilgur5 committed Jul 11, 2019
1 parent 2b63093 commit c47523a
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { onSnapshot, applySnapshot } from 'mobx-state-tree'
import { onSnapshot, applySnapshot, IStateTreeNode } from 'mobx-state-tree'

import AsyncLocalStorage from './asyncLocalStorage'

export interface IArgs {
(name: string, store: object, options?: IOptions): Promise<void>
(name: string, store: IStateTreeNode, options?: IOptions): Promise<void>
}
export interface IOptions {
storage?: any,
jsonify?: boolean,
readonly whitelist?: Array<string>,
readonly blacklist?: Array<string>
}
type StrToAnyMap = {[key: string]: any}

export const persist: IArgs = (name, store, options = {}) => {
let {storage, jsonify, whitelist, blacklist} = options
Expand All @@ -22,7 +23,7 @@ export const persist: IArgs = (name, store, options = {}) => {
const whitelistDict = arrToDict(whitelist)
const blacklistDict = arrToDict(blacklist)

onSnapshot(store, (_snapshot: any) => {
onSnapshot(store, (_snapshot: StrToAnyMap) => {
const snapshot = { ..._snapshot }
Object.keys(snapshot).forEach((key) => {
if (whitelist && !whitelistDict[key]) {
Expand All @@ -38,8 +39,8 @@ export const persist: IArgs = (name, store, options = {}) => {
})

return storage.getItem(name)
.then((data: any) => {
const snapshot = !jsonify ? data : JSON.parse(data)
.then((data: object | string) => {
const snapshot = !isString(data) ? data : JSON.parse(data)
// don't apply falsey (which will error), leave store in initial state
if (!snapshot) { return }
applySnapshot(store, snapshot)
Expand All @@ -56,4 +57,8 @@ function arrToDict (arr?: Array<string>): StrToBoolMap {
}, {})
}

function isString (value: any): value is string {
return typeof value === 'string'
}

export default persist

0 comments on commit c47523a

Please sign in to comment.