A lightweight layer for working with JSON:API data.
npm install json-api-models --save
import { Store } from 'json-api-models';
const models = new Store();
// Sync a JSON:API response document to the store
models.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 models
const user = models.find('users', '1');
user.name; // Toby
user.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.
const model = 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:
const model = 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:
const user = models.find('users', '1');
const user = models.find({ type: 'users', id: '1' });
const users = models.find([
{ type: 'users', id: '1' },
{ type: 'users', id: '2' },
]);Retrieve all of the models of a given type using the findAll method:
const users = models.findAll(