This module provides API to request/submit data using different runtime engines, like XHR, Fetch, etc.
The submodules contain different classes to work with HTTP headers, server responses and errors.
The first one creates a request based on the specified parameters.
As the first argument, the function takes a URL to request. The second argument is optional and declares additional request options.
In addition, you can read or write the api property from core/request#globalOpts or
through globalOpts.api property within your encoders/decoders/middlewares.
This overload is useful to create a wrapped request function.
It takes an object with request options and returns a new request function.
This function will use the passed options by default, but you can override them.
Finally, the result function can take another object with options and returns a new wrapped function recursively.
Parameters from the first and second invoke will be deeply merged.
The third overload helps to create a factory of requests.
It takes a URL to request, additional options (optional), and the special resolve function.
Then, it returns a new function to create requests with the passed options.
// If the resolver function returns an array of string, it will replace the original request URL return ['https://bla.com', ...args.slice(0, -1)]; } );
If the used request engine supports streaming, you can use it via an async iterator.
Notice, you won't switch to another form when you read response as a whole data or in a stream form.
Additional HTTP request headers. You can provide them as a simple dictionary or an instance of the Headers class.
Also, you can pass headers as an instance of the core/request/headers class.
See more.
Request parameters that will be serialized to a string and passed via a request URL.
To customize how to encode data to a query string, see querySerializer.
/** * @typeparam D - response data type */ exportinterfaceRetryOptions<D = unknown> { /** * Maximum number of attempts to request */ attempts?: number;
/** * Returns a number in milliseconds (or a promise) to wait before the next attempt. * If the function returns false, it will prevent all further attempts. * * @paramattempt - current attempt number * @paramerror - error object */ delay?(attempt: number, error: RequestError<D>): number | Promise<void> | false; }
These parameters apply if the original request URL is not absolute, and they can be used to customize the
base API URL depending on the runtime environment. If you define the base API URL via
config#api or globalOpts.api, these parameters will be mapped on it.
exportinterfaceRequestAPI { /** * The direct value of API URL. * If this parameter is defined, all other parameters will be ignored. * * @example * `'https://google.com'` */ url?: RequestAPIValue;
A value in milliseconds that indicates how long a request value should keep in the cache
(all requests are stored within the active session without expiring by default).
This option enables support of offline caching.
By default, a request can only be taken from a cache if there is no network.
You can customize this logic by providing a custom cache object with the core/cache/decorators/persistent decorator.
A dictionary or iterable value with middleware functions: functions take an environment of request parameters and can modify theirs.
Please notice that the order of middleware depends on the structure you use.
Also, if at least one of the middlewares returns a function, invoking this function will be returned as the request result.
It can be helpful to organize mocks of data and other similar cases when you don't want to execute a real request.
A function (or a sequence of functions) takes the current request data and returns new data to request.
If you provide a sequence of functions, the first function will pass a result in the next function from the sequence, etc.
A function (or a sequence of functions) takes the current request response data and returns new data to respond.
If you provide a sequence of functions, the first function will pass a result to the next function from the sequence, etc.
A function (or a sequence of functions) takes the current request response data chunk and yields a new chunk to respond via an async iterator.
If you provide a sequence of functions, the first function will pass a result to the next function from the sequence, etc.
This parameter is used when you're parsing responses in a stream form.
A meta flag that indicates that the request is important: is usually used with middlewares to indicate that
the request needs to be executed as soon as possible.
importrequestfrom'core/request';
request('/users', { important:true,
middlewares: { doSomeWork({ctx}) { if (ctx.important) { // Do some work... } } } }).data.then(console.log);
This parameter defined a request engine to use.
The engine - is a simple function that takes request parameters and returns an abortable promise resolved with the core/request/response instance.
Mind, some engines provide extra features. For instance, you can listen to upload progress events with the XHR engine.
Or, you can parse responses in a stream form with the Fetch engine.
core/request
This module provides API to request/submit data using different runtime engines, like XHR, Fetch, etc. The submodules contain different classes to work with HTTP headers, server responses and errors.
Supported engines
xhr
fetch
browser
(the engine usesfetch
when it's possible, otherwisexhr
)node
(the engine uses Got as a request library)provider
(the engine based oncore/data
providers)API
The function has three overloads of usage.
Creating a request
The first one creates a request based on the specified parameters. As the first argument, the function takes a URL to request. The second argument is optional and declares additional request options.
Request URL
There are two variants of request URL-s:
absolute
relative
In the case of a relative URL, the full request URL is based on the application
location
.But also, you can define the base API URL within your application config. This URL will be used for any relative requests.
config
foo.ts
In addition, you can read or write the
api
property fromcore/request#globalOpts
or throughglobalOpts.api
property within your encoders/decoders/middlewares.Creating a new request function with the default request options
This overload is useful to create a wrapped request function. It takes an object with request options and returns a new request function. This function will use the passed options by default, but you can override them. Finally, the result function can take another object with options and returns a new wrapped function recursively. Parameters from the first and second invoke will be deeply merged.
Creating a new request factory with the specified URL and default request options
The third overload helps to create a factory of requests. It takes a URL to request, additional options (optional), and the special resolve function. Then, it returns a new function to create requests with the passed options.
Returning request value
After creating a request, the function returns an instance of
core/promise/abortable
. The promise resolves with a special response object.Also, you can get
data
,emitter
orSymbol.asyncIterator
from a request promise.Parsing response data in a stream form
If the used request engine supports streaming, you can use it via an async iterator. Notice, you won't switch to another form when you read response as a whole data or in a stream form.
If you want to process only stream data without
total
andloaded
fields, use thestream
getter.Mind, the XHR engine partially supports streaming based on its
progress
event.Listening to internal engine events
If the used request engine emits some events, you can listen there via the
emitter
property. Mind, not every engine dispatch events.Request options
The request function can accept a bunch of optional parameters to make a request.
method
HTTP method to create a request. See more.
headers
Additional HTTP request headers. You can provide them as a simple dictionary or an instance of the Headers class. Also, you can pass headers as an instance of the
core/request/headers
class. See more.credentials
Enables providing of credentials for cross-domain requests. Also, you can manage to omit any credentials if the used request engine supports it.
query
Request parameters that will be serialized to a string and passed via a request URL. To customize how to encode data to a query string, see
querySerializer
.querySerializer
Returns a serialized value of the specified query object.
body
A request body. Mind, not every HTTP method can send data in this way. For instance, GET or HEAD requests can send data only with URLs (@see
query
).contentType
A mime type of the request data (if not specified, it will be cast dynamically).
responseType
A type of the response data (if not specified, it will be cast dynamically from the response headers):
'text'
- the result is interpreted as a simple string;'json'
- the result is interpreted as a JSON string;'document'
- the result is interpreted as an XML/HTML document;'formData'
- result is interpreted as a FormData object;'blob'
- the result is interpreted as a Blob object;'arrayBuffer'
- the result is interpreted as an array buffer;'object'
- the result is interpreted "as is" without any converting.[okStatuses =
new Range(200, 299)
]A list of status codes (or a single code) that match successful operation. Also, you can pass a range of codes.
timeout
A value in milliseconds for a request timeout.
retry
Options to retry bad requests or a number of maximum request retries.
api
A map of API parameters.
These parameters apply if the original request URL is not absolute, and they can be used to customize the base API URL depending on the runtime environment. If you define the base API URL via
config#api
orglobalOpts.api
, these parameters will be mapped on it.cacheStrategy
A strategy of caching for requests that support caching (by default, only GET requests can be cached):
'forever'
- caches all requests and stores their values forever within the active session or until the cache expires (ifcacheTTL
is specified);'queue'
- caches all requests, but more frequent requests will push less frequent requests;'never'
- never caches any requests;If you set a strategy using string identifiers, all requests will be stored within the global cache objects.
cacheTTL
A value in milliseconds that indicates how long a request value should keep in the cache (all requests are stored within the active session without expiring by default).
offlineCache
This option enables support of offline caching. By default, a request can only be taken from a cache if there is no network. You can customize this logic by providing a custom cache object with the
core/cache/decorators/persistent
decorator.offlineCacheTTL
A value in milliseconds that indicates how long a request value should keep in the offline cache.
[cacheMethods =
['GET']
]A list of request methods that support caching.
cacheId
A unique cache identifier: it can be useful to create request factories with isolated cache storages.
middlewares
A dictionary or iterable value with middleware functions: functions take an environment of request parameters and can modify theirs. Please notice that the order of middleware depends on the structure you use. Also, if at least one of the middlewares returns a function, invoking this function will be returned as the request result. It can be helpful to organize mocks of data and other similar cases when you don't want to execute a real request.
encoder
A function (or a sequence of functions) takes the current request data and returns new data to request. If you provide a sequence of functions, the first function will pass a result in the next function from the sequence, etc.
decoder
A function (or a sequence of functions) takes the current request response data and returns new data to respond. If you provide a sequence of functions, the first function will pass a result to the next function from the sequence, etc.
streamDecoder
A function (or a sequence of functions) takes the current request response data chunk and yields a new chunk to respond via an async iterator. If you provide a sequence of functions, the first function will pass a result to the next function from the sequence, etc. This parameter is used when you're parsing responses in a stream form.
[jsonReviver =
convertIfDate
]A reviver function for
JSON.parse
orfalse
to disable defaults. By default, it parses some strings as Date instances.meta
A dictionary with some extra parameters for the request: is usually used with middlewares to provide domain-specific information.
important
A meta flag that indicates that the request is important: is usually used with middlewares to indicate that the request needs to be executed as soon as possible.
engine
This parameter defined a request engine to use. The engine - is a simple function that takes request parameters and returns an abortable promise resolved with the
core/request/response
instance. Mind, some engines provide extra features. For instance, you can listen to upload progress events with the XHR engine. Or, you can parse responses in a stream form with the Fetch engine.