A lightweight layer for working with JSON:API data.
npm install json-api-models --save
import{Store}from'json-api-models';constmodels=newStore();// Sync a JSON:API response document to the storemodels.sync({data: {type: 'users',id: '1',attributes: {name: 'Toby'},relationships: {pet: {data: {type: 'dogs',id: '1'}},},},included: [{type: 'dogs',id: '1',attributes: {name: 'Rosie'},},],});// Resource data is transformed into easy-to-consume modelsconstuser=models.find('users','1');user.name;// Tobyuser.pet;// { type: 'dogs', id: '1', name: 'Rosie' }Use the sync method to load your JSON:API response document into the store. Both the primary data and any included
resources will be synced. The return value will be a model, or an array of models, corresponding to the primary data.
constmodel=models.sync(document);If any of the synced resources already exist within the store, the new data will be merged into the old model. The model instance will not change so references to it throughout your application will remain intact.
You can also sync an individual resource using the syncResource method:
constmodel=models.syncResource({type: 'users',id: '1',attributes: {name: 'Toby'},});Specific models can be retrieved from the store using the find method. Pass it a type and an ID, a resource identifier
object, or an array of resource identifier objects:
constuser=models.find('users','1');constuser=models.find({type: 'users',id: '1'});constusers=models.find([{type: 'users',id: '1'},{type: 'users',id: '2'},]);Retrieve all of the models of a given type using the findAll method:
constusers=models.findAll('users');Models are a superset of JSON:API resource objects, meaning they contain all of the members you would
expect (type, id, attributes, relationships, meta, links) plus some additional functionality.
Getters are automatically defined for all fields, allowing you to easily access their contents. Relationship fields are automatically resolved to their related models (if present within the store):
model.name;// => model.attributes.namemodel.pet;// => models.find(model.relationships.pet.data)To easily retrieve a resource identifier object for the model, the identifier method is available. This is useful when
constructing relationships in JSON:API request documents.
model.identifier();// { type: 'users', id: '1' }Remove a model from the store using the forget method, which accepts a resource identifier object. This means you can
pass a model directly into it:
models.forget(user);You can define custom model classes to add your own functionality. Custom models must extend the Model base class.
This is useful if you wish to add any custom getters or methods to models for a specific resource type:
import{Model}from'json-api-models';classUserextendsModel{getfirstName(){returnthis.name.split(' ')[0];}}Register your custom models with the store during construction:
constmodels=newStore({users: User,});For TypeScript autocompletion of model attributes and relationships, provide the raw JSON:API resource schema when defining your models.
typeUsersSchema={type: 'users';id: string;attributes: {name: string;};relationships: {dog: {data?: {type: 'dogs';id: string}|null};};};classUserextendsModel<UsersSchema>{}To type related resources, you can provide a collection of all models as the second generic.
typeDogsSchema={// ...};typeSchemas={users: User;dogs: Dog;};classUserextendsModel<UsersSchema,Schemas>{}classDogextendsModel<DogsSchema,Schemas>{}This library is completely unopinionated about how you interact with your JSON:API server. It merely gives you an easy
way to work with the resulting JSON:API data. An example integration with fetch is demonstrated below:
constmodels=newStore();functionapi(url,options={}){options.headers=options.headers||{};options.headers['Accept']='application/vnd.api+json';if(options.body){options.body=JSON.stringify(options.body);options.headers['Content-Type']='application/vnd.api+json';}returnfetch('http://example.org/api/'+url,options).then(async(response)=>{if(response.status===204){return{ response };}else{constdocument=awaitresponse.json();constdata=models.sync(document);return{ response, document, data };}},);}api('users/1').then(({ data })=>{console.log(data.name);});When constructing API requests, remember that JSON:API resource objects contain links that can be used instead of
rebuilding the URL. Also, models contain an identifier method that can be used to spread the type and id members
into the document data (required by the specification). Here is an example of a request to update a resource:
constuser=models.find('users','1');api(user.links.self,{method: 'PATCH',body: {data: {
...user.identifier(),attributes: {name: 'Changed'},},},});Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.