Last active
July 8, 2016 11:59
-
-
Save andywer/ab3270adca0c86411dcebea693751a29 to your computer and use it in GitHub Desktop.
Resticle usage idea (HATEOAS)
This file contains 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
import { createApi, Schema } from 'resticle' | |
import { githubHrefResolver } from './middlewares.js' | |
const api = createApi() | |
api.use(githubResolver) | |
const Repo = api.createModel('repo') | |
const User = api.createModel('user', { | |
repos: Schema.Collection(Repo) | |
}) | |
doStuff() | |
async function doStuff () { | |
const user = await User.fetch('https://api.github.com/users/octocat') | |
const repos = await user.repos() | |
console.log(`${user.name} has got ${repos.length} repositories on GitHub:`, repos.map((repo) => repo.full_name).join(', ')) | |
console.log(`Also keep in mind that all model instances actually own exactly the same properties as the pure data without model prototype:`, user) | |
} |
This file contains 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
/* | |
* Resolves REST response data like { abc: 'xyz', ..., foo_url: 'https://some/href' } | |
* to a mapping of { <property>: <href> } like { foo: 'https://some/href' } | |
* => so resticle may set up magic getters for linked resources resolving to proper model instances | |
* @example https://api.github.com/users/octocat | |
*/ | |
export function githubHrefResolver (api) { | |
api.useResolver((data) => { | |
const hrefPropNames = Object.keys(data).filter((propName) => propName.match(/.+_href$/)) | |
const resolved = {} | |
hrefPropNames.forEach((propName) => { | |
const rel = propName.replace(/_href$/, '') | |
const href = data[ propName ] | |
resolved[ rel ] = href | |
}) | |
return resolved | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Those things come to mind:
createModel()
seemed more intuitive thanapi.createModel()
, but the model has got to have some connection to the resolver stuff...