beauby / jsonapi-datastore

JavaScript client-side JSON API data handling made easy.
MIT License
195 stars 40 forks source link

Add new function to get a firstOrDefault #24

Closed spwizard closed 8 years ago

spwizard commented 8 years ago

Hi, I am currently using the datastore, and have ran into an issue when trying to sort my login flow.

The api returns a user object which gets stored in the store. However I need to use this in various places in my app, and the only way i can see to access this is to use find('users' , 'xx') but I don't know what the id is. I could store the id on the $rootscope or in some other service but that doses't feel right. The other option is i could add this method

{ key: "firstOrDefault", value: function firstOrDefault(type) { if (!this.graph[type]) return null; return this.graph[type]; } Example usage var user = store.firstOrDefault('users');

Would appreciate if you have any other suggestions how i might handle this.

Rob

beauby commented 8 years ago

In your case I'd suggest holding a reference to the user object, that I would encapsulate inside a service/factory (as it seems you're using angular). So something like

angular.module('myCoolApp').factory('authenticationService', function(dataService) {
  var user = null;

  return {
    login: function() {
      // do stuff
      var payload = authenticate(); // basically, get the response from the server for your authentication
      user = dataService.syncRecord(payload);
      // do stuff
    }
  };
});
beauby commented 8 years ago

Closing this for now, feel free to keep commenting/reopen if needed.