0.0.8 • Published 8 years ago

glitr-router-client v0.0.8

Weekly downloads
1
License
MIT
Repository
bitbucket
Last release
8 years ago

glitr-router-client

example

glitr-router-client implements functionality on the a connected client to allow it to function as a router networked to the server. this means that the server is able to make requests similar to when a webapp makes a HTTP GET request to a server using some tool like isomorphic-fetch.

./grClient.js

import GlitrRouterClient from '..';

const routes = [
    {
        path: '/route-on-client',
        method: 'post',
        handler: [
            (req, res, next) => {
                console.log('[client-side] router working');
                console.log('--- message from server');
                console.log(req.body);
                console.log('---');
                next();
            },
            (req, res, next) => {
                console.log('[client-side] socket middleware works as expected');
                res.send('message from CLIENT to SERVER in response');
            }
        ]
    }
];

const options = {
    namespace: 'testing', // optional: default = ''
    requestTimeout: 10000, // optional: default = 10000
    reactNative: false // required `true` for react-native
};

const grClient = new GlitrRouterClient(routes, options);
grClient.listen('http://localhost:1234', () => {
    console.log('client is now connected');
});

export default grClient;

the glitr-routes constructor takes 2 arguaments:

  • routes
  • options

routes:

an array of objects:

attributerequiredtypedefaultdescription
pathrequiredstringthe event name that socket.io-client should litening for. the socket will be set to listen to an event in the format: ${method}::>${path}.
methodrequiredstring. one of: get, post, put, deletethe method to use for transmitting the the message.
handlerrequiredfunction or array of functionsthis is a function the takes in 3 parameters: request, response, next. the values passed into the function follow the same pattern as the middleware functions in express route handlers.

when creating handler methods for socket.io, if the request header callback property from the server is set to true, the handlers methods must respond back to the client.

the handler response object has a few helper methods to help with this:

methoddescription
sendsends a response with a default status code 200
endsends a response with a default status code 200
emitsends a response with a default status code 200
failsends a response with a default status code 400
errorsends a response with a default status code 400

all these response methods take 2 parametes i.e. res.send(data, headers). both parametes are options. data is the payload to send, headers is an object to pass additional data in the headers. you can assign a value to headers.status to sent to the client to ovverride the default status code mentioned in the previous table.

if the request takes longer than the timeout period specified in options, an exception will be thrown indicating timeout. you can handle this like a typical promise exception: promise.catch(console.log).

options

an object containing the following attributes:

attrubuterequireddefaultdescription
namespaceoptional''a namespace to assign to all the routes.
requestTimeoutoptional10000this is the number of miliseconds to wait before throwing a timeout exception when making a request that should respond with a callback (see below).
reactNativerequired for react-native clientsfalseset this value to determine if the client is using react-native.

Usage

when a new instance of glitr-router-client is created, the instance exposes the following objects:

attributedescription
listenthis function takes 2 parameters: url and callback. the url should be a a string to represent the server endpoint to connect to (including namespaces).
getthis is one of the HTTP event emitters (see below).
postthis is one of the HTTP event emitters (see below).
putthis is one of the HTTP event emitters (see below).
deletethis is one of the HTTP event emitters (see below).

HTTP event emitters

The event emitter methods mentioned in the previous table, are methods used to communicate with the server.

import GlitrRouterClient from 'glitr-router-client';

const grClient = new GlitrRouterClient(routes, options);
grClient.listen('http://localhost:1234', () => {
    console.log('client is now connected');
});

// grClient.get(path, payload, headers)
// grClient.post(path, payload, headers)
// grClient.put(path, payload, headers)
// grClient.delete(path, payload, headers)

Request

namerequiredtypedescription
pathyesstringa string the represents the path on the client to make the request.
payloadnoobjectthis optional first can be used for sending data to the server
headersnoobjectthis is to pass additional metadata about the request.
headers.callbacknobooleanset this value to true if you want to emit a message to the server and you want the server to respond when finished. (only relevent for socket endpoints on server. express expects this by default)
headers.httpnobooleanset this value to determine if the message should be sent over isomorphic-fetch. the default behaviour is to make the request with socket.io-client.

when making a request through HTTP by specifying headers.http = true, glitr-router-client will use isophomic-fetch internally to make the request. if you want to specify http headers, simply add them to the headers object. to see what header options are available see fetch docs.

Response

when callback is set to true in the headers of a request, the method will return a promise object with data sent back from the server like you would expect for any regular request over HTTP protocol.

when using socket.io to make the request, the response object properties are described in the following table.

namedescription
headerssome metadata about the request sent over by the server
bodythis is the payload the server has sent back to the client.

when using express to make the request, the response object is described on the expressjs docs

Example

import grClient from './grClient';

grClient.post('/send-message',
    {
        message: 'hello world',
        recipient: 'clark'
    }, {
        callback: true
    }
).then((dataFromServer) => {
    // process dataFromServer here ...
    console.log(dataFromServer);
});

for more details about the server-side implmentation see glitr-router.

0.0.8

8 years ago

0.0.7

8 years ago

0.0.6

8 years ago

0.0.5

8 years ago

0.0.4

8 years ago

0.0.3

8 years ago

0.0.2

8 years ago

0.0.1

8 years ago