Skip to content

Instantly share code, notes, and snippets.

@jamesplease
Last active April 26, 2018 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesplease/b9aa9115c26d4930c2770ffd4d527e06 to your computer and use it in GitHub Desktop.
Save jamesplease/b9aa9115c26d4930c2770ffd4d527e06 to your computer and use it in GitHub Desktop.
// Define some schemas
const schemas = {
books: booksSchema,
authors: authorsSchema
};
// Set an initial state
const initialState = {
books: {
resources: {
4: { ... },
10: { ... }
},
lists: {
newBooks: [ ... ]
}
}
};
// Create a store. Schema and initial state is validated...
const store = createResourceStore(schemas, initialState);
store.subscribe((state) => {
// Sync to Redux or to context
});
// Retrieve some of the resources
const someBooks = store.getResources('books', [4], {
// Include related resources (one-level deep)
relationships: true
});
// Update a list
store.updateResources({
books: {
lists: {
newBooks: [2, 10, 50]
}
}
});
// Upsert resources with type-checking
store.updateResources({
books: {
resources: {
1: { ... }
}
}
});
// Delete a resource
store.deleteResources({
books: {
resources: [1]
}
});
{
resourceType: 'books',
// Defaults to "id", but you can use any attribute on the resource
// as the ID.
idAttribute: 'bookId',
// Validate the type of the ID. Useful for our backends that return
// numbers and strings for movie IDs.
idType: PropTypes.number,
// Things that are computed on the resource as it changes
computedAttributes: {
// These can be simple functions...
displayString(resource) {
return resource.firstName + resource.lastName;
}
complicatedValue = createSelector(
(resource) => fastFn(resource),
(stuff) => slowFn(stuff)
)
},
attributes: {
firstName: PropTypes.string,
lastName: PropTypes.string,
publishYear: PropTypes.number,
chapters: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
number: PropTypes.number
})
)
},
meta: {
isSelected: PropTypes.bool
},
relationships: {
author: {
resourceType: 'people',
singular: true
},
contracts: {
resourceType: 'contracts',
singular: false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment