decoreq

0.1.0 • Public • Published

Lightweight (<50 LOC) client defined via DI and decorators. Includes JSON client as example and for convenience.

Setup

const {request} = require('decoreq');

const bound = adornArguments(request, {
    return {
        send: [Request function],
        promise: [Promise constructor],
    };
});

The request function must match the signature of the function in xhr 2.x.

Concept

const {
    request,
    adornArguments,
    adornManifest,
    adornIO,
    adornErrorHandler,
    adornUriPrefix,
} = require('decoreq');

// First step: Bind client to Node request API and Bluebird promises.
const di = adornArguments(request, () => {
    return {
        send: require('xhr'),
        promise: require('bluebird'),
    };
});

// All requests made via pfx() go to cats.com
const pfx = adornUriPrefix(di, 'http://cats.com/');

// mfst() translates resource requests via manifest
const mfst = adornManifest(pfx, {'tabby.png': 'f72bb9.png'});

// GET http://cats.com/f72bb9.png
mfst({ uri: 'tabby.png' }).then(...);

// Note we are extending from `pfx` again, not `mfst`.
const io = adornIO(pfx, {
    i: ({body}) => JSON.parse(body),
    o: ({body}) => body.toJSON(),
});

// Use common error handler
const saferio = adornErrorHandler(io, (err) => {
    if (err instanceof SyntaxError) {
        console.error(err);
    } else {
        throw err;
    }
});

// POST http://cats.com/setdate with date JSON
saferio({ method: 'POST', uri: 'setdate', data: new Date() })
    .then(json => { /* json already parsed */ })
    .catch((err) => {
        // err won't be a SyntaxError.
    });

Readme

Keywords

none

Package Sidebar

Install

npm i decoreq

Weekly Downloads

2

Version

0.1.0

License

SEE LICENSE IN LICENSE

Last publish

Collaborators

  • sage.gerard