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

v0.0.7

Published

Simple resource layer over [axios](https://github.com/axios/axios) client with a few helpers. Valid for browser and node (6+).

Downloads

4

Readme

axios-schema-resource

Simple resource layer over axios client with a few helpers. Valid for browser and node (6+).

Only works for axios version 0.18.1 more info

Basic usage example
const axios = require('axios')
const resource = require('axios-schema-resource')
// import resource from 'axios-schema-resource'
// import axios from 'axios'

const User = resource({
  client: axios,
  config: {
    baseURL: 'https://myapi.com',
    url: '/user',
  },
  actions: {
    current: {
      url: '/profile',
    },
    export: {
      url: '/export',
      responseType: 'blob',
    },
  },
  methods: {
    async getCurrentUserId() {
      const res = await this.$current()
      return res.data.id
    },
    async getCSV() {
      const res = await this.$export()
      return res.data //blob
    },
  },
})

const userId = await User.getCurrentUserId()
FileSaver.saveAs(await User.getCSV(), 'users.csv')

Actions

Actions are the definitions for API endpoints. Only accepts and axios request config as first argument, and returns an axios response schema.

Actions are accesible as methods prefixed with a $ in the returned object.

Action definition
const User = resource({
  config:{ url: '/user', }
  // ...
  actions: {
    enable: {
      // axios request config, plus:

      // Prepends this path to url
      prependUrl: '/v1/admin',

      // Appends this path to url
      appendUrl: '/:userId/enable',

      // Interpolate :keys in url
      urlParams: {
        userId: 'anonymous',
      }
    },
  }
})

User.$enable()
// GET /v1/admin/user/anonymous/enable

User.$enable({ urlParams:{ userId:21 }})
// GET /v1/admin/user/21/enable

Final request config are the results of merging 5 request config, in order of precedence:

  • Action method (user.$enable(methodConfig))
  • Action definition (action: { enable: actionConfig })
  • Resource definition (resource({ config: resourceConfig }))
  • Default definition (resource.withDefaults({ config: defaultConfig })) See Defaults resource definition
  • Axios defaults (axios.create(axiosConfig)) See Change axios defaults

Final url is the result of prependUrl + url + appendUrl, and the interpolation of urlParams object. See action definition example above.

Default actions available
const res = await User.$list() // GET
const res = await User.$create() // POST
const res = await User.$detail() // GET __/:id
const res = await User.$update() // PUT __/:id
const res = await User.$patch() // PATCH __/:id
const res = await User.$delete() // DELETE __/:id

Methods

Methods are responsible for calling actions, accepting any arguments they need and handling the response as needed.

Methods definition
const User = resource({
  // ...
  methods: {
    async findPaginated(query) {
      const res = await this.$list({ params: { query } })
      return res.data.items
    },
  },
})

const users = await User.findPaginated({ limit: 10, page: 4 })
Default methods available
const users = await User.find()
// GET https://myapi.com/user

const user = await User.findOne(15)
// GET https://myapi.com/user/15

const user = await User.create(15, {
  name: 'foo1',
  roles: [1, 2],
})
// POST https://myapi.com/user
// {"name":"foo1","roles":[1,2]}

const user = await User.update(15, {
  name: 'foo2',
  roles: [3, 4],
})
// PUT https://myapi.com/user/15
// {"name":"foo2","roles":[3,4]}

const user = await User.patch(15, {
  name: 'foo3',
})
// PATCH https://myapi.com/user/15
// {"name":"foo3"}

await User.delete(15)
// DELETE https://myapi.com/user/15

Static properties

You can use axios custom instance:

const User = resource({
  client,
  statics: {
    model: {
      name: String
    }
  },
})
console.log(User.model.name === String) // true

Change axios defaults

You can use axios custom instance:

const client = axios.create({
  baseURL: API_URL,
  timeout: 30000,
})
const User = resource({
  client,
  config: {
    // baseURL: API_URL // Is not needed anymore
  },
})

Request and response interceptors (error handling)

You can use axios interceptors as follows:

const client = axios.create()

// Add a request interceptor
client.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
client.interceptors.response.use(
  function(response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function(error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)

const User = resource({
  client,
  // ...
})

Defaults resource definition

You can override defaults resource definitions using .withDefaults() method like:

const myResource = resource.withDefaults({
  client,
  config,
  actions,
  methods,
})

const user = myResource({
  config: { url: '/user' },
  // ...
})

Current resource defaults

This is the source code for the defaults object (as exposed above in methods and actions explanations). You can use this object as a template for creating your own defaults.

const set = require('lodash.set')
const DEFAULTS = {
  client: null,
  config: {},
  statics: {},
  methods: {
    find(config) {
      return this.$list(config).then(res => res.data)
    },
    findOne(id, config = {}) {
      set(config, 'urlParams.id', id)
      return this.$detail(config).then(res => res.data)
    },
    create(data, config = {}) {
      config.data = data
      return this.$create(config).then(res => res.data)
    },
    update(id, data, config = {}) {
      set(config, 'urlParams.id', id)
      config.data = data
      return this.$update(config).then(res => res.data)
    },
    patch(id, data, config = {}) {
      set(config, 'urlParams.id', id)
      config.data = data
      return this.$patch(config).then(res => res.data)
    },
    remove(id, config = {}) {
      set(config, 'urlParams.id', id)
      return this.$delete(config).then(res => res.data)
    },
  },
  actions: {
    list: {
      method: 'get',
    },
    create: {
      method: 'post',
    },
    detail: {
      method: 'get',
      prependUrl: '/:id',
    },
    update: {
      method: 'put',
      prependUrl: '/:id',
    },
    patch: {
      method: 'patch',
      prependUrl: '/:id',
    },
    delete: {
      method: 'delete',
      prependUrl: '/:id',
    },
  },
}