npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

appcd-dispatcher

v3.1.6

Published

Provides HTTP-like API for exposing services.

Downloads

73

Readme

appcd-dispatcher

Provides an HTTP-like API for registering and invoking service endpoints.

Visit https://github.com/appcelerator/appc-daemon for more information.

Report issues to GitHub issues. Official issue tracker in JIRA.

Installation

npm i appcd-dispatcher

Usage

Dispatcher Instance

import Dispatcher from 'appcd-dispatcher';

const dispatcher = new Dispatcher();

dispatcher.register('/foo/:id?', ctx => {
	if (ctx.request.params.id) {
		return {
			message: `hello ${ctx.request.params.id}!`
		};
	}

	return {
		message: 'hello guest!'
	};
});

try {
	// 200
	let ctx = await dispatcher.call('/foo');
	console.log('Response:', ctx.response);

	// 200 with parameter
	ctx = await dispatcher.call('/foo/123');
	console.log('Response:', ctx.response);

	// 404
	await dispatcher.call('/bar');
} catch (err) {
	console.error(err);
}

Global Dispatcher Instance

Dispatcher has a static register(), unregister(), and call() methods.

Dispatcher.register('/foo/:id?', ctx => {
	const { id } = ctx.request.params;
	ctx.response = {
		message: `hello ${id || 'guest'}!`
	};
});

Streaming Handler

Dispatcher.register('/foo', ({ response }) => {
	setInterval(() => {
		response.write(new Date().toString());
	}, 1000);
});

Responses

Response statuses are based on HTTP status codes. Successful calls return a 200 status, bad requests return a 400 status, route not found returns a 404 status, and errors return a 500 status.

Route handlers can throw any Error and the dispatcher will return it as a 500.

appcd-response provides Response and AppcdError classes to assist with return messages with specific text and statuses.

ServiceDispatcher

A ServiceDispatcher is an abstract base class for implementing services that support calls and subscriptions. You must not directly instantiate a ServiceDispatcher, but rather define your own class that extends it.

If your service just needs to serve a simple object or array dataset, such as a gawked object, then you should use the DataServiceDispatcher. ServiceDispatcher is intended for intances where you need strict control.

Examples of a ServiceDispatcher being used are the ConfigService and FSWatchManager.

import { ServiceDispatcher } from 'appcd-dispatcher';

export default class MyService extends ServiceDispatcher {
	onCall(ctx) {
		return 'Hello from my service';
	}
}

The following are all of the methods that your ServiceDispatcher derived class can implement:

onCall(ctx)

Handles a request with a single response. Note that the response can be a stream, but not efficient if there are multiple incoming requests.

| Param | Type | Description | | ----- | ---------------------------------- | -------------------------------------------------------------------- | | ctx | DispatcherContext (docs) | A dispatcher context containing the original request and a response. |

Returns anything. When result is a DispatcherContext, it is returned to the Dispatcher. When result is not undefined, then it is stored in the response of the DispatcherContext (ctx.response) and returned to the dispatcher. onCall() may also return a Promise which resolves a response as previously described.

This method is optional.

getTopic(ctx)

Returns a topic based on the request context.

| Param | Type | Description | | ----- | ---------------------------------- | -------------------------------------------------------------------- | | ctx | DispatcherContext (docs) | A dispatcher context containing the original request and a response. |

Returns a String.

This method is optional. By default, the ServiceDispatcher will use the ctx.realPath.

initSubscription({ ctx, publish(), sid, topic })

Called before the first subscription for the given topic is requested. If all subscriptions have been unsubscribed, then the next subscription event would invoke this callback.

| Param | Type | Description | | ----------- | ------------------------------------ | ----------- | | ctx | DispatcherContext (docs) | A dispatcher context containing the original request and a response. | | publish() | Function | A function that should be called when your service wants to publish an event to all topic subscribers. | | sid | String | The subscription id. Useful for unsubscribing. | | topic | String | The subscription topic derived from getTopic() or ctx.realPath. |

This method returns undefined and is optional unless you are using onSubscribe().

onSubscribe({ ctx, publish(), sid, topic })

Called when a new subscription is requested. Requires the initSubscription() method to be defined.

| Param | Type | Description | | ----------- | ------------------------------------ | ----------- | | ctx | DispatcherContext (docs) | A dispatcher context containing the original request and a response. | | publish() | Function | A function that should be called when your service wants to publish an event to all topic subscribers. | | sid | String | The subscription id. Useful for unsubscribing. | | topic | String | The subscription topic derived from getTopic() or ctx.realPath. |

This method returns undefined and is optional.

onUnsubscribe({ ctx, publish(), sid, topic })

Called when a subscription has been unsubscribed. Requires the destroySubscription() method to be defined.

| Param | Type | Description | | ----------- | ------------------------------------ | ----------- | | ctx | DispatcherContext (docs) | A dispatcher context containing the original request and a response. | | sid | String | The subscription id. Useful for unsubscribing. | | topic | String | The subscription topic derived from getTopic() or ctx.realPath. |

This method returns undefined and is optional.

destroySubscription()

Called after the last subscription for the given topic has been unsubscribed.

| Param | Type | Description | | ----------- | ------------------------------------ | ----------- | | ctx | DispatcherContext (docs) | A dispatcher context containing the original request and a response. | | publish() | Function | A function that should be called when your service wants to publish an event to all topic subscribers. | | sid | String | The subscription id. Useful for unsubscribing. | | topic | String | The subscription topic derived from getTopic() or ctx.realPath. |

Note that publish() is not intended to be invoked, but rather used to remove any event listeners.

This method returns undefined and is optional unless you are using onUnsubscribe().

DataServiceDispatcher

A DataServiceDispatcher is a ServiceDispatcher implementation for wiring up a object or array dataset to a data-only service. It gives you automatic data responses with filtering and subscriptions.

DataServiceDispatcher has an property called data. It must be a gawked object. You can either pass an object into the constructor or override this.data with your own gawked object.

If you pass in an object, the DataServiceDispatcher will gawk it for you, then directly update properties of data.

import { DataServiceDispatcher } from 'appcd-dispatcher';

export default class MyDataService extends DataServiceDispatcher {
	constructor() {
		super({
			ts: Date.now()
		});

		setInterval(() => {
			this.data.ts = Date.now();
		}, 1000);
	}
}

Examples of a DataServiceDispatcher being used are the StatusMonitor and PluginManagerStatus.

Legal

This project is open source under the Apache Public License v2 and is developed by Axway, Inc and the community. Please read the LICENSE file included in this distribution for more information.