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

axios-request-builder

v0.1.2

Published

A ~100-lines module to build Axios requests using chainable properties

Downloads

8

Readme

Axios Request Builder

A ~100-lines module to build Axios requests using chainable "magic" properties.

import axios from "axios";
import RequestBuilder from "axios-request-builder";

// Create an Axios instance with some default config
const client = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/",
});

// Create a builder
const api = new RequestBuilder(client);

// 1. A simple GET request
// GET /users/1/todos?completed=true
api.users.$(1).todos
  .get({
    completed: true,
  })
  .then(({ data }) => {
    console.log(data);
  });

// 2. Every next property returns a new Builder
const users = api.users;
const firstUser = users.$(1);
// GET /users
users.get();
// PATCH /users/1
firstUser.patch({ name: "Sammy" });

// 3. Every endpoint can have a different config
const allTodos = api.todos;
const completedTodos = api.todos.config({
  params: {
    completed: true,
  },
});
// GET /todos
allTodos.get();
// GET /todos?completed=true
completedTodos.get();

Installing

Install the package:

$ npm i axios-request-builder

Import Axios and the builder:

import axios from "axios";
import RequestBuilder from "axios-request-builder";

Create an Axios instance and pass to the RequestBuilder constructor:

const client = axios.create({
  baseURL: "https://api.example.com",
});

const req = new RequestBuilder(client);

Building Requests

Build a request URL using chainable properties:

// GET /this/is/magic
req.this.is.magic.get();

You can parameterize the URL with a special method $:

const userId = 10;
// GET /users/10/todos
req.users.$(userId).todos.get();

Send the request with method aliases:

req.get([params])
req.post(data[, params])
req.put(data[, params])
req.patch(data[, params])
req.delete([params])

Behind the scenes the builder calls the corresponding Axios method aliases and returns the resulting Promise which will resolve with the Axios response object or reject with an error.

req.users.
  .get()
  .then(({ data, status }) => {
    // Handle response
  })
  .catch((error) => {
    // Handle errors
  });

// OR

try {
  const { data, status } = await req.users.get();
  // Handle response
}
catch (error) {
  // Handle errors
}

Request Config

You can add an individual Axios request config to every request:

const posts = req.posts.config({
  params: { limit: 10 }
});
// GET /posts?limit=10
posts.get();

You can call config() multiple times on the same request instance to extend or change the config.

Configs get inherited:

// GET /posts/archive?limit=10
posts.archive.get()

But can be overridden:

// GET /posts/archive?limit=15
posts.archive.get({ limit: 15 })

// OR

const archive = posts.archive.config({
  params: { limit: 15 }
})
// GET /posts/archive?limit=15
archive.get()

When request is dispatched its config is merged with the default config of the provided Axios instance.

There are several config shortcuts for the most commonly used options:

headers()

req.headers({
  'X-Custom-Header': 'foobar'
});
// is the same as
req.config({
  headers: {
    'X-Custom-Header': 'foobar'
  }
});

params()

req.params({
  'foo': 'bar'
});
// is the same as
req.config({
  params: {
    'foo': 'bar'
  }
});

transform()

req.transform(function (data, headers) {
  return data;
});
// is the same as
req.config({
  transformResponse: [function (data, headers) {
    return data; 
  }]
});

signal()

const controller = new AbortController();

req.signal(controller.signal);
// is the same as
req.config({
  signal: controller.signal
});

Abort Controller

The builder has a helper method createSignal() for creating abort controllers:

const post = req.posts.$(1);
// Create an abort controller and set the signal in one line
const controller = post.createSignal();

// Dispatch the request
post.get();
// And abort it
controller.abort();