Members

QueryString

An object with default parse and stringify functions from qs

addRelatedRecord

Adds a record to a related array and updates the jsonapi reference in the relationships

arrayType

Strips observers and returns a plain JS array

coerceDataToExistingRecord

Takes any object with { id, type } properties and gets an object from the store with that structure. Useful for allowing objects to be serialized in real time, saving overhead, while at the same time always returning an object of the same type.

dateType

Coerces a string or date to a date

defineToManyRelationships

Takes the toMany definitions from a document type and creates getters and setters. A getter finds records from the store, falling back to a lookup of the inverse records if none are defined in the relationships hash.

The setter will unset the previous inverse and set the current inverse. Both return a RelatedRecordsArray, which is an array with added methods add, remove, and replace

A definition will look like this:

categories: { direction: 'toMany', inverse: { name: 'organization', direction: 'toOne' } }

defineToOneRelationships

Takes the toOne definitions from a document type and creates getters and setters. A getter finds a record from the store. The setter calls setRelatedRecord, which will return an instance of a model and add it to the inverse relationship if necessary. A definition will look something like this:

todo: { direction: 'toOne', inverse: { name: 'notes', direction: 'toMany' } }

definitionsByDirection

Gets only the relationships from one direction, ie 'toOne' or 'toMany'

isEmptyString

Returns true if the value is an empty string

mobxAnnotations

Annotations for mobx observability. We can't use makeAutoObservable because we have subclasses.

mobxAnnotations

Annotations for mobx observability. We can't use makeAutoObservable because we have subclasses.

numberType

Coerces a value to a number

objectType

Strips observers and returns a plain JS object

removeRelatedRecord

Removes a record from an array of related records, removing both the object and the reference.

serverResponse

Encodes models into full compliant JSONAPI payload, as if it were being sent with all relevant relationships and inclusions. The resulting payload will look like { data: { id: '1', type: 'zones', attributes: {}, relationships: {}, }, included: [] }

setRelatedRecord

Sets a related record, as well as the inverse. Can also remove the record from a relationship.

stringType

Coerces a value to a string

validatesArray

Returns valid if the value is an array

validatesArrayPresence

Is valid if the array has at least one object

validatesOptions

Valid if target options are not blank

validatesString

Is valid if the value is not an empty string

Methods

addIncluded(store, encodedModel, included, allEncoded)

JSONAPI uses included only at the top level. To recursively add models to this array, we preserve the top-level object and pass it in to the next round Because objects can have multiple relationships, we do a check of the array to make sure it's not already there.

Parameters:
NameTypeDescription
storeobject

the data store

encodedModelobject

the the model

includedArray

data

allEncodedArray

the previously encoded models

circularFetchError(url, options)

Will throw an error if fetch is called from the mockServer, usually due to a POST or PATCH called by a save

Parameters:
NameTypeDescription
urlstring

the url that is attempted

optionsobject

options including the http method

circularFindError(type, id)

Throws an error if MockServer tries to findOne or findAll from itself.

Parameters:
NameTypeDescription
typestring

the model type

idstring

the model id

combineRacedRequests(key, fn) → {Promise}

Avoids making racing requests by blocking a request if an identical one is already in-flight. Blocked requests will be resolved when the initial request resolves by cloning the response.

Parameters:
NameTypeDescription
keystring

the unique key for the request

fnfunction

the function the generates the promise

Returns:

the request

Type: 
Promise

decrementor(key) → {number}

Decreases a counter by 1

Parameters:
NameTypeDescription
keystring

the counter to decreases

Returns:

the current count

Type: 
number

deriveIdQueryStrings(ids, restOfUrl) → {Array.<string>}

Splits an array of ids into a series of strings that can be used to form queries that conform to a max length of URL_MAX_LENGTH. This is to prevent 414 errors.

Parameters:
NameTypeDescription
idsArray

an array of ids that will be used in the string

restOfUrlstring

the additional text URL that will be passed to the server

Returns:

an array of strings of ids

Type: 
Array.<string>

diff(a, b) → {Array.<string>}

deeply compare objects a and b and return object paths for attributes which differ. it is important to note that this comparison is biased toward object a. object a is walked and compared against values in object b. if a property exists in object b, but not in object a, it will not be counted as a difference.

Parameters:
NameTypeDescription
aobject

the first object

bobject

the second object

Returns:

the path to differences

Type: 
Array.<string>

disallowFetches(store)

Overrides store methods that could trigger a fetch to throw errors. MockServer should only provide data for fetches, never call a fetch itself.

Parameters:
NameTypeDescription
storeobject

the internal store

fetchWithRetry(url, fetchOptions, attempts, delay) → {Promise}

Implements a retry in case a fetch fails

Parameters:
NameTypeDescription
urlstring

the request url

fetchOptionsobject

headers etc to use for the request

attemptsnumber

number of attempts to try

delaynumber

time between attempts

Returns:

the fetch

Type: 
Promise

getOneFromFactory(_backendFactoryFarm, factory, type, id) → {object}

Finds or creates a model that will match an id. This is useful for creating a response on the fly if no object already exists

Parameters:
NameTypeDescription
_backendFactoryFarmobject

the private factory farm

factoryobject

the the factory to use

typestring

the model type

idstring

the id to find

Returns:

a Model object

Type: 
object

incrementor(key) → {number}

Increments a counter by 1

Parameters:
NameTypeDescription
keystring

the counter to increment

Returns:

the current count

Type: 
number

isValid(value) → {boolean}

Returns true if the value is truthy

Parameters:
NameTypeDescription
valueany

the value to check

Returns:

true if the value is present

Type: 
boolean

makeDate(value) → {Date}

convert a value into a date, pass Date or Moment instances thru untouched

Parameters:
NameTypeDescription
valueDate | string

a date-like object

Returns:

a date object

Type: 
Date

newId() → {string}

Generates a temporary id to be used for reference in the store

Returns:

a uuidv1 string prefixed with tmp

Type: 
string

parseErrorPointer(error) → {object}

Parses the pointer of the error to retrieve the index of the record the error belongs to and the full path to the attribute which will serve as the key for the error.

If there is no parsed index, then assume the payload was for a single record and default to 0.

ex. error = { detail: "Foo can't be blank", source: { pointer: '/data/1/attributes/options/foo' }, title: 'Invalid foo' }

parsePointer(error)

{ index: 1, key: 'options.foo' }

Parameters:
NameTypeDescription
errorobject

the error object to parse

Returns:

the matching parts of the pointer

Type: 
object

parseErrors(response, errorMessages) → {Array.<object>}

Parses JSONAPI error objects from a fetch response. If the response's body is undefined or is not formatted with a top-level errors key containing an array of errors, it builds a JSONAPI error object from the response status and a errorMessages configuration.

Errors that are returned which contain a status also have their detail overridden with values from this configuration.

Parameters:
NameTypeDescription
responseobject

a fetch response

errorMessagesobject

store configuration of error messages corresponding to HTTP status codes

Returns:

An array of JSONAPI errors

Type: 
Array.<object>

requestUrl(baseUrl, endpoint, queryParams, id) → {string}

Build request url from base url, endpoint, query params, and ids.

Parameters:
NameTypeDescription
baseUrlstring

the base url

endpointstring

the endpoint of the url

queryParamsobject

query params to add

idstring

the id of the the model

Returns:

formatted url string

Type: 
string

simulatePatch(store, type, body) → {object|Array}

Interpret a PATCH request

Parameters:
NameTypeDescription
storeobject

the store

typestring

the type

bodystring

json encoded response body

Returns:

a model or array created from the response

Type: 
object | Array

simulatePost(store, type, body) → {object|Array}

Interpret a POST request

Parameters:
NameTypeDescription
storeobject

the store

typestring

the type

bodystring

json encoded response body

Returns:

a model or array created from the response

Type: 
object | Array

stringifyIds(object)

Coerces all ids to strings

Parameters:
NameTypeDescription
objectobject

object to coerce

toFullJsonapi(model) → {object}

Encodes a model to a jsonapi document with all relationships

Parameters:
NameTypeDescription
modelobject

the model to convert

Returns:

the jsonapi encoded document

Type: 
object

validatePresence() → {object}

returns true as long as the value is not null, undefined, or ''

Returns:

a validation object

Type: 
object

validateProperties(model, propertyNames, propertyDefinitions) → {Array}

Maps the passed-in property names through and runs validations against those properties

Parameters:
NameTypeDescription
modelobject

the model to check

propertyNamesArray

the names of the model properties to check

propertyDefinitionsobject

a hash map containing validators by property

Returns:

an array of booleans representing results of validations

Type: 
Array

walk(obj, iteratee, prefix) → {Array}

recursively walk an object and call the iteratee function for each property. returns an array of results of calls to the iteratee.

Parameters:
NameTypeDescription
objobject

the object to analyze

iterateefunction

the iterator to use

prefixstring

the prefix

Returns:

the result of iteratee calls

Type: 
Array

wrapResponse(response, method, status) → {Promise}

Wraps response JSON or object in a Response object that is itself wrapped in a resolved Promise. If no status is given then it will fill in a default based on the method.

Parameters:
NameTypeDescription
responsestring

JSON string

methodstring

the http method

statusnumber

the http status

Returns:

a promise wrapping the response

Type: 
Promise