npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

scratch-fetch

v1.1.1

Published

JavaScript FetchAPI library.

Downloads

65

Readme

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

| Name | Type | Default value | | :------------: | :------------: | :------------: | | url | string | undefined | | headers | {} | "Accept": "application/json" "Content-Type": "application/json" | | body | any | undefined | | configuration | IHttpRequestInitConfiguration | undefined |

IHttpRequestInitConfiguration

| Name | Type | Default value | | :------------: | :------------: | :------------: | | useDefaultHeaders | boolean | true | | stringifyBody | boolean | true | | allowMultiple | boolean | false | | credentials | RequestCredentials | "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

| Name | Arguments | Returned value type | | :------------: | :------------: | :------------: | | url | none (getter) | string | | headers | none (getter) | {} | | body | none (getter) | any | | withUrl | value: string | IHttpRequest | | withHeaders | value: {} | IHttpRequest | | withBody | value: any | IHttpRequest | | addHeaders | value: {} | undefined (void) | | patchHeaders | value: {} | undefined (void) | | removeHeader | key: string | boolean | | execute | - | Promise<HttpResponse> | | abort | - | undefined (void) |

HttpResponse

| Name | Type | | :------------: | :------------: | | ok | boolean | | status | number? | | isAborted | boolean | | value | any | | error | {} |