symmetric-js
v1.0.15
Published
Symmetric provides observable model and collection classes with support for field specifications that mirror backend sources with encoding functions and validation rules.
Downloads
7
Maintainers
Readme
About
Symmetric provides observable model and collection classes with support for field specifications that mirror backend sources with encoding functions and validation rules.
Requirements
The built-in sync function requires a fetch compatible function on window/self/ or global.
- https://github.com/github/fetch
- https://github.com/bitinn/node-fetch
- https://github.com/matthew-andrews/isomorphic-fetch
NOTE: When using create-react-app, fetch is already included. No need to add an additional dependency.
Configuration
autoValidate
- auto validate model rules after X ms from a change - use -1 (default) to disable or 0 to run immediateencoders
- dictionary of encoding (converting to a string) functions keyed by typesdecoders
- dictionary of decoding (converting from a string) functions keyed by typesinputEncodings
- dictionary of field types that are be used ONLY with encoding/decoding user inputformats
- dictionary of field types to RegExp objects or functions that return a booleanformatErrorMessage
- function to format errorsbatch
- function to convert an array of fetch init objects into a single batched fetch initunbatch
- function to convert a single Response object to many Response objectssync
- function that wraps the call tofetch()
syncConfig
- additional settings for the built-in sync function, see sync below
sync function
Basic options are:
url
- required url to fetchparams
- will be added to url as query string argsdata
- will set body withJSON.stringify(data)
andContent-Type
toapplication/json
auth
- any authorization object that implements aprepare(request, opts)
functionmeta
- provide an object here to receive withmeta.set(key, value)
theLink
andX-Headers
from the response as well as any meta data from unwrapping
Standard fetch options are:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
method
- defaults to 'GET'headers
- a dictionary of http headers to use, if setting 'Content-Type' note it is case-sensitive to avoid conflictsbody
- the body of the requestmode
- defaults to 'same-origin'credentials
- defaults to 'same-origin'cache
- defaults to 'no-cache'redirect
- defaults to 'follow'
Additional options with defaults provided by config.syncConfig
are:
syncCamelCase
- converts responses to camelCase keys before parsing. defaults to truesaveSnakeCase
- defaults to truequerySnakeCase
- defaults to truesaveEncoding
- one of the following stringsjson
,form
, orform-json
, defaults tojson
saveArrayName
- whensaveEncoding
isform
orform-json
, the form name to use when data is just an arraycsrfCookieName
- defaults tocsrftoken
csrfHeaderName
- defaults toX-CSRFToken
requestedWith
- value of theX-Requested-With
header, defaults toXMLHttpRequest
batchTimeout
- will queue requests that happen within this timeframe into a single request, -1 (default) to disable or >= 0 to enablebatchUrl
- the backend url that accepts batched requestsauth
- an optional single auth object to use for all sync operations, defaults to nullunwrap
- function to unwrap and enveloped response and return the extracted dataunwrap(data, meta) => unwrapped
, defaults to nullerrorFactory
- receives a Response object and should return or eventually resolve to rejected PromiseerrorHandler
- a callback to globally handle errors before they are thrown to the next Promise rejection handler
Subclassing
Model
toJSON()
- return data for JSON stringification. The base method will encode each fielddefaults()
- return an object of default values for the fields when creating a new instancefield(key)
- return the field specification for the given attribute keyurl(options, operation)
- return the url to use with the fetch, save, or deleteparse(data)
- The base method will decode all fields that are a string and have an encoding type
Collection
The following methods should be implemented on subclasses:
model(attrs)
- return a model class used to construct with the given attributesurl(options, operation)
- return the url to use with the fetch or saveparse(data)
- parse raw data from a fetch. The base method converts each item into models using themodel()
method.
Parsing
The base behavior of the parse()
method on the model class is to decode any string values that have a specified encoding. The base behavior of the parse()
method on the collection class is to pass each item in the data array to a model class constructor and create model instances inside the returned array. This is where the model()
method is used.
When subclassing and providing custom parsing it is a good idea to call the base method and use the data it returns.
Field Specifications
Each field can specify one or more of the following:
choices
- an array of valid choices the value must matchencoding
- type of encoding to use, keys will match up to configencoders
anddecoders
rule
- the validation rule, see belowtitle
- title of an input for this fieldsubtitle
- subtitle of an input for this fieldinstructions
- string of instructions to present to the user for how to enter a value. Will be returned byformatErrorMessage()
if set
Validation Rules
Each rule is a dictionary with one or more of the following:
required
- if true, then the value may not be null or an empty stringtype
- checks to make sure that the value is properly decoded as this typeformat
- key into config formats to choose a RegExp or function to checkequals
- value should exactly equal this or if an array match one of the valuesmin
- values needs to pass a > test with this or the length must be longer than this if a stringmax
- values needs to pass a < test with this or the length must be less than this if a string
Serialization
serialize
and deserialize
Functions are provided to make it easier for storing and retrieving already loaded models and collections to and from local or session storage.
License
MIT