@devicious/fetchy
v0.2.1
Published
A library that adds super powers to native fetch implementation
Downloads
34
Maintainers
Readme
#Fetchy
The Fetchy class represent an handy and configurable helper that allows to easily interact with remote resources.
Any instance can be configured in many different aspects while enforcing use of correct configuration. Leveraging its functionalities it's easy to generate pre-configured instances of any given remote resource, and easily query them with cool features like: automatic error handling, caching, timeouts, etc.
Installation
Using npm:
$ npm i @devicious/fetchy
How to use it:
//Import the Library
import Fetchy from "@devicious/fetchy"
//Define and configure a new instance of a Fetchy Class
const Authors = new Fetchy("/api/v1/authors")
.method('POST')
.cache(true)
.id('articles')
.expiry(1);
//Further edit the configuration and fire the request.
Authors
.data({
parameter1: 'value1',
parameter2: 'value2'
})
.then((results) => {
console.log(results);
});
//Execute another call with different parameters (caching won't affect the results since the payload has changed)
Authors
.data({
parameter4: 123,
parameter6: false
})
.then((results) => {
console.log(results);
})
.catch((error) => {
console.log(error);
});
Docs
Constructors
Internal Properties
Other Properties
Methods
- attachSelf
- cache
- call
- catch
- clearCache
- clone
- credentials
- data
- do
- expiry
- finally
- format
- formatResponse
- getCacheHash
- headers
- id
- isCached
- isInQueue
- method
- mode
- override
- refreshCacheStorage
- retrieveCached
- retry
- setQueue
- storeCached
- then
- timeout
- validator
Constructors
constructor
• new Fetchy(url
)
Basic usage (GET):
const Resource = new Fetchy("/api/v1/:endpoint");
Resource.then((data) => {
//...
});
Parameters
| Name | Type |
| :------ | :------ |
| url
| string
|
Defined in
Internal Properties
writable
• Private
writable: boolean
= true
The properties of a Fetchy instance are mutable up until the first fetch. From that moment only the payload data can be mutated, in order to prevent consistency issues.
Defined in
Other Properties
cacheQueueRetries
• Private
Readonly
cacheQueueRetries: 40
Internal use only.
internal
Defined in
cacheQueueUID
• Private
Readonly
cacheQueueUID: "_cacheResponseQueue"
Internal use only.
internal
Defined in
cacheStorage
• Private
cacheStorage: Object
= {}
This variable handles the internal caching storage.
internal
Defined in
cacheUID
• Private
Readonly
cacheUID: "_cacheResponseData"
Internal use only.
internal
Defined in
config
• Private
config: FetchyConfig
This variable represents the internal state of a Fetchy instance. It mutates while you configure your instance, and it's inherited from its child.
internal
Defined in
Methods
attachSelf
▸ Private
attachSelf(response
): any
internal
Parameters
| Name | Type |
| :------ | :------ |
| response
| any
|
Returns
any
Defined in
cache
▸ cache(enable
): Fetchy
Enable or disable automatic caching for the current Fetchy instance. Caching is performed automatically when enabled based on the current set of parameters, and automatically handling configuration changes. Any change in the configuration or data payload will generate new calls instead of fetching from the cache.
cache
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| enable
| boolean
| true | false |
Returns
the Fetchy class instance
Defined in
call
▸ Private
call(): Promise
<Response
>
internal
Returns
Promise
<Response
>
Defined in
catch
▸ catch(fn
): any
Triggers the data fetch and returns the final payload. After this method is invoked is no longer possible to change this instance configuration without cloning it.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| fn
| Function
| A callback function that is invoked with the result of the fetch in case of error |
Returns
any
a mutated version of Fetchy class instance that inherits all the properties of a Promise.
Defined in
clearCache
▸ clearCache(id?
): void
Allows to clear the cached entries of a specific id or in general.
cache
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| id?
| string
| The id of the cached entity. *optional |
Returns
void
Defined in
clone
▸ clone(): Fetchy
Clones the current instance into a new one, allowing for configuration changes without affecting the original instance.
utility
Returns
a new clone of Fetchy class instance that inherits all previous configurations.
Defined in
credentials
▸ credentials(credentials
): Fetchy
Sets the credential mode for the current Fetch instance.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| credentials
| string
| Allowed values: 'omit', 'same-origin', 'include' |
Returns
the Fetchy class instance
Defined in
data
▸ data(data
): Fetchy
Allows to set request payload.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| data
| any
| Allowed formats: Object, Array, String. |
Returns
a new clone of Fetchy class instance that inherits all previous configurations.
Defined in
do
▸ Private
do(): any
internal
Returns
any
Defined in
expiry
▸ expiry(minutes
): Fetchy
Sets a time in minutes after which any cached request will be discarded and substituted with a fresh data fetch.
cache
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| minutes
| number
| Timing expressed in minutes |
Returns
the Fetchy class instance
Defined in
finally
▸ finally(fn
): any
Triggers the data fetch and returns the final payload. After this method is invoked is no longer possible to change this instance configuration without cloning it.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| fn
| Function
| A callback function that is invoked with the result of the fetch in either case |
Returns
any
a mutated version of Fetchy class instance that inherits all the properties of a Promise.
Defined in
format
▸ format(format
): Fetchy
Allows to set fetch expected response format
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| format
| string
| Allowed values: 'json', 'text', 'blob' |
Returns
the Fetchy class instance
Defined in
formatResponse
▸ Private
formatResponse(metaResponse
): any
internal
Parameters
| Name | Type |
| :------ | :------ |
| metaResponse
| any
|
Returns
any
Defined in
getCacheHash
▸ Private
getCacheHash(): string
internal
Returns
string
Defined in
headers
▸ headers(headers
): Fetchy
Allows to set headers for the fetch call.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| headers
| any
| Allowed values Array, Object |
Returns
the Fetchy class instance
Defined in
id
▸ id(id
): Fetchy
Sets a unique id for the current Fetch instance, allowing more clear and debug friendly caching
cache
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| id
| string
| Allowed values: Any unique string |
Returns
the Fetchy class instance
Defined in
isCached
▸ Private
isCached(): boolean
internal
Returns
boolean
Defined in
isInQueue
▸ Private
isInQueue(): boolean
internal
Returns
boolean
Defined in
method
▸ method(method
): Fetchy
Allows to set a method for the fetch call.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| method
| string
| Allowed values: 'GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS' |
Returns
the Fetchy class instance
Defined in
mode
▸ mode(mode
): Fetchy
Sets a mode for the current Fetch instance to handle CORS issues
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| mode
| string
| Allowed values: 'cors', 'same-origin', 'no-cors' |
Returns
the Fetchy class instance
Defined in
override
▸ override(config
): Fetchy
Override the current configuration of the Fetchy instance without format restrictions, should not be used.
internal
Parameters
| Name | Type |
| :------ | :------ |
| config
| any
|
Returns
a new clone of Fetchy class instance that inherits all previous configurations.
Defined in
refreshCacheStorage
▸ Private
refreshCacheStorage(): void
internal
Returns
void
Defined in
retrieveCached
▸ Private
retrieveCached(): Promise
<unknown
>
internal
Returns
Promise
<unknown
>
Defined in
retry
▸ retry(times
, delayMs?
): Fetchy
Allows to set automatic retries in case of fetch failure.
errorhandling
Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| times
| number
| undefined
| Number of times to retry before considering failed the request |
| delayMs
| number
| 0
| Time to wait between each try, expressed in ms. |
Returns
the Fetchy class instance
Defined in
setQueue
▸ Private
setQueue(): void
internal
Returns
void
Defined in
storeCached
▸ Private
storeCached(response
): void
internal
Parameters
| Name | Type |
| :------ | :------ |
| response
| any
|
Returns
void
Defined in
then
▸ then(fn
): any
Triggers the data fetch and returns the final payload. After this method is invoked is no longer possible to change this instance configuration without cloning it.
request
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| fn
| Function
| A callback function that is invoked with the result of the fetch in case of success |
Returns
any
a mutated version of Fetchy class instance that inherits all the properties of a Promise.
Defined in
timeout
▸ timeout(seconds
): Fetchy
Allows to set fetch timeout in seconds.
errorhandling
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| seconds
| number
| Must be a value equal or greater than 1 |
Returns
the Fetchy class instance
Defined in
validator
▸ validator(fn
): Fetchy
Sets a validator function to allow or forbid caching of any request coming from this instance. The cache is common among all Fetchy instances Defaults to Ensure that the response is not empty and with status code 200.
cache
Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| fn
| any
| Allowed values: 'cors', 'same-origin', 'no-cors' |
Returns
the Fetchy class instance Example validator function:
const Helper = new Fetchy("/api/v1/:endpoint")
.cache(true) //Caching must be enabled for validator function to take any effect.
.validator((response) => {
return response && response.header.status === "OK";
});