1.0.1 • Published 3 years ago

starless-http v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

Starless Http Client

Promise based HTTP client for the browser and node.js with additional utils.

Installing

npm i starless-http

Example

Performing a GET request

const httpClient = require("starless-http").default;

// Make a request for a user with a given ID
httpClient.get("/user?ID=12345").then(function ([response, error]) {
  console.log(response);
  console.log(error);
});

// Optionally the request above could also be done as
httpClient
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function ([response, error]) {
    console.log(response);
    console.log(error);
  });

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  const [response, error] = await httpClient.get("/user?ID=12345");
  console.log(response);
  console.error(error);
}

Performing a POST request

httpClient
  .post("/user", {
    firstName: "Fred",
    lastName: "Flintstone",
  })
  .then(function ([response, error]) {
    console.log(response);
    console.log(error);
  });

Retry Request

Sometime we want to retry when request is failed.

async function main() {
  const [response, error] = await httpClient.get(
    "/users",
    {},
    {
      retry: 3,
      retryDelay: 3000,
      retryWhen: (res) => !res || res.status >= 400,
    }
  );
}

main();

Interval Request

You can call request like heartbeat with interval options.

async function main() {
  const [response, error] = await httpClient.get(
    "/users",
    {},
    {
      interval: 3000, // 3 seconds
      requestUntil: (res) => res.status == 200, // will stop interval when callback return true
    }
  );
}

main();