oortcloud / node-ddp-client

A callback style DDP (Meteor's Distributed Data Protocol) node client.
Other
263 stars 80 forks source link

Initial added not being detected? #67

Closed rclai closed 9 years ago

rclai commented 9 years ago

I have the following code on a vanilla node client:

var DDPClient = require("ddp");

var ddpclient = new DDPClient({
  // All properties optional, defaults shown 
  host: "localhost",
  port: 3000,
  ssl: false,
  autoReconnect: true,
  autoReconnectTimer: 500,
  maintainCollections: true,
  ddpVersion: '1',
  useSockJs: true
});

ddpclient.connect(function(error, wasReconnect) {
  if (error) {
    console.log('DDP connection error!');
    return;
  }

  if (wasReconnect) {
    console.log('Reestablishment of a connection.');
  }

  console.log('Connected!');

  ddpclient.subscribe(
    'test', [],
    function() {
      console.log('Subscribed to `test`');

      var observer = ddpclient.observe("test");
      observer.added = function(id, doc) {
        console.log("[ADDED] to", observer.name, ":", id, 'doc:', doc);
      };
      observer.changed = function(id, oldFields, clearedFields, newFields) {
        console.log("[CHANGED] in", observer.name,":", id);
        console.log("[CHANGED] old field values:", oldFields);
        console.log("[CHANGED] cleared fields:", clearedFields);
        console.log("[CHANGED] new fields:", newFields);
      };
    }
  );
});

And I have a meteor server with this publication:

Meteor.publish('test', function() {
  this.added('test', 'testId', { num: Math.random() });
  this.ready();
});

When I start up the node client, this is my console output:

Connected!
Subscribed to `test`

However, once I start triggering a bunch of changed items, they do start coming in:

Meteor.publish('test', function() {
  const id = 'test';

  this.added('test', id, { num: Math.random() });

  let handle = Meteor.setInterval(() => {
    this.changed('test', id, { num: Math.random() });
  }, 1000);

  this.ready();

  this.onStop(() => {
    Meteor.clearInterval(handle);
  });
});

Console output:

Connected!
Subscribed to `test`
[CHANGED] in test : test
[CHANGED] old field values: { num: 0.945352595532313 }
[CHANGED] cleared fields: []
[CHANGED] new fields: { num: 0.13286670367233455 }
[CHANGED] in test : test
[CHANGED] old field values: { num: 0.13286670367233455 }
[CHANGED] cleared fields: []
[CHANGED] new fields: { num: 0.5646781949326396 }
...
...
rclai commented 9 years ago

Oh wait, what am I thinking? That's how it's supposed to work.

I'm supposed to get my initial set by doing ddpclient.collections.test.

rclai commented 8 years ago

Actually, if I wanted my observers to get the initial set of documents, I should've set up the observers outside the .connect.