Skip to content

Instantly share code, notes, and snippets.

@andywer
Created July 8, 2016 09:57
Show Gist options
  • Save andywer/90316897a0c3a6b5e0a1dc87506b9e1e to your computer and use it in GitHub Desktop.
Save andywer/90316897a0c3a6b5e0a1dc87506b9e1e to your computer and use it in GitHub Desktop.
Resticle idea: Additional gimmicks
import { createApi, Schema } from 'resticle'
const api = createApi('/api')
// Don't Repeat Yourself: Small middleware function to automatically provide `created_at` and `updated_at` timestamps
api.use(function timestampsMiddleware (api) {
api.extendModels((model, schema) => {
// Extend schema if timestamps are not already defined
schema.created_at = schema.created_at || Schema.Date()
schema.updated_at = schema.updated_at || Schema.Date()
})
})
const User = api.createModel('user', {
// we don't specify `email`, `id` or other common fields here, you can just use them out-of-the-box
lastLogin: Schema.Date(),
blogUrl: Schema.Href()
})
fetchUser()
async function fetchUser () {
const user = await User.fetch(123)
console.log(`Thanks to Schema.Date() resticle is now able to transparently construct a Date object out of the timestamp sent by server:`)
console.log(user.lastLogin, typeof user.lastLogin)
}
@andywer
Copy link
Author

andywer commented Jul 8, 2016

Hint: Resticle is able to construct the request href automatically when doing User.fetch(123) by using {api.href}/{model.namePlural}/{id} by default. model.namePlural is {model.name}s by default.

Idea: Provide different plural name like this: api.createModel('man|men')

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