Last active
April 26, 2018 15:56
-
-
Save jamesplease/b9aa9115c26d4930c2770ffd4d527e06 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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] | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
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