Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Networking client for Node.js, React Native & browser web apps
Coolio is an environment-agnostic networking client for Node.js, React Native & browser web apps. The aim of Coolio is to abstract out the technical stuff and let developers query APIs in DRY manner. Usually such approach makes simple things easier while making complex use-cases impossible. Coolio gives users more control over networking, allowing to customize almost every step of it's networking pipeline:
sending and handling requests,
body normalization,
pre and postprocessing.
This is achieved by using interceptors concept and providing pluggable interfaces whenever possible.
Coolio is broken down into several packages, allowing you to pick what's really needed.
Auth Interceptor with OAuth2 refresh token support for @coolio/http
HTTP networking client
JSON API client
Most important yarn
scripts during development:
start
- runs builds for all packages in watch mode
verify
- runs lint & tests
Create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.
CFormData
+ new CFormData(data?
: any): CFormData
Parameters:
data?
any
Returns: CFormData
Static
DEFAULT_CONTENT_TYPE▪ DEFAULT_CONTENT_TYPE: string = "application/octet-stream"
Static
LINE_BREAK▪ LINE_BREAK: string = " "
▸ append(name
: string, value
: any, meta?
: CFormDataEntryMetadata): void
Parameters:
name
string
value
any
meta?
Returns: void
▸ delete(name
: string): void
Parameters:
name
string
Returns: void
▸ forEach(callbackfn
: function): void
Parameters:
▪ callbackfn: function
▸ (value
: CFormDataValue, key
: string, parent
: CFormData): void
Parameters:
value
key
string
parent
Returns: void
▸ get(name
: string): CFormDataValue | null
Parameters:
name
string
Returns: CFormDataValue | null
▸ getAll(name
: string): CFormDataValue[]
Parameters:
name
string
Returns: CFormDataValue[]
▸ getBoundary(): string
Returns: string
▸ getBuffer(): Promise‹Buffer›
Returns: Promise‹Buffer›
▸ getHeaders(): object
Returns: object
content-type: string = 'multipart/form-data; boundary=' + this.getBoundary()
▸ has(name
: string): boolean
Parameters:
name
string
Returns: boolean
▸ pipe(writable
: Writable): void
Parameters:
writable
Writable
Returns: void
▸ set(name
: string, value
: CFormDataValue | Blob, meta?
: CFormDataEntryMetadata): void
Parameters:
name
string
value
meta?
Returns: void
▸ toString(): string
Returns: string
Static
from▸ from(data
: any, __namedParameters
: object): FormData | CFormData
Parameters:
▪ data: any
▪Default value
__namedParameters: object= {}
forceImplementation
undefined | "native" | "custom"
Returns: FormData | CFormData
Static
isFormData▸ isFormData(data
: any): data is FormData | CFormData
Parameters:
data
any
Returns: data is FormData | CFormData
Ƭ BodyParser: function
Parameters:
Ƭ BodyParserImplementation: function
Parameters:
Ƭ BodySerializer: function
Parameters:
Ƭ BufferEncoding: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"
Ƭ CFormDataValue: string | Blob | Readable
Ƭ CaseConverter: function
▸ (object
: any): any
Parameters:
Ƭ ContentTypeMap: Record‹keyof typeof ContentTypeRegex, T›
Ƭ HttpFetch: function
Ƭ HttpHeaders: Record‹string, string | number | boolean | undefined | null›
Ƭ HttpInterceptorFunction: function
Type parameters:
▪ Body
Parameters:
Ƭ HttpRequestHandler: function
Parameters:
Ƭ PromiseFunction: function
▸ (): Promise‹T›
Ƭ RequestMode: "navigate" | "same-origin" | "no-cors" | "cors"
Const
DEFAULT_REQUEST_TIMEOUT_MS• DEFAULT_REQUEST_TIMEOUT_MS: number = 5 * 60 * 1000
Default request timeout - 5 minutes.
Const
DONE• DONE: 4 = 4
Const
HEADERS_RECEIVED• HEADERS_RECEIVED: 2 = 2
Const
SUPPORTS_BROWSER_FORM_DATA• SUPPORTS_BROWSER_FORM_DATA: boolean = (() => { try { return !({} instanceof FormData); } catch { return false; } })()
• TypedArray: any
Const
symbol• symbol: unique symbol = Symbol('HttpResponseError')
Const
bodyParserParameters:
▪Default value
__namedParameters: object= {}
Const
bodySerializerParameters:
▪Default value
__namedParameters: object= {}
Const
cacheParsedBodyThis is not a regular cache! This function is only used across subsequent executions of parsedBody() on a single HttpResponse. To implement cache, make use of interceptors.
Type parameters:
▪ T
Parameters:
a promise function returning body, it can be called many times
Const
createAsyncBodyHandler▸ createAsyncBodyHandler<T>(): object
Type parameters:
▪ T
Returns: object
call(): Promise‹T›
onBodyFailure(failer
: function): void
onBodyReceived(getter
: function): void
Const
createErrorInterceptorConst
createHttpResponseParameters:
▪ __namedParameters: object
Const
createLoggingInterceptorParameters:
▪ __namedParameters: object
Const
createRedirectionInterceptorParameters:
▪Default value
__namedParameters: object= {}
Const
createSimpleServerConst
deepKeyMap▸ deepKeyMap(object
: any, mapper
: function): any
Parameters:
▪ object: any
▪ mapper: function
▸ (key
: string): string
Parameters:
Returns: any
Const
defaultHeaders▸ defaultHeaders(_host
: string): object
Parameters:
Returns: object
Accept: string = "application/json,application/vnd.api+json"
Const
encodeArrayBufferParameters:
Returns: Uint8Array‹›
Const
encodeText▸ encodeText(buffer
: ArrayBuffer, encoding
: string): string
Parameters:
Returns: string
Const
fetchRequestHandlerParameters:
Const
getBoundaryFromContentTypeHeader▸ getBoundaryFromContentTypeHeader(header
: string[]): string
Parameters:
Returns: string
Const
getCaseConverterParameters:
Returns: toCamelCase
Const
getEncodingFromHeadersParameters:
Returns: string
Const
getFileMetaParameters:
Returns: object | object
Const
getHeaderParameters:
Returns: string | undefined
Const
getHostname▸ getHostname(url
: string): string
Parameters:
Returns: string
Const
handleRequestParameters:
Const
httpRequestHandlerParameters:
Const
isBlob▸ isBlob(value
: any): value is Blob
Parameters:
Returns: value is Blob
Const
isBrowserFormData▸ isBrowserFormData(value
: any): value is FormData
Parameters:
Returns: value is FormData
Const
isHttpInterceptorInterfaceParameters:
Returns: interceptor is HttpInterceptorInterface
Const
isHttpRequestError▸ isHttpRequestError(error
: any): error is HttpRequestError
Parameters:
Returns: error is HttpRequestError
Const
isHttpResponseError▸ isHttpResponseError(error
: any): error is HttpResponseError
Parameters:
Returns: error is HttpResponseError
Const
mockRequestHandlerParameters:
Const
noConversion▸ noConversion(object
: any): any
Parameters:
Returns: any
Const
parseHeaders▸ parseHeaders(headers
: Headers): Record‹string, string›
Parameters:
Returns: Record‹string, string›
Const
processMultipartBody▸ processMultipartBody(body
: string, boundary
: string): never
Parameters:
Returns: never
Const
readBlob▸ readBlob(blob
: Blob): Promise‹Buffer›
Parameters:
Returns: Promise‹Buffer›
Const
sanitizeHeaders▸ sanitizeHeaders(...multipleHeaders
: undefined | object[]): Record‹string, string›
Parameters:
Returns: Record‹string, string›
Const
sleep▸ sleep(ms
: number): Promise‹unknown›
Parameters:
Returns: Promise‹unknown›
Const
splitWords▸ splitWords(text
: string): string[]
Parameters:
Returns: string[]
Type parameters:
▪ T
Parameters:
Returns: T
Type parameters:
▪ T
Parameters:
Returns: T | undefined
Const
toCamelCase▸ toCamelCase(object
: any): any
Parameters:
Returns: any
Const
toKebabCase▸ toKebabCase(object
: any): any
Parameters:
Returns: any
Const
toPascalCase▸ toPascalCase(object
: any): any
Parameters:
Returns: any
Const
toScreamingSnakeCase▸ toScreamingSnakeCase(object
: any): any
Parameters:
Returns: any
Const
toSnakeCase▸ toSnakeCase(object
: any): any
Parameters:
Returns: any
Const
toUrlEncoded▸ toUrlEncoded(obj
: object): string
Parameters:
Returns: string
Const
urlCombine▸ urlCombine(sourceUrl
: string, sourceQuery?
: undefined | object, options?
: qs.IStringifyOptions): string
Parameters:
Returns: string
Const
urlDecode▸ urlDecode<T>(value
: string, options?
: qs.IParseOptions): T
Type parameters:
▪ T
Parameters:
Returns: T
Const
urlDestruct▸ urlDestruct(url
: string, options?
: qs.IParseOptions): object
Parameters:
Returns: object
query: any
url: string
Const
urlEncode▸ urlEncode(value
: any, options?
: qs.IStringifyOptions): string
Parameters:
Returns: string
Const
useInterceptorParameters:
Returns: (Anonymous function)
Const
xhrRequestHandlerParameters:
Const
ContentTypeRegex• JSON: RegExp‹› = /^application/(json|.++json)$/
• MULTIPART: RegExp‹› = /^multipart//
• TEXT: RegExp‹› = /^text//
• URL_ENCODED: RegExp‹› = /^application/x-www-form-urlencoded$/
Const
HttpClientHelper• getHostname: getHostname
Const
HttpStatusText• __computed: string = "Network Authentication Required"
Const
Interceptors• createErrorInterceptor: createErrorInterceptor
• createLoggingInterceptor: createLoggingInterceptor
• createRedirectionInterceptor: createRedirectionInterceptor
Base class in Coolio http package, which allows to perform API calls.
▪ T
Common body shape defined by bodyParser passed in .
HttpClient
Parameters:
Adds an interceptor to the client. Interceptor can be written either as class or as a function, which may mutate request options and post-process response from server. Multiple interceptors can be added to a single HttpClient. They can perform as:
cache
error handler
authorizer
logger
auto-retry
redirection handler
Parameters:
Returns: this
Performs a DELETE request.
Type parameters:
▪ Body: T
Parameters:
Performs a GET request.
Type parameters:
▪ Body: T
Parameters:
Performs a PATCH request.
Type parameters:
▪ Body: T
Parameters:
Performs a POST request.
Type parameters:
▪ Body: T
Parameters:
Performs a PUT request.
Type parameters:
▪ Body: T
Parameters:
Performs a DELETE request.
deprecated
Use delete instead of remove, since it matches HTTP request method.
Type parameters:
▪ Body: T
Parameters:
Type parameters:
▪ Body: T
Parameters:
Networking client for Node.js, React Native & browser web apps
Coolio is an environment-agnostic networking client for Node.js, React Native & browser web apps. The aim of Coolio is to abstract out the technical stuff and let developers query APIs in DRY manner. Usually such approach makes simple things easier while making complex use-cases impossible. Coolio gives users more control over networking, allowing to customize almost every step of it's networking pipeline:
sending and handling requests,
body normalization,
pre and postprocessing.
This is achieved by using interceptors concept and providing pluggable interfaces whenever possible.
Coolio is broken down into several packages, allowing you to pick what's really needed.
Most important yarn
scripts during development:
start
- runs builds for all packages in watch mode
verify
- runs lint & tests
All notable changes to this project will be documented in this file. See for commit guidelines.
case-conversion: incorrect name formats are handled gracefully ()
headers: preserve header casing ()
case-conversion: screaming snake case support ()
headers: explicitly passed nil value removes existing header ()
headers: removed deprecated headers options
Note: Version bump only for package coolio
Note: Version bump only for package coolio
Note: Version bump only for package coolio
url-encoding: url string has now bigger priority than query passed in object, which results in better composability (parameters from url are always merged into object)
Note: Version bump only for package coolio
Note: Version bump only for package coolio
@coolio/http
is a simple, yet extendable HTTP client for web apps. It features:
body parsing and serialization, with case-conversion support
raw data (ArrayBuffer)
JSON
URL-encoded
plain text
multipart ()
extensibility via , with built-ins such as:
logger
error handler
redirection interceptor
configurable requestHandler layer, which let's you choose the underlaying mechanism used for HTTP communication
Install @coolio/http
package using npm
or yarn
.
You may create multiple HttpClient
instances, as your application connects to various APIs and each API probably has slightly different conventions. You can initialize a HttpClient and configure it as below:
In the example above, we create HttpClient
instance which will route all paths to api.example.com/v1
address:
if you request /users
, the request will go to api.example.com/v1/users
if you request https://google.com
, the request will go to google.com
, as you specified full URL and baseUrl
is not applied in such case.
You may use the repository pattern to separate API requests from other code. You can use previously defined HttpClient
as below:
After doing the following, you can simply call UserRepository.getProfile()
to receive the Promise returning User
object.
Another way of dealing with repositories is to use class-based approach:
If you happen to use JSON API, you may benefit from using a wrapper library that handles most of it's specs:
| Blob
▸ (response
: ): ‹T›
▸ (rawResponse
: ): Promise‹any›
▸ (request
: ):
Ƭ HttpBody: object | | string
▸ (): Promise‹‹Body››
Ƭ HttpInterceptor: |
▸ <Body>(request
: ‹Body›, options
: ): ‹Body›
Ƭ HttpOptions: Partial‹›
▸ (requestOptions
: ): Promise‹›
Ƭ MockHttpRequestHandler: & object
Ƭ NormalizedHttpBody: FormData | | | string | undefined
▸ bodyParser(__namedParameters
: object): ‹any›
Returns: ‹any›
▸ bodySerializer(__namedParameters
: object):
Returns:
▸ cacheParsedBody<T>(parsedBody
: ‹T›): ‹T›
Returns: ‹T›
▸ createErrorInterceptor():
Returns:
▸ createHttpResponse(__namedParameters
: object):
Returns:
▸ createLoggingInterceptor(__namedParameters
: object):
Returns:
▸ createRedirectionInterceptor(__namedParameters
: object):
Returns:
▸ createSimpleServer():
Returns:
Content-Type: = ContentType.JSON
▸ encodeArrayBuffer(data
: | string | undefined, encoding
: ): Uint8Array‹›
▸ fetchRequestHandler(fetchRequestHandlerOptions
: ):
Creates a new that uses underneath. Does not support timeout property. Abort is possible only after headers were received.
Returns:
▸ getCaseConverter(bodyCasing?
: ): toCamelCase
▸ getEncodingFromHeaders(headers
: | undefined, fallback
: string): string
▸ getFileMeta(value
: Blob | Readable, existingMeta?
: ): object | object
▸ getHeader(headers
: | undefined, header
: string): string | undefined
▸ handleRequest(code
: number, body
: any, contentType
: string): Promise‹›
Returns: Promise‹›
▸ httpRequestHandler(requestHandlerOptions
: ):
Creates a new that uses native Node.js & modules underneath. Does not support mode property.
Returns:
▸ isHttpInterceptorInterface(interceptor
: ): interceptor is HttpInterceptorInterface
▸ mockRequestHandler(mockOptions
: ):
Returns:
▸ switchContentType<T>(contentType
: string, map
: ‹T›, defaultResult
: T): T
▸ switchContentType<T>(contentType
: string, map
: ‹T›): T | undefined
▸ useInterceptor(normalizedOptions
: ): (Anonymous function)
▸ xhrRequestHandler(_?
: ):
Returns:
• defaultHeaders:
• toUrlEncoded:
+ new HttpClient(config
: ‹T›):
Returns:
▸ addInterceptor(interceptor
: ): this
▸ delete<Body>(uri
: string, options?
: ): Promise‹‹Body››
Returns: Promise‹‹Body››
▸ get<Body>(uri
: string, options?
: ): Promise‹‹Body››
Returns: Promise‹‹Body››
▸ patch<Body>(uri
: string, options?
: ): Promise‹‹Body››
Returns: Promise‹‹Body››
▸ post<Body>(uri
: string, options?
: ): Promise‹‹Body››
Returns: Promise‹‹Body››
▸ put<Body>(uri
: string, options?
: ): Promise‹‹Body››
Returns: Promise‹‹Body››
▸ remove<Body>(uri
: string, options?
: ): Promise‹‹any››
Returns: Promise‹‹any››
▸ request<Body>(url
: string, options
: ): Promise‹‹Body››
Returns: Promise‹‹Body››
+ new HttpRequestError(options
: , message?
: undefined | string):
Returns:
Inherited from .
Inherited from .
• options:
Inherited from .
Overrides .
headers & multipart requests: reworked header merging mechanism ()
headers: fixed header merging in fetch requesthandler ()
multipart upload: tested multipart upload on all request handlers ()
http: bodyparser & bodyserializer support for multipart and formdata ()
oauth2interceptor: token-type can be optional ()
timeout support: full timeout support for all request handlers ()
types: properly arranged types for typescript<3.7 ()
clean: clean should not remove node_modules ()
typings: using downlevel-dts to bring back TS<3.7 support ()
build: removed redundant setup file ()
request-handlers: all request handlers are available from bindings ()
url-encoding: url string should override query passed in object ()
case-conversion: body casing enum has now string names ()
http-module: exposed request-handlers separately ()
query-string-options: one can configure query string options ()
redirection-interceptor: built-in support for redirections ()
redirections: redirection support ()
encoding: fix for invalid body encoding issue ()
http-request-handler: removed duplicated helpers ()
http-request-handler: moved to a separate package ()
json-api: added withId functionality to post builder ()
http: fix for headers being overwritten ()
http: body cache fix ()
http-request-handler: fix for node.js path/query support ()
http: native request handler for node.js ()
auth-interceptor: class-based queue & auth-interceptor ()
auth-interceptor: initial implementation of auth interceptor ()
http-interceptors: built-in error interceptor ()
http-interceptors: built-in logging interceptor ()
github actions: fixed invalid path ()
action: workspace fix ()
release: retry npm publish ()
token: use regular token ()
release: combine publishing in one flow ()
release: separate tag from publish ()
build: build & vulnerability fix ()
release: added git credentials ()
release: invalid command args ()
workflow: yet another release fix ()
workflows: run release with yarn, but use npm underneath ()
build: build & vulnerability fix ()
dependencies: dependency update ()
dependency: dependency fixes ()
json-api: new syntax for passing multiple square-bracketed keys to filter in json api ()
Then, our httpClient
uses fetchRequestHandler
to deal with HTTP requests, in order to use Fetch API as request handler. Each requestHandler
in coolio acts as a bridge between natively available mechanisms (such as , or module available in Node.js) and . Such Raw response has to be further processed by bodyParser
. BodyParser and BodySerializer automatically handle most common body types, such as JSON, URL-encoded, plain text, multipart and raw (for binary uploads). As a result we get a nicely processed , which lets us get response body, headers and status code of a response.
You can find all options directly in API docs.
httpClient
allows you to perform requests using all basic http methods. See to check what can be passed there.
See docs for details.
response
RawHttpResponse
rawResponse
RawHttpResponse
request
object
any
request
HttpFetch‹Body›
options
NormalizedHttpOptions
requestOptions
NormalizedHttpOptions
bodyCasing
undefined | CAMEL_CASE | SNAKE_CASE | SCREAMING_SNAKE_CASE | PASCAL_CASE | KEBAB_CASE
customCaseConverter
undefined | function
defaultParser
bodyCasing
undefined | CAMEL_CASE | SNAKE_CASE | SCREAMING_SNAKE_CASE | PASCAL_CASE | KEBAB_CASE
parsedBody
a promise function returning parsed body, which in most cases can be called only once
body
undefined | string | Uint8Array‹› | Uint8ClampedArray‹› | Uint16Array‹› | Uint32Array‹› | Int8Array‹› | Int16Array‹› | Int32Array‹› | Float32Array‹› | Float64Array‹›
-
bodyParserOptions
BodyParserOptions
-
headers
undefined | object
-
status
number
-
url
string
""
logger
function
redirectionLimit
number
30
key
string
_host
string
""
data
TypedArray | string | undefined
""
encoding
"utf8"
buffer
ArrayBuffer
-
encoding
string
"utf8"
fetchRequestHandlerOptions
FetchRequestHandlerOptions
{}
default Fetch API options attached to all requests
header
string[]
bodyCasing?
BodyCasing
headers
HttpResponseHeaders | undefined
-
fallback
string
"utf8"
value
Blob | Readable
existingMeta?
CFormDataEntryMetadata
headers
HttpHeaders | undefined
header
string
url
string
code
number
-
body
any
-
contentType
string
ContentType.TEXT
requestHandlerOptions
HttpRequestHandlerOptions
{}
default native options attached to all requests
value
any
value
any
interceptor
error
any
error
any
mockOptions
MockOptions
object
any
headers
Headers
body
string
boundary
string
blob
Blob
...multipleHeaders
undefined | object[]
ms
number
text
string
contentType
string
map
defaultResult
T
contentType
string
map
object
any
object
any
object
any
object
any
object
any
obj
object
sourceUrl
string
sourceQuery?
undefined | object
options?
qs.IStringifyOptions
value
string
options?
qs.IParseOptions
url
string
options?
qs.IParseOptions
value
any
options?
qs.IStringifyOptions
normalizedOptions
NormalizedHttpOptions
_?
XhrRequestHandlerOptions
config
interceptor
Interceptor that will process every request/response in this HttpClient.
uri
string
Address of HTTP endpoint
options?
Additional HttpOptions passed with request
uri
string
Address of HTTP endpoint
options?
Additional HttpOptions passed with request
uri
string
Address of HTTP endpoint
options?
Additional HttpOptions passed with request
uri
string
Address of HTTP endpoint
options?
Additional HttpOptions passed with request
uri
string
Address of HTTP endpoint
options?
Additional HttpOptions passed with request
uri
string
Address of HTTP endpoint
options?
Additional HttpOptions passed with request
url
string
options
Package
Description
Auth Interceptor with OAuth2 refresh token support for @coolio/http
HTTP networking client
JSON API client
options
message?
undefined | string
JSON API Client Wrapper
Add the JSON API package, assuming that you already have @coolio/http
installed:
Declare httpClient
as described in @coolio/http's README.md and then build JSON API Client:
Make sure that httpClient uses standard bodyParser
or a parser that returns complete body of server's response (an object including at least data
property).
An instance of JsonApiClient
exposes a collection of get()
, getList()
, post()
, remove()
, put()
and patch()
methods. Each method returns a request builder. For example:
UsersRepository.getUsers()
method presented above returns a Promise<JsonListResponse<UserAttributes, UserRelationships>>
. @coolio/json-api
merges attributes and relationships automatically.
Auth interceptor can be plugged in to a HttpClient to ensure passing proper authorization data to all requests and automatically refresh the tokens when they expire. You can configure whether authorization is done by body, header or query param, you can define your own refresh mechanism or use some ready-made, commonly used options.
Add the Auth Interceptor package, assuming that you already have @coolio/http
installed:
Declare httpClient
as described in @coolio/http's README.md and then use createAuthInterceptor
, passing all parameters required by options
object. authInterceptor
itself may also make it's own calls (via reauthorize
function), so you may need to create another HttpClient
, which won't interfere with your basic HttpClient
's interceptors. See the Usage section for complete example.
Now each request directed to my-domain.org
has a proper Authorization
header. In case of 401
response, all requests are paused and token refresh happens. When token is fresh, all requests are resumed. The whole process is transparent and doesn't affect calls.
If you're using OAuth2 authentication mechanisms, you can use an interceptor pre-made specifically for that case. See an example below:
AuthError
AuthInterceptor
InMemoryAuthStorage
SimpleQueue
AuthInterceptorOptions
AuthStorage
OAuth2InterceptorOptions
OAuth2TokenResponse
Ƭ Promisable: T | Promise‹T›
Ƭ QueueItem: object
fail(): function
(reason
: any): void
run(): function
(): Promise‹void›
Const
createAuthInterceptor▸ createAuthInterceptor(options
: AuthInterceptorOptions): AuthInterceptor‹›
Parameters:
Name
Type
options
Returns: AuthInterceptor‹›
Const
createOAuth2Interceptor▸ createOAuth2Interceptor(__namedParameters
: object): AuthInterceptor‹›
Parameters:
▪ __namedParameters: object
Name
Type
authStorage
canAuthorize
function
oauth
object
onAuthorizationFailure
function
Returns: AuthInterceptor‹›
Const
hasUnauthorizedResponseCode▸ hasUnauthorizedResponseCode(response
: HttpResponse): boolean
Parameters:
Name
Type
response
HttpResponse
Returns: boolean
Const
isUnauthorizedError▸ isUnauthorizedError(error
: any): boolean
Parameters:
Name
Type
error
any
Returns: boolean
SortOrder
CreationalRequestBuilder
JsonApiClient
JsonApiManySender
JsonApiOneSender
JsonApiRequestData
JsonApiSender
JsonListResponse
JsonResponse
RequestBuilder
Attributes
Data
IncludedGroup
ListMetaData
RawListResponse
RawResponse
RequestBuilderOptions
Ƭ AnyData: Data‹any, any›
Ƭ AttributesOf: D extends object ? D["attributes"] : EmptyRecord
Ƭ EmptyRecord: object
[ key: string]: never
Ƭ IncludedGroups: object
Ƭ IncludedGroupsSchema: Record‹string, IncludedGroup›
Ƭ IncludedRelationships: D[]
Ƭ MergedData:
This sophisticated type allows to correctly infer nicely formatted data from JSON API format. id
, type
, attributes
and relationships
suddenly become a single, combined object with easy access to it. Same is applied to arrays.
Ƭ MergedIncludedGroups: object
Ƭ OptionalRels: Relationships | undefined
Ƭ RawRelationship: object
data: T
links? : undefined | object
related? : undefined | string
Ƭ Relationship: RawRelationship‹RelationshipData›
Ƭ RelationshipArray: RawRelationship‹RelationshipData[]›
Ƭ RelationshipData: object
id: string
type: Type
Ƭ RelationshipType: RelationshipData‹Type› | RelationshipData‹Type›[]
Ƭ Relationships: Record‹string, RawRelationship‹RelationshipType› | undefined›
Ƭ RelationshipsOf: D extends object ? D["relationships"] : EmptyRecord
Ƭ ResolvedRelationship: RawRelationship‹D›
Ƭ ResolvedRelationshipArray: RawRelationship‹D[]›
Ƭ ResolvedRelationships: Record‹string, ResolvedRelationship | ResolvedRelationshipArray | undefined›
Ƭ UnresolvedRelationships: Record‹string, Relationship | RelationshipArray›
Const
DEFAULT_RESOURCE_LIMIT• DEFAULT_RESOURCE_LIMIT: 10 = 10
Const
findIncludedRelationship▸ findIncludedRelationship(relationship
: RelationshipData, included
: IncludedRelationships): AnyData | undefined
Parameters:
Name
Type
relationship
included
Returns: AnyData | undefined
Const
includedGroup▸ includedGroup<D>(type
: string): IncludedGroup‹D›
Type parameters:
▪ D: AnyData
Parameters:
Name
Type
type
string
Returns: IncludedGroup‹D›
Const
isData▸ isData<D>(data
: RelationshipData | D): data is D
Type parameters:
▪ D: AnyData
Parameters:
Name
Type
data
Returns: data is D
Const
mergeElementData▸ mergeElementData<D>(data
: D): MergedData‹D›
Type parameters:
▪ D: AnyData
Parameters:
Name
Type
data
D
Returns: MergedData‹D›
▸ resolveRelationships<D>(data
: D, included
: IncludedRelationships): D
Type parameters:
Parameters:
Name
Type
data
D
included
Returns: D
▸ resolveRelationships(data
: RelationshipData[], included
: IncludedRelationships): object | Data‹any, any›[]
Parameters:
Name
Type
data
included
Returns: object | Data‹any, any›[]
▸ resolveRelationships(data
: RelationshipData, included
: IncludedRelationships): AnyData | RelationshipData
Parameters:
Name
Type
data
included
Returns: AnyData | RelationshipData
Const
Headers• Accept: ContentType = ContentType.VND_JSON
• Content-Type: ContentType = ContentType.VND_JSON
HttpResponseHeaders
+ new HttpResponseHeaders(headers
: IncomingHttpHeaders | HttpHeaders | Headers | string): HttpResponseHeaders
Parameters:
headers
{}
Returns: HttpResponseHeaders
• map: Record‹string, string›
▸ get(key
: string): undefined | string
Parameters:
key
string
Returns: undefined | string
▸ set(key
: string, value
: any): void
Parameters:
key
string
value
any
Returns: void
▪ T
↳ HttpResponseError
+ new HttpResponseError(response
: HttpResponse‹T›, message?
: undefined | string): HttpResponseError
Parameters:
response
message?
undefined | string
Returns: HttpResponseError
• message: string
Inherited from HttpRequestError.message
• name: string
Inherited from HttpRequestError.name
• response: HttpResponse‹T›
Optional
stack• stack? : undefined | string
Inherited from HttpRequestError.stack
Overrides HttpRequestError.stack
• status: HttpCode
Static
Error▪ Error: ErrorConstructor
Quite often we need to do something "in-between" while our API requests are running. This is why we have a built-in interceptors mechanism. Interceptors allow us to :
perform actions before request happens,
perform actions after request happens,
retry the request multiple times,
even totally ignore the request and serve content in a different way (i.e. serve content from in-memory cache).
Common use-cases for interceptors:
throw errors if response status code indicates that request failed,
automagically retry request up to X times if it failed,
transparently reauthorize if your access token has been revoked
The concept of interceptors should sound familiar to you if you ever used Angular or OkHttp.
One can add interceptor to HttpClient
using addInterceptor
method. addInterceptor
can be chained and it mutates the httpClient, so you can define a client as below.
coolio offers some basic interceptors, which you probably want to add right away.
Interceptor
Purpose
Import
Logger
Logs out requests, responses and errors.
import { createLoggerInterceptor } from '@coolio/http`;
Error Handler
import { createErrorInterceptor } from '@coolio/http';
Redirection Handler
Follows redirections, when response contains 301 status code.
import { createRedirectionInterceptor } from '@coolio/http';
Auth
Handles Authorization and reauthenticates automatically when it's needed.
import { createAuthInterceptor } from '@coolio/auth-interceptor';
OAuth
AuthInterceptor following OAuth2 specs. Your job is to provide a storage for tokens only.
import { createOAuth2Interceptor } from '@coolio/auth-interceptor';
coolio supports two ways of creating interceptors. One is a function-based approach and second is a class-based approach. Both ways are correct, just use what fits your use-case best.
Interceptors accept two arguments:
request: HttpFetch
- a function that returns a Promise that performs http request. It allows to queue or delay multiple requests, retry them etc.
options: NormalizedHttpOptions
- options that can be modified before request is made, i.e. you can add Authorization
header in your authInterceptor
.
See the example of error interceptor created as a function:
Interceptor has to return async function that returns response. In other words, it can either:
just return request, which is passed as a first argument to interceptor
create an async function, which performs some operations and then returns response
In the above case, we create such function manually and check the response status code, throwing an error when something goes wrong.
If we'd like to create an interceptor as a class, it would look like that:
By exploiting the fact, that we return a function in our interceptor, we can implement retry mechanism, embed a queue and more. You can see some examples in coolio's auth-interceptor source code.
‹›
| D
[]
IncomingHttpHeaders | | Headers | string
‹T›
Throws when response contains 4xx/5xx status code.