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

dk-request

v3.4.5

Published

Request utility with validations based on Axios & ts-interface-checker

Downloads

45

Readme

Request utility with validations based on Axios & ts-interface-checker

coverage npm license size

[!WARNING]
It's fine if you use this library from NPM package with a static versioning in case you want it for some pet-project or to test it's capabilities.

But for production use it's strongly recommended to create a fork, because I do not write Changelogs and may break / add some functionality without notice.

Features

  • validates request and response by ts-interface-checker. Checkers could be created using dk-file-generator
  • omits extraneous params from response using dk-checker-remove-extraneous
  • supports mocks
  • supports file downloads if response type is blob with customizable file name
  • supports FormData requests
  • supports url as function
  • supports custom headers
  • works in Node.js
  • request params starting with omit_ are used in in url creation but omitted in body

Installation

Add dk-request to package.json and install.

Usage

import { AxiosError } from 'axios';
import { request, errors } from 'dk-request';

type TypeRequest = {
  id: string;
}

type TypeResponse = {
  data: string;
}

// possibly auto-generated
const validators = t.createCheckers({
  TypeRequest: t.iface([], { id: 'string' }),
  TypeResponse: t.iface([], { data: 'string' }),
});

request({
  url: 'https://google.com/api/get-items',
  // url: (requestParams) => `https://google.com/api/get-items/${requestParams.id}`,
  apiName: 'getItems',
  requestParams: { id: 'id' } as TypeRequest,
  validatorRequest: validators.TypeRequest,
  validatorResponse: validators.TypeResponse,
}).then((response: TypeResponse) => {
  // response is validated and cleared, put it in store or use as you need
  
  successHandler(response);
}).catch((error: Error | AxiosError) => {
  // if it's validation error then
  // error.name === errors.VALIDATION
  // error.message smth. like 
  // 'validateRequest: request.id is missing for "getItems"'
  // 'validateResponse: response.data is not a string for "getItems"'
  
  errorHandler(error);
});

Params

url - string | ((request: any) => string) - full url

apiName - string - just for logging

requestParams - Record<string, any> & { formData?: any; downloadAsFile?: boolean }

If you need to send FormData include it in formData. Other params will not be sent, but could still be used in url function.

If you need to download file passed as blob by backend use downloadAsFile: true, this way response validation will be omitted.

mock (optional) - TypeResponse, there will be no actual request to API, but validations are applied

method (optional, default POST) - 'GET' | 'POST' | 'PUT' | 'DELETE'

headers (optional) - Record<string, any>

extraneousLogger (optional) - logger for dk-checker-remove-extraneous

validatorRequest (optional) - Checker

validatorResponse (optional) - Checker

disableCredentials (optional) - boolean - restrict or allow sending of cookies along with request

omitResponseValidation (optional) - boolean - restrict or allow response validation

afterRequestInterceptor (optional) - (response: AxiosResponse) => Promise<void> - a method for performing some manipulations with response, like checking response.headers (ex. server sends JWT token in headers)

afterRequestInterceptor: (axiosResponse) => {
  const newToken = axiosResponse.headers.authorization;

  if (newToken) setTokenToStore(newToken);

  return Promise.resolve();
}

downloadFileNameGetter (optional) - (response: AxiosResponse) => string - a method for defining custom downloaded file name, ex.

downloadFileNameGetter: (axiosResponse) => {
  return (
    axiosResponse.headers['content-disposition']?.split('filename=')?.[1]?.replaceAll('"', '') ||
    'result.csv'
  );
}

For access to response headers like content-disposition don't forget expose-headers header in server response