rauricoste-request v2.0.2
Summary
rauricoste-request is a fluent api to send HTTP request
using Promise as its core data object.
It is written using nodejs libraries. Then, it should be
compiled with a tool like browserify
API
A HTTP call consists on some modifiers calls followed
by a callers call. It will always return a Promise.
If the HTTP code is >= 400, the promise response will contain an error
with details.
Exemple :
new Request()
.json()
.withHeader("Authorization", "Bearer 12345")
.withQueryParams({
start_time: "2017-01-01",
end_time: "2017-12-31"
})
.get("https://api.domain.com").then(response => {
// extract the response body and status code
const { body, statusCode } = response;
// parse the body as a json object
const json = JSON.parse(body);
}).catch(err => {
// extract the response and request
const { request, res } = err;
// extract the response status code and the response body
const { statusCode, body } = res;
})callers
get(url): launch the request with the methodGETon the urlurlpost(url, body): launch the request with the methodPOSTon the urlurlwith the bodybody.
body can be a string or an object (cf withBody method)
call(url): launch the request with the current method provided bywithMethodon the urlurl.
Default method is GET
modifiers
withBody(string or object): add a body to the request. If the body is an object, it will convert it the same way it does for query parameters. If calling aPOST, you shoud pass an object. If calling a JSON API, you should convert the object to JSON usingJSON.stringify(object)
Exemple : withBody({start: 2017, end: 2018}) will convert
to start=2017&end=2018.
withQueryParams(string or object): adds query parameters on the url called. If this method is called several times, only last call is effective.
Exemple : withQueryParams({start: "a", end: "z"}) : will add
start=a&end=z
withHeaders(object)adds a list of headers
Exemple : withHeaders({Authorization: "Bearer 12345"}) : adds the
header Authorization: Bearer 12345
withHeader(key, value)adds a header
Exemple : withHeaders("Authorization", "Bearer 12345") : adds the
header Authorization: Bearer 12345
withMethod(value): will change the HTTP method. Methods can beGET, PUT, POST, DELETE, .... Defaults :GETwithUrl(url): will change the base URL called. This method will not modify query parameterswithCredentials(boolean): if set totrue, credentials will be sent. It can be usefull when using CORS
content-types
talkType(type): is a shortcut for.withHeaders({"Content-Type": type, "Accept": type})json(): is a shortcut for.talkType("application/json")xml(): is a shortcut for.talkType("application/xml")