Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

asteroid

mondora1.4kMIT2.0.3

Alternative Meteor client

ddp, asteroid, meteor

readme

npm version Build Status Coverage Status Dependency Status devDependency Status

asteroid

A javascript client (node) for a Meteor backend.

2.x.x is out, find out what changed in the CHANGELOG

Why

Meteor is an awesome framework for building real-time APIs. Its canonical front-end framework however is not very flexible. Adopting other front-ends comes with the cost of having to work around the limitations of meteor's build tool, which makes it very difficult, for instance, to use other tools like webpack, or to manage dependencies via npm.

Asteroid is an isomorphic/universal javascript library which allows to connect to a Meteor backend from almost any JS environment.

With Asteroid you can:

  • hook any existing application to a real-time meteor API
  • use any front-end framework you want with a Meteor backend
  • develop browser extensions backed by Meteor
  • use Meteor as a backend for a react-native app

Advantages over the canonical Meteor front-end

  • Small footprint
  • Framework agnostic. Use the tools you already know and love to build your app
  • Allows to use Meteor as a full-blown backend or just as a real-time platform pluggable into any existing project
  • Easily connect to multiple Meteor servers at the same time, perfect for building admin interfaces

Install

npm install --save asteroid

Usage

import {createClass} from "asteroid";

const Asteroid = createClass();
// Connect to a Meteor backend
const asteroid = new Asteroid({
    endpoint: "ws://localhost:3000/websocket"
});

// Use real-time collections
asteroid.subscribe("tasksPublication");

asteroid.ddp.on("added", ({collection, id, fields}) => {
    console.log(`Element added to collection ${collection}`);
    console.log(id);
    console.log(fields);
});

// Login
asteroid.loginWithPassword({username, email, password});

// Call method and use promises
asteroid.call("newUser")
    .then(result => {
        console.log("Success");
        console.log(result);
    })
    .catch(error => {
        console.log("Error");
        console.error(error);
    });

Mixins

Mixins are used to extend Asteroid's functionalities. You add mixins by passing them to the createClass function.

A mixin is an object with a set of enumerable function properties. Those functions will all be mixed into Asteroid.prototype. The special function init won't end up the in prototype. Instead it will be called on instantiation with the arguments passed to the constructor.

Included mixins

  • ddp: establishes the ddp connection
  • methods: adds methods for invoking ddp remote methods
  • subscriptions: adds methods for subscribing to ddp publications
  • login: adds methods for logging in
  • password-login: adds methods for password logins / user creation

Third-party mixins

Development environment setup

After cloning the repository, install npm dependencies with npm install. Run npm test to run unit tests, or npm run dev to have mocha re-run your tests when source or test files change.

Contribute

Contributions are as always very welcome. If you have written a mixin for asteroid, feel free to make a PR to add it to this README.

API

module.createClass([mixins])

Create the Asteroid class. Any passed-in mixins will be added to the default mixins.

Arguments
  • mixins Array< object > optional: mixins you want to use
Returns

The Asteroid class.


new Asteroid(options)

Creates a new Asteroid instance (which is also an EventEmitter).

On instantiation:

  • the ddp mixin will automatically connect to the Meteor backend
  • the login mixin will try to resume a previous session
Arguments
  • options object required:
    • endpoint string required: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructor function optional [default: WebSocket]: the class to be used to create the websocket connection to the server. In node, use faye-websocket-node's Client. In older browsers which do not support WebSocket, use sockjs-client's SockJS
    • autoConnect boolean optional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnect boolean optional [default: true]: wheter to auto-reconnect when the connection drops for whatever reason. This option will be ignored - and the connection won't be re-established - if the connection is terminated by calling the disconnect method
    • reconnectInterval number optional [default: 10000]: the interval in ms between reconnection attempts
Returns

An Asteroid instance.


connect()

Provided by the ddp mixin.

Establishes a connection to the ddp server. No-op if a connection is already established.

Arguments

None.

Returns

Nothing.


disconnect()

Provided by the ddp mixin.

Terminates the connection to the ddp server. No-op if there's no active connection.

Arguments

None.

Returns

Nothing.


call(method, [param1, param2, ...])

Provided by the methods mixin.

Calls a server-side method with the specified arguments.

Arguments
  • method string required: the name of the method to call
  • param1, param2, ... ...any optional: parameters passed to the server method
Returns

A promise to the method return value (the promise is rejected if the method throws).


apply(method, params)

Provided by the methods mixin.

Same as call, but using as array of parameters instead of a list.

Arguments
  • method string required: the name of the method to call
  • params Array< any > optional: an array of parameters passed to the server method
Returns

Same as call, see above.


subscribe(name, [param1, param2, ...])

Provided by the subscriptions mixin.

Subscribes to the specified publication. If an identical subscription (name and parameters) has already been made, Asteroid will not re-subscribe and return that subscription instead (subscriptions are idempotent, so it does not make sense to re-subscribe).

Arguments
  • name string required: the name of the publication

  • param1, param2, ... ...any optional: a list of parameters that are passed to the publication function on the server

Returns

A subscription object. Subscription objects have an id, which you can later use to unsubscribe, and are EventEmitter-s. You can listen for the following events:

  • ready: emitted without parameters when the subscription is marked as ready by the server
  • error: emitted with the error as first and only parameter when the server signals an error occurred on the subscription
  • TODO stopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • id string required: the id of the subscription
Returns

Nothing.


createUser(options)

Provided by the password-login mixin.

Creates a user and logs him in. Does not hash the password before sending it to the server. This should not be a problem, since you'll probably be using SSL anyway.

Arguments
  • options object required:
    • username string optional
    • email string optional
    • password string required

Note: you must specify either options.username or options.email.

Returns

A promise which resolves to the userId of the created user when the creation succeeds, or rejects when it fails.


loginWithPassword(options)

Provided by the password-login mixin.

Logs the user in using username/email and password. Does not hash the password before sending it to the server. This should not be a problem, since you'll probably be using SSL anyway.

Arguments
  • options object required:
    • username string optional
    • email string optional
    • password string required

Note: you must specify either options.username or options.email.

Returns

A promise which resolves to the userId of the logged in user when the login succeeds, or rejects when it fails.


login(params)

Provided by the login mixin.

Log in the user.

Arguments
  • params object required: params to pass for login with a custom provider
Returns

A promise which resolves to the userId of the logged in user when the login succeeds, or rejects when it fails.


logout()

Provided by the login mixin.

Logs out the user.

Arguments

None

Returns

A promise which resolves to null when the logout succeeds, or rejects when it fails.


Public Asteroid events

  • connected (emitted by the ddp mixin)
  • disconnected (emitted by the ddp mixin)
  • loggedIn (emitted by the login mixin)
  • loggedOut (emitted by the login mixin)

changelog

2.0.2 (February 23, 2016)

Updated ddp.js to 2.1.0.

2.0.1 (February 16, 2016)

No changes. Only published to fix the latest tag on npm.

2.0.0 (February 16, 2016)

The library has undergone a major rewrite. As such it's drastically different from 0.6.1. The API changed, hopefully for the best. Its scope also changed a bit, so some features that were in 0.6.1 have been dropped in 2.0.0. Of course the reverse is also true.

Most notable changes

  • Installing the library

    In 0.6.1 the library was distributed as a bundle for client-side consumption, and could be installed via bower or npm. It was not possible though to require via browserify or webpack, require-ing it only worked in node.

    In 2.0.0 the library is distributed as an npm module. It's not distributed as a bundle though, so you can't download it and include it as a script in your html. If publishing it as a bundle (through npm and/or bower) is needed, please open an issue and I'll add support for it.

    The change was made to support require-ing the library in client-side code. The bundle is not distributed just because we haven't had the time to do so.

  • Obtaining the Asteroid class

    In 0.6.1 the module exported a class, Asteroid.

    In 2.0.0 the module exports a createClass function, which is used to create the Asteroid class.

    The change was made to allow adding functionalities to the class via mixins (see docs).

    // 0.6.1
    const Asteroid = require("asteroid");
    const asteroid = new Asteroid(/* ... */);
    
    // 2.0.0
    const createClass = require("asteroid").createClass;
    const Asteroid = createClass();
    const asteroid = new Asteroid(/* ... */);
  • Creating Asteroid instances

    The signature of the Asteroid class constructor changed.

    The change was made to allow to specify options which mixins might need.

    // 0.6.1
    const asteroid = new Asteroid(host, useSsl, interceptorFunction);
    
    // 2.0.0
    // The `optionsObject` now takes whatever options needed by the used mixins.
    const asteroid = new Asteroid(optionsObject);
  • Calling methods

    In 0.6.1 the call and apply methods returned an object with two properties: result and updated. result was a promise to the method invocation result. updated was a promise which resolved when the server sent an updated message for the invocation.

    In 2.0.0 both methods return directly a promise to the invocation result. The library does not currently offer a way to listen for the updated event (it can be done by doing something like asteroidInstance.ddp.on("updated", handler)).

    The change was made to simplify method calls (it seemed more idiomatic for a js library to have this API).

    // 0.6.1
    asteroid.call("myMethod", 1, 2, 3).result.then(ret => {
        console.log(ret);
    });
    
    // 2.0.0
    asteroid.call("myMethod", 1, 2, 3).then(ret => {
        console.log(ret);
    });
  • Subscribing to publications

    In 0.6.1 the subscribe method returned an object containing:

    • a stop method, which could be called to terminate the subscription
    • a ready property, a promise which resolved when the server marked the subscription as ready

    In 2.0.0 the subscribe method returns an object containing:

    • an id property, which can be used to terminate the subscription by passing it to the unsubscribe method
    • an on method (the object is an event emitter), which can be used to register a handler for the ready, error (and soon also the stopped) events

    The change was made to allow a finer-grained management of subscriptions.

  • Managing collections

    0.6.1 handled collections.

    2.0.0 simply doesn't. Handling collections is delegated to third party mixins, such as asteroid-immutable-collections-mixin.

    The change was made because in many projects we found ourselves not using Asteroid's collections, but rather re-implementing them in some other way (e.g. as immutable maps). To avoid wasting cpu time and memory storing them in Asteroid directly, we preferred to leave managing them to external mixins. Admittedly, there is currently no mixin that replicates the old behaviour. If you developed one or plan to do so, be sure to let us know and we'll list it in the mixins section in the README.

  • Using reactiveQuery-s

    reactiveQuery-s were a feature of collections. As such, they have also been dropped in 2.0.0.

1.0.0 (February 16, 2016)

Unless you're certain you need 1.0.0, skip it and just use 2.0.0

The 1.0.0 fiasco

We began the rewrite that led to 2.0.0 sometime in summer 2015. Development took place on the 1.0.0-rewrite branch. Unfortunately we never got to the point of actually releasing 1.0.0, and changes staled in the 1.0.0-rewrite branch for several months. Some of our projects migrated to 1.0.0, installing it directly from the branch.

Then 2.0.0 came along and brought with it some minor braking changes (it's a bit of an oxymoron, but...) that we couldn't push to 1.0.0-rewrite. So we froze the branch, published 1.0.0 from there and right after published 2.0.0.

Sorry for the mess. Pretend 1.0.0 never existed. If you can't because - like us - you're in some way dependent on it, we hope to have made all we can to keep it available. If not, let us know and we'll help you out.

0.7.0 (February 16, 2016)

Basically 0.6.1 with two pull-requests merged in.