Skip to content

Latest commit

 

History

History
495 lines (342 loc) · 10.7 KB

API.md

File metadata and controls

495 lines (342 loc) · 10.7 KB

API

The following methods are available.

get

.get(url)

Where url is a string. Shorthand for request.method('get').url(url).

post

.post(url)

Where url is a string. Shorthand for request.method('post').url(url).

put

.put(url)

Where url is a string. Shorthand for request.method('put').url(url).

delete

.delete(url)

Where url is a string. Shorthand for request.method('delete').url(url).

method

Sets the HTTP method.

.method(method)

Where method is a string, e.g. 'get' or 'GET'.

url

Sets the full URL of the request. If a query-string is present, it will override any previously set query parameters.

.url(url)

Where url is a string, e.g. 'https://example.com/accounts'.

urlParams

Sets URL parameters which will be replaced from the URL when the request is sent.

.urlParams(object)

Where object is an object.

Example:

// Will make request to "/api/accounts/123/info"
request.get('/api/accounts/:accountId/info').urlParams({ accountId: 123 })

baseUrl

Sets the base URL to which all subsequent request URLs will be appended.

.baseUrl(url)

Where url is a string, e.g. 'https://example.com'.

A few examples of practical usage:

request.baseUrl('https://example.com').url('accounts')    // => https://example.com/accounts
request.baseUrl('https://example.com').url('/accounts')   // => https://example.com/accounts
request.baseUrl('https://example.com/nested').url('/accounts')     // => https://example.com/nested/accounts
request.baseUrl('https://example.com/nested/foo').url('accounts')  // => https://example.com/nested/foo/accounts

query

Sets query parameters from an object or a string. Overwrites existing query.

.query(object | string)

Where object is key-value object of query parameters to set, or a valid query string.

Example:

request.query({ first: 'foo', second: 'bar' })
request.query('first=foo&second=bar')

headers

Sets request headers from an object. Overwrites existing headers.

.headers(object)

Where object is key-value object of headers to set.

Example:

const req = request.headers({ 'x-example': 'foo' });
console.log(req.toObject().headers) // => { 'x-example': 'foo' }
// Overwrites all previous headers:
const req2 = req.headers({ 'x-token': 'secret123' });
console.log(req2.toObject().headers) // => { 'x-token': 'secret123' }

amendHeaders

Sets request headers from an object. Only overwrites headers present in the given object.

.amendHeaders(object)

Where object is key-value object of headers to set.

Example:

const req = request.headers({ 'x-example': 'foo' }).amendHeaders({ 'x-token': 'secret123' });
console.log(req.toObject().headers) // => { 'x-example': 'foo', 'x-token': 'secret123' }

header

Adds or updates a header value.

.header(key, value)

Where key is a string and value is a string.

Example:

const req = request.header('x-example', 'foo').header('x-token', 'secret123');
console.log(req.toObject().headers) // => { 'x-example': 'foo', 'x-token': 'secret123' }

unsetHeader

Removes a header from the request.

.unsetHeader(name)

Where name is a string.

Example:

const req = request.headers({ 'x-example': 'foo', 'x-token': 'secret123' }).unsetHeader('x-example');
console.log(req.toObject().headers) // => { 'x-token': 'secret123' }

body

Set the raw body of the request.

.body(data)

Where data is a string.

See also json and urlencoded.

json

Sets a JSON-encoded body and sets the Content-Type header to 'application/json'.

.json(value)

Where value is mixed.

Shorthand for request.header('Content-Type', 'application/json').body(JSON.stringify(value)).

urlencoded

Sets a URL-encoded body and sets the Content-Type header to 'application/urlencoded'.

.urlencoded(data)

Where value is an object.

Shorthand for request.header('content-type', 'application/x-www-form-urlencoded').body(_valueUrlEncoded_).

timeout

Sets a timeout after which the request will be aborted and the Promise rejected.

.timeout(milliseconds)

Where milliseconds is an integer.

See also unsetTimeout.

unsetTimeout

Removes the timeout-value previously set with timeout.

.unsetTimeout()

prop

Sets a path (similar to lodash.get) which will be resolved once the response is returned.

.prop(path)

Where path is a string or an array.

Example:

const account = await request.get('...').prop('data.accounts[0]');
const contentType = await request.get('...').prop(['headers', 'content-type']);

send

Dispatches the request and returns a Promise.

.send([body])

Where the optional argument body is a string. If it is set, it will be set as the request body. Also see sendJson and sendUrlencoded.

The Promise resolves with a response object.

request
  .get('https://example.com')
  .then(response => {
    console.log(response.headers); // object
    console.log(response.body); // string
    console.log(response.status); // integer
  })
  .catch(error => {
    console.log(error.message);
    console.log(error.response); // Similar structure as successful response
  })

A new Promise is always returned, and the YeaAjaxRequest is not mutated, so you can send the same request multiple times.

const req = request.get('https://example.com');
req.send().then(response => {
  console.log('first response', response);
});
req.send().then(() => {
  console.log('second response', response);
});

See polyfills for switching away from global Promise (e.g. bluebird).

Note that calling .send() is not always necessary. You can usually directly call .then().

sendUrlencoded

Shorthand for .urlencoded(data).send().

.sendUrlencoded(data)

sendJson

Shorthand for .json(data).send().

.sendJson(data)

setResponseTransformers

Sets a list of response transformers which are called when a response is received. By default the list contains one transformer which decodes JSON bodies based on the response Content-Type header.

Using this method you can remove the default transformer:

.setResponseTransformers([])

If you need to add it back, just set it again:

request.setResponseTransformers([ request.jsonResponseTransformer ]);

Transformer functions are executed sequentially in the order they are in the list, and they receive response as the only parameter. Whatever value they return is passed onto the next transformer and eventually back to the Promise-chain.

request.setResponseTransformers([
  response => {
    response.foobar = 'some extra information from elsewhere, for example';
    return response;
  }
]);

Reference to the original array is lost:

const array = [];
const req = request.setResponseTransformers(array);
array.push(someFunction);
req.toObject().responseTransformers; // not affected by the push, still []

setAllowedStatusCode

By default any 2XX status code resolves the Promise and other status codes will reject it. This can be customized using setAllowedStatusCode.

.setAllowedStatusCode(allowed)

Where allowed is an integer, a RegExp or a function.

polyfills

Override global dependencies which are used internally. Most useful for adding polyfills or a custom Promise-implementation.

.polyfills(polyfills)

Where polyfills is an object. See example for the possible dependencies you can override:

request.polyfills({
  Promise: window.Promise
})

Links to polyfills for older browsers if you need to support them (these can automatically patch window.Promise; no need to use request.polyfills):

then

Sends the request and resolves like a normal Promise.

.then(arguments)

Where arguments are what you would submit to a then-handler of a Promise.

The following examples are basically equivalent:

const responseHandler = response => { /* ... */ };

// using .then()
yea.get('http://example.com').then(responseHandler)

// using .send()
yea.get('http://example.com').send().then(responseHandler)

toObject

Returns the request configuration as an object.

.toObject()
.config() // alias
.debug() // alias

Example:

const req = request.baseUrl('http://example.com').get('/info').header('X-Random', 'foo')
const config = req.toObject(); // or req.config() or req.debug()
// =>
// {
//   method: 'GET',
//   url: 'http://example.com/info',
//   body: '',
//   headers: {
//     'x-random': 'foo'
//   },
//   allowedStatusCode: /^2[0-9]{2}$/,
//   timeout: null,
//   responseTransformers: [
//     req.jsonResponseTransformer
//   ],
// }

YeaResponse

Responses have the following format:

{
  headers: {
    'content-type': 'text/html',
    ...
  },
  body: 'raw body text',
  status: 200
}

By default JSON responses are decoded (see .setResponseTransformers([])), in which case there is an extra property:

{
  headers: {
    'content-type': 'application/json',
    ...
  },
  body: '{"foo":"bar"}',
  status: 200
  data: {
    foo: 'bar'
  }
}

YeaRequestError

If a request fails, the Promise is rejected with an error which includes an extra response property:

{
  message: 'Request failed with status 500',
  stack: '...',
  // ...
  response: {
    headers: { ... },
    status: 500,
    body: '...'
  }
}

Note that yea throws regular synchronous errors if a request config is invalid, e.g.

throw new Error('Invalid header value for header \'' + name + '\'');