Giter VIP home page Giter VIP logo

node-ddp-client's Introduction

Node DDP Client

A callback style DDP (Meteor's Distributed Data Protocol) node client, originally based

The client implements version 1 of DDP, as well as fallbacks to pre1 and pre2.

Installation

$ npm install ddp-client

Authentication

Built-in authentication support was removed in ddp 0.7.0 due to changes in Meteor version 0.8.2.

One can authenticate using plain-text logins as follows:

// logging in with e-mail
ddpclient.call("login", [
  { user : { email : "[email protected]" }, password : "password" }
], function (err, result) { ... });

// logging in with username
ddpclient.call("login", [
  { user : { username : "username" }, password : "password" }
], function (err, result) { ... });
var DDPClient = require("ddp-client");

var ddpclient = new DDPClient({
  // All properties optional, defaults shown
  host : "localhost",
  port : 3000,
  ssl  : false,
  autoReconnect : true,
  autoReconnectTimer : 500,
  maintainCollections : true,
  ddpVersion : '1',  // ['1', 'pre2', 'pre1'] available
  // Use a full url instead of a set of `host`, `port` and `ssl`
  url: 'wss://example.com/websocket'
  socketConstructor: WebSocket // Another constructor to create new WebSockets
});

/*
 * Connect to the Meteor Server
 */
ddpclient.connect(function(error, wasReconnect) {
  // If autoReconnect is true, this callback will be invoked each time
  // a server connection is re-established
  if (error) {
    console.log('DDP connection error!');
    return;
  }

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

  console.log('connected!');

  setTimeout(function () {
    /*
     * Call a Meteor Method
     */
    ddpclient.call(
      'deletePosts',             // name of Meteor Method being called
      ['foo', 'bar'],            // parameters to send to Meteor Method
      function (err, result) {   // callback which returns the method call results
        console.log('called function, result: ' + result);
      },
      function () {              // callback which fires when server has finished
        console.log('updated');  // sending any updated documents as a result of
        console.log(ddpclient.collections.posts);  // calling this method
      }
    );
  }, 3000);

  /*
   * Call a Meteor Method while passing in a random seed.
   * Added in DDP pre2, the random seed will be used on the server to generate
   * repeatable IDs. This allows the same id to be generated on the client and server
   */
  var Random = require("ddp-random"),
      random = Random.createWithSeeds("randomSeed");  // seed an id generator

  ddpclient.callWithRandomSeed(
    'createPost',              // name of Meteor Method being called
    [{ _id : random.id(),      // generate the id on the client
      body : "asdf" }],
    "randomSeed",              // pass the same seed to the server
    function (err, result) {   // callback which returns the method call results
      console.log('called function, result: ' + result);
    },
    function () {              // callback which fires when server has finished
      console.log('updated');  // sending any updated documents as a result of
      console.log(ddpclient.collections.posts);  // calling this method
    }
  );

  /*
   * Subscribe to a Meteor Collection
   */
  ddpclient.subscribe(
    'posts',                  // name of Meteor Publish function to subscribe to
    [],                       // any parameters used by the Publish function
    function () {             // callback when the subscription is complete
      console.log('posts complete:');
      console.log(ddpclient.collections.posts);
    }
  );

  /*
   * Observe a collection.
   */
  var observer = ddpclient.observe("posts");
  observer.added = function(id) {
    console.log("[ADDED] to " + observer.name + ":  " + id);
  };
  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);
  };
  observer.removed = function(id, oldValue) {
    console.log("[REMOVED] in " + observer.name + ":  " + id);
    console.log("[REMOVED] previous value: ", oldValue);
  };
  setTimeout(function() { observer.stop() }, 6000);
});

/*
 * Useful for debugging and learning the ddp protocol
 */
ddpclient.on('message', function (msg) {
  console.log("ddp message: " + msg);
});

/*
 * Close the ddp connection. This will close the socket, removing it
 * from the event-loop, allowing your application to terminate gracefully
 */
ddpclient.close();

/*
 * If you need to do something specific on close or errors.
 * You can also disable autoReconnect and
 * call ddpclient.connect() when you are ready to re-connect.
*/
ddpclient.on('socket-close', function(code, message) {
  console.log("Close: %s %s", code, message);
});

ddpclient.on('socket-error', function(error) {
  console.log("Error: %j", error);
});

/*
 * You can access the EJSON object used by ddp.
 */
var oid = new ddpclient.EJSON.ObjectID();

Unimplemented Features

The node DDP client does not implement ordered collections, something that while in the DDP spec has not been implemented in Meteor yet.

Thanks

Inspired by https://github.com/oortcloud/node-ddp-client

  • Tom Coleman (@tmeasday)
  • Thomas Sarlandie (@sarfata)
  • Mason Gravitt (@emgee3)
  • Mike Bannister (@possiblities)
  • Chris Mather (@eventedmind)
  • James Gill (@jagill)
  • Vaughn Iverson (@vsivsi)

node-ddp-client's People

Contributors

hharnisc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-ddp-client's Issues

ddp.on not working

ddpclient.on('added',function () {
console.log("ddp added");
});
It is not printing ddp added .

Error with connect function in React Native v0.10.1

I keep getting this error in react native 0.10.1

screen shot 2015-09-02 at 1 21 55 am

I've figured out that it's being caused by ddpClient.connect():

 ddpClient.connect((error, wasReconnect) => {

            // If autoReconnect is true, this callback will be invoked each time
            // a server connection is re-established

            if (error) {
                console.log('DDP connection error!');
                return;
            }

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

            ddpClient.call('Accounts.getUsers', [], function (err, resp) {
                if (resp) {
                    _this.setState({resp});
                }

                if (err) console.log(err);
            });

        });

could you explain why this is occurring?

DDP client with file upload is showing error

I am trying to upload file through ddp client connection. In that iam download a packages from node-ddp-client .connections and send and retrive text message is working fine. But iam trying to upload a file with options like

{
    "msg": "method",
    "method": "slingshot/uploadRequest",
    "id": "42",
    "params": [
        "rocketchat-uploads", 
        {
            "name": _"https://domain.com/aws_logo._V400518270_.png",
            "size": 15664,
            "type": "image/png"
        },
        { "rid": "room-id" }
    ]
}

I am calling functions like

ddpclient.call(
"slingshot/uploadRequest",
[
        "rocketchat-uploads", 
        {
            "name": "https://domain.com/aws_logo._V400518270_.png",
            "size": 430.8,
            "type": "image/png"
        },
        { "rid": "GENERAL" }
    ],function(err,result){
      console.log(err);
      console.log(result);
    },function(ucb){
        console.log("ucb");
    });

in client side shows the error

{ error: 'Invalid directive',
  reason: 'The directive rocketchat-uploads does not seem to exist',
  message: 'The directive rocketchat-uploads does not seem to exist [Invalid directive]',
  errorType: 'Meteor.Error' }


What is the problem and where i change my code. ?
Please help...!!!

Logging in with google

Hey, first off, really great work! I really appreciate all that you've done to get ddp working with react-native.

How would you suggest handling logging in with google via ddp? I used to do this via asteroid but it seems as though the asteroid library is not compatible with react-native.

Login flow

Hi, implementation question!

I have the client logging correctly and authenticating fine, but i'm not sure of how to manage the session. I can see that a token is returned during the login process, but i don't know what to do with it.

Is there any inbuilt token management, or do i need to store the token between sessions and refresh it when needed? How do i pass the token back to the application on launch?

Thanks

Gareth

DDP Can't Reconnect

after successful connection in between it loss the connection object then cant reconnect. how i will handle this issue and idea ?

error throws - the subscriber of subscription is incorrectly set.

Changing a subscription

Hello,

I have a question: let's say I am subscribing and observing a collection that was based on a certain query with parameters .find({parameters}).

If I change my parameters, how can I refresh the subscription with the new parameters other than by unsubscribing/subscribing again?

Thanks so much!

How to browserify your library.

I tried browserifying your library to use it on the client side but it fails due to syntax error with class keyword. Any clue as to how can i go about browserifying your library.

Thanks in advance.

Collection Observer

after subscribing the collection the when we register a observer it says "underfined is not a functiuon"
ios simulator screen shot 17-sep-2015 2 45 10 pm

Not ECMAScript 2015 Compliant

Not super familiar with the new standard yet but I'm building a react native app and am using your package to talk to the Meteor server.

Running into the following error after upgrading to verision 0.6.0 of react-native.

node_modules/ddp-client/index.js: Line 9: 'this' is not allowed before super().

Related spec: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

Repo that shows problem: https://github.com/spencercarli/ddp-client-breaking

Happy to take a stab at this, just not exactly sure what to do.

logout

Hello, Thanks for this library first of all,
is there any way to logout the current connected user ?

Multiple subscriptions/switching subscriptions.

So i have a single page react native application where i am trying to load multiple publications of the same collection. Each publication is filtered to a sub-set of the collection.

However as i am only able to subscribe to notifications of changes to the collection via DDP-Client rather than the subscription i have no way of feeding only that publications data through as my datasource to my scroll view.

The other method i have taken is to send a filter through as part of the subscription and reload the subscription when i want to show alternative data. Unfortunately this also doesn't seem to work, the existing subscription doesn't seem to get cleared when i recall the same subscription with a different filter parameter.

So, before i start doing some nasty client side filtering is there a way of doing this that i'm missing?

Help much appreciated!

Thanks

Gareth

Provide an example for "DDP Client for browsers"

Can you describe the steps required to use the "DDP Client for browsers" in a HTML file?

<html>
  <head>
    <script src="???"></script>
    <script>

      var ddpclient = new DDPClient({
        host : "localhost",
        port : 3000,
        ssl  : false,
        autoReconnect : true,
        autoReconnectTimer : 500,
        maintainCollections : true,
        ddpVersion : '1',
        socketConstructor: WebSocket
      });

      ddpclient.subscribe(...);

      ddpclient.on('message', function (msg) {
        console.log("ddp message: " + msg);
      });

    </script>
  </head>
  <body>
    <p>Check the console log for DDP messages</p>
  </body>
</html>

Observer functions not getting triggered

The observers are created and the change is also called in the index.js file. Only the functions attached to the observer.change and added are never called. My client looks like this:

var DDPClient = require('ddp-client');
var ddpclient = new DDPClient({
    host : '127.0.0.1',
    port : 3000,
});

/* Connect to the Meteor Server*/
ddpclient.connect(function (error, wasReconnect) {
    if (error) {
        console.log('DDP connection error!');
        return;
    }

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

    console.log('connected!');
    /* Subscribe to a Meteor Collection */
    ddpclient.subscribe('sensorvalues', [], function() {
        console.log(ddpclient.collections.sensorvalues);
    });

    /* Observe a collection */
    var observer = ddpclient.observe('sensorvalues');
    observer.added = function(id) {
        console.log("[ADDED] to " + observer.name + ":  " + id);
    };
    observer.changed = function(id, oldFields, clearedFields, newFields) {
        if (id == 0) {
            document.getElementById('date').textContent = newFields.value
        }
        if (id == 1) {
            document.getElementById('ping').textContent = newFields.value
        }
        if (id == 2) {
            document.getElementById('cpu').textContent = newFields.value
        }
        if (id == 3) {
            document.getElementById('clicks').textContent = newFields.value
        }
    };

    /* Send a remote procedure call */
    document.getElementById('addclick').addEventListener('click', function() {
        ddpclient.call('click');
    });
});

Beside this I did a check on the message event and this one was triggered.


Update about the used browsers. All on OSX 10.10.5.

  • Chrome Version 45.0.2454.99 (64-bit)
  • Chrome Version 47.0.2519.0 canary (64-bit)
  • Firefox 40.0.3 & 41.0

How to stop a subscription?

I don't see a way to stop a subscription after it has been initiated.

Am I suppose to close the connection every time I want to stop the subscriptions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.