Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

npm versionBuild StatusCoverage StatusDependency StatusdevDependency 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";constAsteroid=createClass();// Connect to a Meteor backendconstasteroid=newAsteroid({endpoint: "ws://localhost:3000/websocket"});// Use real-time collectionsasteroid.subscribe("tasksPublication");asteroid.ddp.on("added",({collection, id, fields})=>{console.log(`Element added to collection ${collection}`);console.log(id);console.log(fields);});// Loginasteroid.loginWithPassword({username, email, password});// Call method and use promisesasteroid.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
  • mixinsArray< 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
  • optionsobjectrequired:
    • endpointstringrequired: the DDP endpoint to connect to, e.g. ws://example.com/websocket
    • SocketConstructorfunctionoptional [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
    • autoConnectbooleanoptional [default: true]: whether to auto-connect to the server on instantiation. Otherwise the connect method can be used to establish the connection
    • autoReconnectbooleanoptional [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
    • reconnectIntervalnumberoptional [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
  • methodstringrequired: the name of the method to call
  • param1, param2, ......anyoptional: 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
  • methodstringrequired: the name of the method to call
  • paramsArray< 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
  • namestringrequired: the name of the publication

  • param1, param2, ......anyoptional: 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
  • TODOstopped: emitted when the subscription stops

unsubscribe(id)

Provided by the subscriptions mixin.

Unsubscribes from a publication.

Arguments
  • idstringrequired: 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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • optionsobjectrequired:
    • usernamestringoptional
    • emailstringoptional
    • passwordstringrequired

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
  • paramsobjectrequired: 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)

About

An alternative client for a Meteor backend

Resources

Stars

729 stars

Watchers

47 watching

Forks

Releases

Packages

Used by

Contributors

Languages