1.0.3 • Published 6 years ago

@amidoltd/shared-req-res-handler v1.0.3

Weekly downloads
-
License
WTFPL
Repository
-
Last release
6 years ago

Shared Rest Request/Response parser

Can be used with any web framework like express, should be used to strip out any meta data in the request object, allowing for quick access to headers, body, params, query objects

installation

npm i @amidoltd/shared-req-res-handler

sample usage

full request object parsed
var RestModel = require('@amidoltd/shared-req-res-handler');
var SomeFoo = require('./someFoo');

/**
 * sample PUT request
 */
router.post('/:mandatoryPathParam/:optionalPathParam?', function (req, res) {
    this._req = req;
    // fullObject will parse the entire request and strip out all properties except body, headers, params, query
    var someFoo = new SomeFoo(RestModel.Reqst.fullObject(this._req));
    someFoo.methodRequiringFullRequestObject((e, d) => {
        if (e) {
            res.statusCode = 500;
            res.send(RestModel.Resp.errorResp(e, "ANSIBLE160x5"));  // TODO stringify error response on app side
            res.end();
        } else {
            res.statusCode = 200;
            res.send(RestModel.Resp.successResp(d));
            res.end();
        }
    });
});
params only
var RestModel = require('@amidoltd/shared-req-res-handler');
var SomeFoo = require('./someFoo');

/**
 * sample PUT request
 */
router.put('/:mandatoryPathParam/:optionalPathParam?', function (req, res) {
    this._req = req;
    // params will parse the params of request and strip out all other properties
    var someFoo = new SomeFoo(RestModel.Reqst.fullObject(this._req));
    someFoo.methodRequiringParamsOfTheRequestOnly((e, d) => {
        if (e) {
            res.statusCode = 500;
            res.send(RestModel.Resp.errorResp(e, "ANSIBLE160x5"));  // TODO stringify error response on app side
            res.end();
        } else {
            res.statusCode = 200;
            res.send(RestModel.Resp.successResp(d));
            res.end();
        }
    });
});
request details
var RestModel = require('@amidoltd/shared-req-res-handler');
var requestParsed = RestModel.Reqst.fullObject(this._req);

console.log(requestParsed);
{   
    body: {},
    params: {},
    headers: {},
    query: {}
}

Response Parser

This will create a unified response Model to be consumed in client apps

  • on success returning an object
{ 
    responseData: {}
}
  • on success returning an array
{ 
    responseData: [{}]
}
  • on success returning a string
{ 
    responseData: ""
}
  • on error returns an error object and a code to allow for
{ 
    responseData: {},
    code: ""
}

RELEASE NOTES
  • 1.0.2
TODO
  • improve docs