Best way toto query records that is pushed into store in realtime . (can't do with this.store.find() )


#1

my goals

  • Push records to store when event source recives data
  • Query the records , to filter them live.
  • Display in realtime.

here is my EventSource service:

import Ember from 'ember';
import ENV from '../config/environment';
if (ENV.environment === 'development') {
  var host = ENV.localHost
} else if (ENV.environment === 'production') {
  var host = ENV.remoteHost
}
export default Ember.Service.extend({
  store: Ember.inject.service('store'),
  unbind: null,
  subscribe(url, fn) {
    var source = new EventSource(url);
    source.onmessage = function(e) {
      fn(e.data);
    };
    source.onerror = function(e) {
      if (source.readyState == EventSource.CLOSED) return;
      console.error(e);
    };
    return source.close.bind(source);
  },
  start(question_path) {

    this.set("unbind", this.subscribe(`${host}/${question_path}`, (data) => {
        console.log(data)
      this.get('store').pushPayload({"chat": JSON.parse(data)})
    }))
  },
  stop(){
      var unbind= this.get("unbind")
      if (unbind){
          unbind()
      }

  }

});

route:

import Ember from 'ember';
import FBLoginStatus from '../mixins/route/fb-login-status';
export default Ember.Route.extend(FBLoginStatus, {
  messaging: Ember.inject.service("messagebus"),
  states: Ember.inject.service(),
  queryParams: {
    question_id: {
      refreshModel: true
    }
  },
  model(params) {
    const rnd = Math.round(Math.random() * 100000)
    console.log(params)
    var chat = this.get('messaging')
    // chat.set("unbind",null)
    chat.stop()
    chat.start('updatechats/' + params.question_id);
    // this.controller.set("")

    // console.log(this);
    return this.store.query("chat",params);
    //return this.store.findAll('chat')
  }
});

model

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
  message: attr('string'),
  question_id: attr('string'),
  stamp: attr('date', {
    defaultValue() { return new Date(); }
  }),
  user: attr('string'),
  userid: attr('string'),
  type: attr('string')
});

what i am trying to do is , a chatroom where channels are quried via question_id . return this.store.find("chat",params.question_id);

but by design of ember-data , this.store.find is not a live array.

How to do it in correct way since store.filter is deprecated . All i need to do is to make this.store.find("chat",params.question_id); return data as pushed via this.get('store').pushPayload({"chat": JSON.parse(data)})

in real time.


#2

peekAll is live so you could use that to get all of the current records, then use a computed property to get only those that have the correct question_id. Any new records you fetch will automatically get added to the peekAll array.