1.1.1 • Published 4 years ago

scratch-fetch v1.1.1

Weekly downloads
4
License
MIT
Repository
github
Last release
4 years ago

What is this?

This is a JavaScript FetchAPI library.

How to use

1. Install package

npm install scratch-fetch --save

2. Import module

1. ES5 or earlier

require("scratch-fetch");

2. ES6

import { httpGet, httpPost, httpPut, httpDelete } from "scratch-fetch";

3. Set up your request

You can use either constructor or methods to set up your request.

By constructor:

const response = await httpPost({
                        url: "https://localhost:8080/api/hello",
                        headers: {
                            "KEY_0": "VALUE",
                            "KEY_1": "VALUE"
                        },
                        body: {
                            "key": "value"
                        }
                    }).execute();

By methods

const response = await httpPost()
                        .withUrl("https://localhost:8080/api/hello")
                        .withHeaders({
                            "KEY_0": "VALUE",
                            "KEY_1": "VALUE"
                        }).
                        withBody({
                            "key": "value"
                        }).execute();
  • By default, the request contains "Accept": "application/json" and "Content-Type": "application/json" headers. If you wish to remove default headers, you can set the useDefaultHeaders property in configuration to false when initializing the request. (in constructor)
  • The body of a request will be stringified automatically. If you wish to keep your request body raw, you can set the stringifyBody property in configuration to false when initializing the request. (in constructor)

For example,

const response = await httpGet({
                        url: "https://localhost:8080/api/hello",
                        configuration: {
                            useDefaultHeaders: false, // <- Remove default headers.
                            stringifyBody: false // <- Keep request body raw.
                        }
                    }).execute();

You can reuse a request object multiple times. If you want to change the url of the request (for most cases, we want to change route parameters or query parameters), then you can call the withUrl method at any time to achieve this aim.

For example,

const requests = {
  fetchData: httpGet()
};

async function fetchMyData() {
  const queryString = ""; // queryString may be different every time you call this function.
  const response = requests.fetchData
                          .withUrl(`https://localhost:8080/api/hello?${queryString}`)
                          .execute();
}

scratch-fetch also offers you a function to build query string. To use this function, we have to import it from the module.

1. ES5 or earlier

var buildQueryString = require("scratch-fetch").buildQueryString;

2. ES6

import { buildQueryString } from "scratch-fetch";

Then you can use this function to build your query string.

For example,

const params = {
  page: 5,
  size: 20
};
const queryString = buildQueryString(params); // queryString will be "page=5&size=20", WITHOUT the leading question mark.

4. Get response and handle errors

const response = await httpGet({ url: "https://localhost:8080/api/hello" }).execute();
if (response.ok) {
    console.log(response.value); // "value" is already converted to json object.
}
else if (!response.isAborted) {
    // Handle error here
    console.error(response.error);
}

What do I do if I want to abort a request?

You can call the abort method to abort a request.

For example,

const requests = {
    fetchData: httpGet(),
    updateData: httpPut()
};

// Set up requests
const response = requests.updateData
                        .withUrl("https://localhost:8080/api/hello")
                        .withBody({ "key": "value" })
                        .execute();

// Then somewhere in your code
requests.updateData.abort();
  • If a request is already done (that means you have received the value of response), then the abort method will not do anything.
  • You can handle abort error by checking the isAborted property in the response.

5. API References

1. Constructor

NameTypeDefault value
urlstringundefined
headers{}"Accept": "application/json" "Content-Type": "application/json"
bodyanyundefined
configurationIHttpRequestInitConfigurationundefined
IHttpRequestInitConfiguration
NameTypeDefault value
useDefaultHeadersbooleantrue
stringifyBodybooleantrue
allowMultiplebooleanfalse
credentialsRequestCredentials"include"
  • The allowMultiple property is used to prevent a request from getting sent multiple times before the previous one is done. By default, this attribute is set to false. If you wish to remove this constraint, you can set it to true.
  • For more info about credentials property, please visit MDN Web Docs

2. Methods

NameArgumentsReturned value type
urlnone (getter)string
headersnone (getter){}
bodynone (getter)any
withUrlvalue: stringIHttpRequest
withHeadersvalue: {}IHttpRequest
withBodyvalue: anyIHttpRequest
addHeadersvalue: {}undefined (void)
patchHeadersvalue: {}undefined (void)
removeHeaderkey: stringboolean
execute-Promise<HttpResponse>
abort-undefined (void)
HttpResponse
NameType
okboolean
statusnumber?
isAbortedboolean
valueany
error{}
1.1.1

4 years ago

1.1.0

4 years ago

1.0.26

4 years ago

1.0.25

4 years ago

1.0.24

4 years ago

1.0.23

4 years ago

1.0.22

4 years ago

1.0.21

4 years ago

1.0.20

4 years ago

1.0.19

4 years ago

1.0.18

4 years ago

1.0.17

4 years ago

1.0.16

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.11

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.10

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago