Skip to content

Instantly share code, notes, and snippets.

@bfitch
Created August 9, 2016 17:01
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 bfitch/6210ef18e98afa284b769a98bd3031c2 to your computer and use it in GitHub Desktop.
Save bfitch/6210ef18e98afa284b769a98bd3031c2 to your computer and use it in GitHub Desktop.
Caching HTTP requests with Factories

Caching HTTP requests with Factories

Just sketching out some scenarios and how we would handle them with the tools we have in cerebral today (factories and actions).

State store:

Model({
  messages: [
    {id: 1, body: 'cool', isNew: false},
    {id: 2, body: 'cool', isNew: true}
  ]
})

1 - Fetching an collection (HTTP GET /messages)

when(not('state:messages')), {
  true: [
    ({services}) => {
      services.http.get('http://myapp.com/api/messages')
        .then(data => output({data}))
        .catch(error => output({error})
    }, {
      error: [/*handle error*/]
    },
    copy('input:data', 'state:messages')
  ],
  false: [/*noop*/]
}

2 - Fetching a single object (HTTP GET messages/:id)

when(
  not(({input, state}) => {
    return state.findWhere('messages', {id: input.id});
  })
), {
  true: [
    ({input, services}) => {
      services.http.get(`http://myapp.com/api/messages/${input.id}`)
        .then(data => output({data}))
        .catch(error => output({error})
    }, {
      error: [/*handle error*/]
    },
    push('input:data', 'state:messages')
  ],
  false: [/*noop*/]
}

3 - Dynamic inputs with data stored by key

when(({input, state}) => {
    return !state.get(`messages${input.id}`);
  })
), {
  true: [
    ({input, services}) => {
      services.http.get(`http://myapp.com/api/messages/${input.id}`)
        .then(data => output({data}))
        .catch(error => output({error})
    }, {
      error: [/*handle error*/]
    },
    push('input:data', 'state:messages')
  ],
  false: [/*noop*/]
}

Given these scenarios, can we create some factories (or expand them) to handle these cases "elegantly"?

I think solving this in a Cerebral way would be extremely cool and valuable. No other framework other than Ember gives you data caching "out of the box" and it would be such a simple solution compared to rest-store or a complex data layer or library. :)

So, can we build on what we have?!?!

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