Skip to content

Instantly share code, notes, and snippets.

@andywer
Last active July 8, 2016 11:59
Show Gist options
  • Save andywer/ab3270adca0c86411dcebea693751a29 to your computer and use it in GitHub Desktop.
Save andywer/ab3270adca0c86411dcebea693751a29 to your computer and use it in GitHub Desktop.
Resticle usage idea (HATEOAS)
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)
}
/*
* 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
})
}
@andywer
Copy link
Author

andywer commented Jul 7, 2016

Those things come to mind:

  • The previous createModel() seemed more intuitive than api.createModel(), but the model has got to have some connection to the resolver stuff...
  • For write operations on hrefs we still need the middleware logic for "inverse href resolving": Model instance to href

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment