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-rest-resource

v0.7.0

Published

Schema-based HTTP client powered by axios. Built with Typescript. Heavily inspired by AngularJS' $resource.

Downloads

502

Readme

axios-rest-resource Build Status

Schema-based HTTP client powered by axios. Built with Typescript. Heavily inspired by AngularJS' $resource.

Installation

npm i axios-rest-resource axios

Quick start

  • Create resource module in your utils folder

    // utils/resource.ts
    import { ResourceBuilder } from 'axios-rest-resource'
    
    export const resourceBuilder = new ResourceBuilder({
      baseURL: 'http://localhost:3000',
    })
  • Using a newly created resource builder create an actual resource

    // api/entity1.js
    import { resourceBuilder } from 'utils/resource'
    
    export const entity1Resource = resourceBuilder.build('/entity1')
    // exports an object
    // {
    //   create: (requestConfig) => axiosPromise // sends POST http://localhost:3000/entity1,
    //   read: (requestConfig) => axiosPromise // sends GET http://localhost:3000/entity1,
    //   readOne: (requestConfig) => axiosPromise // sends GET http://localhost:3000/entity1/{id},
    //   remove: (requestConfig) => axiosPromise // sends DELETE http://localhost:3000/entity1/{id},
    //   update: (requestConfig) => axiosPromise // sends PUT http://localhost:3000/entity1/{id}
    // }
  • Use your resource whenever you want to make an AJAX call

    import { entity1Resource } from 'api/entity1'
    
    const resRead = entity1Resource.read()
    // sends GET http://localhost:3000/entity1
    // resRead is a Promise of data received from the server
    
    const resReadOne = entity1Resource.readOne({ params: { id } })
    // for id = '123'
    // sends GET http://localhost:3000/entity1/123
    // resReadOne is a Promise of data received from the server
    
    const resCreate = entity1Resource.create({ data })
    // for data = { field1: 'test' }
    // sends POST http://localhost:3000/entity1 with body { field1: 'test' }
    // resCreate is a Promise of data received from the server
    
    const resUpdate = entity1Resource.update({ data, params: { id } })
    // for data = { field1: 'test' } and id = '123'
    // sends PUT http://localhost:3000/entity1/123 with body { field1: 'test' }
    // resUpdate is a Promise of data received from the server
    
    const resRemove = entity1Resource.remove({ params: { id } })
    // for id = '123'
    // sends DELETE http://localhost:3000/entity1/123
    // resRemove is a Promise of data received from the server

URL token substituion

axios-rest-resource applies interceptorUrlFormatter interceptor by default. It handles {token} substitution in URLs.

Method Interface Customization

You can customize the interface of your resource methods using withParams and withResult. These allow you to define type-safe parameter handling and response transformation, making your API calls more intuitive and type-safe.

Note: These are different from axios's built-in transformRequest and transformResponse. While axios's transforms modify the request/response data internally, our withParams and withResult change the method's interface - how you call it and what it returns.

// api/users.ts
import { resourceBuilder } from 'utils/resource'

interface User {
  id: number
  email: string
}

interface SignInResponse {
  token: string
  user: User
}

export const usersResource = resourceBuilder.build('/users', {
  signIn: {
    method: 'post',
    url: '/sign_in',
    // Define method parameters and how they map to request config
    withParams: (email: string, password: string) => ({
      data: { email, password },
      headers: { 'X-Custom': 'test' },
    }),
    // Define how response data maps to your type
    withResult: (response): SignInResponse => ({
      token: response.data.auth_token,
      user: {
        id: response.data.user.id,
        email: response.data.user.email,
      },
    }),
  },
  getProfile: {
    method: 'get',
    // Only transform response
    withResult: (response): User => ({
      id: response.data.id,
      email: response.data.email,
    }),
  },
  register: {
    method: 'post',
    // Only transform parameters
    withParams: (email: string, password: string) => ({
      data: { email, password },
    }),
  },
})

// Usage with full type inference
const signInResult = await usersResource.signIn('[email protected]', 'password')
console.log(signInResult.token) // string
console.log(signInResult.user.id) // number

const profile = await usersResource.getProfile()
console.log(profile.email) // string

const registerResult = await usersResource.register('[email protected]', 'password')
console.log(registerResult.data) // axios response data

The interface customization provides:

  • Type-safe parameter transformation with optional parameters
  • Type-safe response data transformation
  • Custom headers support
  • Independent use of transforms (can use either or both)
  • Full TypeScript type inference for parameters and return types

Custom resource schema

Create resource module in your utils folder:

// utils/resource.ts
import { ResourceBuilder } from 'axios-rest-resource'

export const resourceBuilder = new ResourceBuilder({
  baseURL: 'http://localhost:3000',
})

Extended Schema

Extend the default schema with additional methods:

// api/entity2.js
import { resourceSchemaDefault } from 'axios-rest-resource'
import { resourceBuilder } from 'utils/resource'

export const entity2Resource = resourceBuilder.build('/entity2', {
  ...resourceSchemaDefault,
  doSomething: {
    method: 'post',
    url: '/do-something',
  },
})
// exports an object
// {
//   create: (requestConfig) => axiosPromise // sends POST http://localhost:3000/entity2,
//   read: (requestConfig) => axiosPromise // sends GET http://localhost:3000/entity2,
//   readOne: (requestConfig) => axiosPromise // sends GET http://localhost:3000/entity2/{id},
//   remove: (requestConfig) => axiosPromise // sends DELETE http://localhost:3000/entity2/{id},
//   update: (requestConfig) => axiosPromise // sends PUT http://localhost:3000/entity2/{id},
//   doSomething: (requestConfig) => axiosPromise // sends POST http://localhost:3000/entity2/do-something
// }

Example usage:

import { entity2Resource } from 'api/entity2'

const resRead = entity2Resource.read()
// sends GET http://localhost:3000/entity2
// resRead is a Promise of data received from the server

const resReadOne = entity2Resource.readOne({ params: { id } })
// for id = '123'
// sends GET http://localhost:3000/entity2/123
// resReadOne is a Promise of data received from the server

const resCreate = entity2Resource.create({ data })
// for data = { field1: 'test' }
// sends POST http://localhost:3000/entity2 with body { field1: 'test' }
// resCreate is a Promise of data received from the server

const resUpdate = entity2Resource.update({ data, params: { id } })
// for data = { field1: 'test' } and id = '123'
// sends PUT http://localhost:3000/entity2/123 with body { field1: 'test' }
// resUpdate is a Promise of data received from the server

const resRemove = entity2Resource.remove({ params: { id } })
// for id = '123'
// sends DELETE http://localhost:3000/entity2/123
// resRemove is a Promise of data received from the server

const resDoSomething = entity2Resource.doSomething()
// sends POST http://localhost:3000/entity2/do-something
// resDoSomething is a Promise of data received from the server

Custom Schema

Create a completely custom schema without extending the default:

// api/entity.js
import { resourceBuilder } from 'utils/resource'

export const entityResource = resourceBuilder.build('/entity', {
  doSomething: {
    method: 'post',
    url: '/do-something',
  },
})
// exports an object
// {
//   doSomething: (requestConfig) => axiosPromise // sends POST http://localhost:3000/entity/do-something
// }

Partial Schema

Use only specific methods from the default schema:

// api/entity.js
import { resourceSchemaDefault } from 'axios-rest-resource'
import { resourceBuilder } from 'utils/resource'

const { read, readOne } = resourceSchemaDefault

export const entityResource = resourceBuilder.build('/entity', {
  read,
  readOne,
})
// exports an object
// {
//   read: (requestConfig) => axiosPromise // sends GET http://localhost:3000/entity,
//   readOne: (requestConfig) => axiosPromise // sends GET http://localhost:3000/entity/{id},
// }

Rails Schema

If you're using Ruby on Rails, there is also a default schema that matches Rails' conventions for controller actions:

// api/entity.js
import { railsResourceSchema } from 'axios-rest-resource'
import { resourceBuilder } from 'utils/resource'

export const entityResource = resourceBuilder.build('/entity', railsResourceSchema)
// exports an object with Rails conventional action names:
// {
//   index: (requestConfig) => axiosPromise   // GET /entity (mapped from read)
//   show: (requestConfig) => axiosPromise    // GET /entity/{id} (mapped from readOne)
//   create: (requestConfig) => axiosPromise  // POST /entity
//   update: (requestConfig) => axiosPromise  // PUT /entity/{id}
//   destroy: (requestConfig) => axiosPromise // DELETE /entity/{id} (mapped from remove)
// }

In depth

What does ResourceBuilder do exactly upon creation?

When you call new ResourceBuilder(axiosConfig)

  1. If your axiosConfig doesn't have headers.Accept property it sets it to 'application/json'.
  2. It creates a new instance of axios passing axiosConfig to axios.create.
  3. It adds interceptorUrlFormatter to request interceptors of the newly created instance of axios.
  4. It exposes the newly created instance of axios for further modifications at axiosInstance.

Each instance of ResourceBuilder has its own axiosInstance. It's useful if you want to do something more with your axios instance like adding an interceptor.

import { ResourceBuilder } from 'axios-rest-resource'
import axios, { AxiosInstance } from 'axios'

const resourceBuilder = new ResourceBuilder({
  baseURL: 'http://localhost:3000',
})
resourceBuilder.axiosInstance.interceptors.response.use(myCustomResponeInterceptor)

export { resourceBuilder }