Skip to content
/ mande Public
forked from posva/mande

Simple, light and easy to use wrapper around fetch

License

Notifications You must be signed in to change notification settings

maxzz/mande

 
 

Repository files navigation

mande Build Status npm package coverage thanks

Simple, light and easy to use wrapper around fetch

Requires fetch support.

mande has better defaults to communicate with APIs using fetch, so instead of writing:

// creating a new user
fetch('/api/users', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Dio',
    password: 'irejectmyhumanityjojo',
  }),
})
  .then((response) => {
    if (response.status >= 200 && response.status < 300) {
      return response.json()
    }
    // reject if the response is not 2xx
    throw new Error(response.statusText)
  })
  .then((user) => {
    // ...
  })

You can write:

const users = mande('/api/users')

users
  .post({
    name: 'Dio',
    password: 'irejectmyhumanityjojo',
  })
  .then((user) => {
    // ...
  })

Installation

npm install mande
yarn add mande

Usage

Creating a small layer to communicate to your API:

// api/users
import { mande } from 'mande'

const users = mande('/api/users', globalOptions)

export function getUserById(id) {
  return users.get(id)
}

export function createUser(userData) {
  return users.post(userData)
}

Adding Authorization tokens:

// api/users
import { mande } from 'mande'

const todos = mande('/api/todos', globalOptions)

export function setToken(token) {
  // todos.options will be used for all requests
  todos.options.headers.Authorization = 'Bearer ' + token
}

export function clearToken() {
  delete todos.options.headers.Authorization
}

export function createTodo(todoData) {
  return todo.post(todoData)
}
// In a different file, setting the token whenever the login status changes. This depends on your frontend code, for instance, some libraries like Firebase provide this kind of callback but you could use a watcher on Vue.
onAuthChange((user) => {
  if (user) setToken(user.token)
  else clearToken()
})

You can also globally add default options to all mande instances:

import { defaults } from 'mande'

defaults.headers.Authorization = 'Bearer token'

API

Most of the code can be discovered through the autocompletion but the API documentation is available at https://posva.net/mande/.

Related

  • fetchival: part of the code was borrowed from it and the api is very similar
  • axios:

License

MIT

About

Simple, light and easy to use wrapper around fetch

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 70.2%
  • JavaScript 23.5%
  • Shell 6.3%