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-url-template

v1.0.3

Published

Axios interceptor adding support for URL templates.

Downloads

399

Readme

axios-url-template

npm version Build status Coverage Status install size

This package adds support for URL templates to Axios, according to RFC 6570 URI Template specification.

It uses url-template package and wraps it into Axios interceptor.

Installation

$ npm install axios-url-template

or

$ yarn add axios-url-template

Usage

Importing library:

import { urlTemplateInterceptor } from "axios-url-template";

Attaching interceptor to Axios global instance:

axios.interceptors.request.use(urlTemplateInterceptor());

Passing options:

axios.interceptors.request.use(urlTemplateInterceptor({
  urlAsTemplate: false,
}));

Attaching interceptor to Axios instance

const instance = axios.create({ /* ... */});
instance.interceptors.request.use(urlTemplateInterceptor());

Example requests:

const response1 = await axios.get('/test/{id}', {
  urlTemplateParams: { id: 123 },
});
// config:
// {
//   url: '/test/123',
//   urlTemplate: '/test/{id}',
//   urlTemplateParams: { id: 123 }
// }

const response2 = await axios.get('/test{?foo,bar}', {
  urlTemplateParams: { foo: 'foo1', bar: 'bar1' },
});
// config:
// {
//   url: '/test?foo=foo1&bar=bar1',
//   urlTemplate: '/test{?foo,bar}',
//   urlTemplateParams: { foo: 'foo1', bar: 'bar1' },
// }

const response3 = await axios.request({
  urlTemplate: '/test/{id}',
  urlTemplateParams: { id: 123 },
});
// config:
// {
//   url: '/test/123',
//   urlTemplate: '/test/{id}',
//   urlTemplateParams: { id: 123 },
// }

Interceptor may be also registered using shortcut method:

import { useUrlTemplateInterceptor } from "axios-url-template";

useUrlTemplateInterceptor(axios);

const instance = axios.create({ /* ... */});
useUrlTemplateInterceptor(instance, { urlAsTemplate: false });

Options

  • urlAsTemplate: when set to true, then url is treated as template and possibly interpolated. When set to false it does not touch url unless urlTemplate is explicitly specified. Default: true.

Behavior

When urlTemplate (and optional urlTemplateParams) is provided in Axios config object, this interceptor uses it to generate url. Those template fields are persisted in config object, so after execution config will contain all of those fields:

  • url
  • urlTemplate
  • urlTemplateParams - when no parameter are provided it will be an empty object

When urlAsTemplate option is set to true (default), then url will be also treated as url template and passed through interpolation. In this case, urlTemplate and urlTemplateParams will be added accordingly, and url will be replaced with interpolated value, giving the same effect as for urlTemplate.

When no urlTemplate is provided and urlAsTemplate option is set to false then the interceptor passes request config without any changes.

Use cases

This interceptor helps to automate things like structural logging and/or request metrics, where low cardinality route is preferred over full URL with dynamic parts.

When request is performed in traditional way, there is no easy option to retrieve such route from full URL provided in call to Axios. It may be provided as custom fields, but it increases overhead and may generate mistakes.

The interceptor ensures consistency, as actual URL provided to Axios is computed from route (url template) and parameters.

Example (in TypeScript):

import axios, { AxiosResponse } from 'axios';
import { useUrlTemplateInterceptor } from "axios-url-template";

// example logging interceptor
function loggingInterceptor(response: AxiosResponse) {
  const { status, statusText } = response;
  const { urlTemplate, urlTemplateParams } = response.config;
  const url = axios.getUri(response.config);

  const logObject = {
    status,
    statusText,
    url,
    route: urlTemplate, // low cardinality value is preferred
    routeParams: urlTemplateParams, // dynamic route parts
  };

  // do something with such log object
  console.log(JSON.stringify(logObject, null, 2));
}

// attach url template interceptor
useUrlTemplateInterceptor(axios, { urlAsTemplate: true })

// attach logging interceptor
axios.interceptors.response.use(loggingInterceptor);

async function execute() {
  await axios.get("https://postman-echo.com/status/{status}", {
    urlTemplateParams: { status: 201 },
  });

  await axios.get("https://postman-echo.com/get{?foo,bar}", {
    urlTemplateParams: { foo: "foo1", bar: "bar1" },
    params: { baz: 'baz1' }, // additional param, not being part of route
  });
}
execute().catch(console.error);

Result:

{
  "status": 201,
  "statusText": "Created",
  "url": "https://postman-echo.com/status/201",
  "route": "https://postman-echo.com/status/{status}",
  "routeParams": {
    "status": 201
  }
}
{
  "status": 200,
  "statusText": "OK",
  "url": "https://postman-echo.com/get?foo=foo1&bar=bar1&baz=baz1",
  "route": "https://postman-echo.com/get{?foo,bar}",
  "routeParams": {
    "foo": "foo1",
    "bar": "bar1"
  }
}

License

MIT