Store

Defines the Data Store class.

Constructor

new Store(options)

Initializer for Store class

Parameters:
NameTypeDescription
optionsobject

options to use for initialization

Members

data :object

Stores data by type. { todos: { records: observable.map(), // records by id cache: observable.map(), // cached ids by url meta: observable.map() // meta information by url } }

Type:
  • object
Default Value
  • {}

lastResponseHeaders :object

The most recent response headers according to settings specified as headersOfInterest

Type:
  • object
Default Value
  • {}

loadedStates :Map

Map of data that has been loaded into the store. This can be observed to know if a given type (or tag) has finished loading.

  • Key is a tag that is either the model type or a custom value
  • Falue is a Set of JSON-encoded objects with unique urls and queryParams Set[JSON.stringify({ url, type, queryParams, queryTag })]
Type:
  • Map

loadingStates :Map

Map of data that is in flight. This can be observed to know if a given type (or tag) is still processing.

  • Key is a tag that is either the model type or a custom value
  • Falue is a Set of JSON-encoded objects with unique urls and queryParams Set[JSON.stringify({ url, type, queryParams, queryTag })]
Type:
  • Map

pauseSnapshots :boolean

True if models in the store should stop taking snapshots. This is useful when updating records without causing records to become 'dirty', for example when initializing records using add

Type:
  • boolean

Methods

add(type, props, options) → {object|Array}

Adds an instance or an array of instances to the store. Adds the model to the type records index Adds relationships explicitly. This is less efficient than adding via data if there are also inverse relationships.

const todo = store.add('todos', { name: "A good thing to measure" })
todo.name
=> "A good thing to measure"

const todoArray = [{ name: "Another good thing to measure" }]
const [todo] = store.add('todos', [{ name: "Another good thing to measure" }])
todo.name
=> "Another good thing to measure"
Parameters:
NameTypeDescription
typestring

the model type

propsobject | Array

the properties to use

optionsobject

currently supports skipInitialization

Returns:

the new record or records

Type: 
object | Array

bulkCreate(type, records, options) → {Promise}

Save a collection of new records via a bulk-supported JSONApi endpoint. All records need to be of the same type and not have an existing id.

Parameters:
NameTypeDescription
typestring

the model type

recordsArray

to be bulk created

optionsobject

{queryParams, extensions}

Returns:

the created records

Type: 
Promise

bulkSave(type, records, options) → {Promise}

Saves a collection of records via a bulk-supported JSONApi endpoint. All records need to be of the same type.

Parameters:
NameTypeDescription
typestring

the model type

recordsArray

records that will be bulk saved

optionsobject

{queryParams, extensions}

Returns:

the saved records

Type: 
Promise

bulkUpdate(type, records, options) → {Promise}

Updates a collection of records via a bulk-supported JSONApi endpoint. All records need to be of the same type and have an existing id.

Parameters:
NameTypeDescription
typestring

the model type

recordsArray

array of records to be bulk updated

optionsobject

{queryParams, extensions}

Returns:

the saved records

Type: 
Promise

clearCache(type) → {Set}

Clears the cache for provided record type

Parameters:
NameTypeDescription
typestring

the model type

Returns:

the cleared set

Type: 
Set

createModelFromData(data, options) → {object}

Helper to create a new model

Parameters:
NameTypeDescription
dataobject

id, type, attributes and relationships

optionsobject

currently supports skipInitialization

Returns:

model instance

Type: 
object

createOrUpdateModelFromData(data) → {object}

Creates or updates a model

Parameters:
NameTypeDescription
dataobject

the object will be used to update or create a model

Returns:

the record

Type: 
object

createOrUpdateModelsFromData(data) → {Array}

Create multiple models from an array of data. It will only build objects with defined models, and ignore everything else in the data.

Parameters:
NameTypeDescription
dataArray

the array of jsonapi data

Returns:

an array of the models serialized

Type: 
Array

deleteLoadingState(state)

Removes a loading state. If that leaves an empty array for the map key in loadingStates, will also delete the set. Also adds to loadedStates.

Parameters:
NameTypeDescription
stateobject

the state to remove

fetch(url, options) → {Promise}

Wrapper around fetch applies user defined fetch options

Parameters:
NameTypeDescription
urlstring

the url to fetch

optionsobject

override options to use for fetching

Returns:

the data from the server

Type: 
Promise

fetchAll(type, options) → {Promise}

Finds all records with the given type. Always fetches from the server.

Parameters:
NameTypeDescription
typestring

the type to find

optionsobject

query params and other options

Returns:

Promise.resolve(records) or Promise.reject([Error: [{ detail, status }])

Type: 
Promise

fetchMany(type, ids, options) → {Promise}

Fetch all records with the given type and ids from the server.

Parameters:
NameTypeDescription
typestring

the type to get

idsstring

the ids of the records to get

optionsobject

{ queryParams }

Returns:

Promise.resolve(records) or Promise.reject([Error: [{ detail, status }])

Type: 
Promise

fetchOne(type, id, options) → {Promise}

Fetches record by id from the server and returns a Promise.

Parameters:
NameTypeDescription
typestring

the record type to fetch

idstring

the id of the record to fetch

optionsobject

{ queryParams }

Returns:

record result wrapped in a Promise

Type: 
Promise

fetchUrl(type, queryParams, id, options) → {string}

Builds fetch url based on type, queryParams, id, and options

Parameters:
NameTypeDescription
typestring

the type to find

queryParamsobject

params to be used in the fetch

idstring

a model id

optionsobject

options for fetching

Returns:

a formatted url

Type: 
string

findAll(type, options) → {Promise}

Finds all records of the given type. If any records from the given type from url are in the store, it returns those. Otherwise, it fetches all records from the server.

store.findAll('todos') // fetch triggered => [todo1, todo2, todo3]

store.findAll('todos') // no fetch triggered => [todo1, todo2, todo3]

Query params can be passed as part of the options hash. The response will be cached, so the next time findAll is called with identical params and values, the store will first look for the local result.

store.findAll('todos', { queryParams: { filter: { start_time: '2020-06-01T00:00:00.000Z', end_time: '2020-06-02T00:00:00.000Z' } } })

Parameters:
NameTypeDescription
typestring

the type to find

optionsobject

{ queryParams }

Returns:

Promise.resolve(records) or Promise.reject([Error: [{ detail, status }])

Type: 
Promise

findMany(type, ids, options) → {Promise}

Finds multiple records of the given type with the given ids and returns them wrapped in a Promise. If all records are in the store, it returns those. If some records are in the store, it returns those plus fetches all other records. Otherwise, it fetches all records from the server.

store.findMany('todos', [1, 2, 3]) // fetch triggered => [todo1, todo2, todo3]

store.findMany('todos', [3, 2, 1]) // no fetch triggered => [todo1, todo2, todo3]

Parameters:
NameTypeDescription
typestring

the type to find

idsstring

the ids of the records to find

optionsobject

{ queryParams }

Returns:

a promise that will resolve an array of records

Type: 
Promise

findOne(type, id, options) → {Promise}

Finds a record by id, always returning a Promise. If available in the store, it returns that record. Otherwise, it fetches the record from the server.

store.findOne('todos', 5) // fetch triggered => Promise(todo) store.findOne('todos', 5) // no fetch triggered => Promise(todo)

Parameters:
NameTypeDescription
typestring

the type to find

idstring

the id of the record to find

optionsobject

{ queryParams }

Returns:

a promise that will resolve to the record

Type: 
Promise

getAll(type, options) → {Array}

Gets all records with the given type from the store. This will never fetch from the server.

Parameters:
NameTypeDescription
typestring

the type to find

optionsobject

options for fetching queryParams

Returns:

array of records

Type: 
Array

getCachedId(type, id) → {object}

Gets a record from store based on cached query

Parameters:
NameTypeDescription
typestring

the model type

idstring

the id to get

Returns:

the cached object

Type: 
object

getCachedIds(type, url) → {Array}

Gets records from store based on cached query

Parameters:
NameTypeDescription
typestring

the model type

urlstring

the url that was requested

Returns:

array of ids

Type: 
Array

getCachedRecord(type, id, queryParams) → {object}

Gets single from store based on cached query

Parameters:
NameTypeDescription
typestring

the model type

idstring

the model id

queryParamsobject

the params to be searched

Returns:

record

Type: 
object

getCachedRecords(type, queryParams, id) → {Array}

Gets records from store based on cached query and any previously requested ids

Parameters:
NameTypeDescription
typestring

type of records to get

queryParamsobject

query params that were used for the query

idstring

optional param if only getting 1 cached record by id

Returns:

array of records

Type: 
Array

getKlass(type) → {function}

Helper to look up model class for type.

Parameters:
NameTypeDescription
typestring

the model type

Returns:

model constructor

Type: 
function

getMany(type, ids, options) → {Array}

Get all records with the given type and ids from the store. This will never fetch from the server.

Parameters:
NameTypeDescription
typestring

the type to get

idsstring

the ids of the records to get

optionsobject

{ queryParams }

Returns:

array of records

Type: 
Array

getOne(type, id, options) → {object}

Gets a record from the store. Will never fetch from the server. If given queryParams, it will check the cache for the record.

Parameters:
NameTypeDescription
typestring

the type to find

idstring

the id of the record to get

optionsobject

{ queryParams }

Returns:

record

Type: 
object

getRecord(type, id) → {object}

Gets individual record from store

Parameters:
NameTypeDescription
typestring

the model type

idnumber

the model id

Returns:

record

Type: 
object

getRecords(type) → {Array}

Gets records for type of collection

Parameters:
NameTypeDescription
typestring

the model type

Returns:

array of objects

Type: 
Array

getRecordsById(type, ids) → {Array}

Get multiple records by id

Parameters:
NameTypeDescription
typestring

the model type

idsArray

the ids to find

Returns:

array or records

Type: 
Array

init(options)

Entry point for configuring the store

Parameters:
NameTypeDescription
optionsobject

passed to constructor

initializeErrorMessages(options)

Configure the error messages returned from the store when API requests fail

Parameters:
NameTypeDescription
optionsobject

for initializing the store options for initializing error messages for different HTTP status codes

initializeModelIndex(models)

Creates the key/value index of model types

Parameters:
NameTypeDescription
modelsobject

a fallback list of models

initializeNetworkConfiguration(options)

Configures the store's network options

Parameters:
NameTypeDescription
optionsstring

the parameters that will be used to set up network requests

Properties
NameTypeDescription
baseUrlstring

the API's root url

defaultFetchOptionsobject

options that will be used when fetching

headersOfInterestArray

an array of headers to watch

retryOptionsobject

options for re-fetch attempts and interval

pickAttributes(properties, type) → {object}

Given a set of properties and type, returns an object with only the properties that are defined as attributes in the model for that type.

properties = { title: 'Do laundry', unrelatedProperty: 'Do nothing' }
pickAttributes(properties, 'todos')
=> { title: 'Do laundry' }
Parameters:
NameTypeDescription
propertiesobject

a full list of properties that may or may not conform

typestring

the model type

Returns:

the scrubbed attributes

Type: 
object

pickRelationships(properties, type) → {object}

Given a set of properties and type, returns an object with only the properties that are defined as relationships in the model for that type.

properties = { notes: [note1, note2], category: cat1, title: 'Fold Laundry' }
pickRelationships(properties, 'todos')
=> {
      notes: {
        data: [{ id: '1', type: 'notes' }, { id: '2', type: 'notes' }]
      },
      category: {
        data: { id: '1', type: 'categories' }
      }
   }
Parameters:
NameTypeDescription
propertiesobject

a full list of properties that may or may not conform

typestring

the model type

Returns:

the scrubbed relationships

Type: 
object

remove(type, id)

Removes a record from the store by deleting it from the type's record map

Parameters:
NameTypeDescription
typestring

the model type

idstring

of record to remove

reset(type)

Clears the store of a given type, or clears all if no type given

store.reset('todos') // removes all todos from store store.reset() // clears store

Parameters:
NameTypeDescription
typestring

the model type

setLoadingState(options) → {object}

Sets a loading state when a fetch / deserialization is in flight. Loading states are Sets inside of the loadingStates Map, so multiple loading states can be in flight at the same time. An optional query tag can be passed to identify the particular query.

const todos = store.fetchAll('todos', { queryTag: 'myTodos' }) store.loadingStates.get('myTodos') => Set([JSON.stringify({ url, type, queryParams, queryTag })])

Parameters:
NameTypeDescription
optionsobject

options that can be used to build the loading state info

Properties
NameTypeDescription
urlstring

the url queried

typestring

the model type

queryParamsstring

the query params used

queryTagstring

an optional tag to use in place of the type

Returns:

the loading state that was added

Type: 
object

updateRecordFromData(record, data)

Updates a record from a jsonapi hash

Parameters:
NameTypeDescription
recordobject

a Model record

dataobject

jsonapi-formatted data

updateRecordsFromResponse(promise, records) → {Promise}

Defines a resolution for an API call that will update a record or set of records with the data returned from the API

Parameters:
NameTypeDescription
promisePromise

a response from the API

recordsobject | Array

to be updated

Returns:

a resolved promise after operations have been performed

Type: 
Promise