All Projects → posva → Mande

posva / Mande

Licence: mit
600 bytes convenient and modern wrapper around fetch

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Mande

miniprogram-network
Redefine the Network API of Wechat MiniProgram (小程序网络库)
Stars: ✭ 93 (-39.61%)
Mutual labels:  fetch, promise, axios
Apisauce
Axios + standardized errors + request/response transforms.
Stars: ✭ 2,303 (+1395.45%)
Mutual labels:  api, promise, axios
Flowa
🔥Service level control flow for Node.js
Stars: ✭ 66 (-57.14%)
Mutual labels:  api, promise
React Ufo
🛸 react-ufo - A simple React hook to help you with data fetching 🛸
Stars: ✭ 85 (-44.81%)
Mutual labels:  axios, fetch
Vue2 Element
基于vue2 + vue-router2 + element-ui + vuex2 + fetch + webpack2 企业级后台管理系统最佳实践
Stars: ✭ 112 (-27.27%)
Mutual labels:  promise, fetch
Before After Hook
wrap methods with before/after hooks
Stars: ✭ 49 (-68.18%)
Mutual labels:  api, promise
Redux Api Call
One declarative API to create reducers, action creators and selectors for any API calls
Stars: ✭ 63 (-59.09%)
Mutual labels:  api, fetch
Apipeline
Feature-rich and pluggable offline-first API wrapper for all your javascript environements ! Easily wire-up your API and make your app work offline in minutes.
Stars: ✭ 92 (-40.26%)
Mutual labels:  api, fetch
Fritzbox.js
☎️ The leading AVM Fritz!Box API for NodeJS and JavaScript.
Stars: ✭ 36 (-76.62%)
Mutual labels:  api, promise
Nion
🌵 Declarative API Data Management Library built on top of redux 🌵
Stars: ✭ 116 (-24.68%)
Mutual labels:  api, fetch
Vue Api Request
Control your API calls by using an amazing component which supports axios and vue-resource
Stars: ✭ 116 (-24.68%)
Mutual labels:  api, axios
Nuxt Dev To Clone
Build DEV.TO clone with Nuxt.js and new `fetch` hook
Stars: ✭ 118 (-23.38%)
Mutual labels:  api, fetch
Frisbee
🐕 Modern fetch-based alternative to axios/superagent/request. Great for React Native.
Stars: ✭ 1,038 (+574.03%)
Mutual labels:  axios, fetch
Axios Rest
A simple axios wrapper to make rest api call delightful
Stars: ✭ 41 (-73.38%)
Mutual labels:  api, axios
Vue Fetch Data
A simple and declarative way to fetch data for Vue components.
Stars: ✭ 65 (-57.79%)
Mutual labels:  axios, fetch
Axios Module
Secure and easy axios integration with Nuxt.js
Stars: ✭ 998 (+548.05%)
Mutual labels:  api, axios
Mfetch
mfetch will provide you with a strong ability to request resource management
Stars: ✭ 90 (-41.56%)
Mutual labels:  promise, fetch
Poloniex Api Node
Poloniex API client for REST and WebSocket API
Stars: ✭ 138 (-10.39%)
Mutual labels:  api, promise
Apipie
Transform api declaration to js object for frontend. Inspired by VueRouter, koa-middleware and axios.
Stars: ✭ 29 (-81.17%)
Mutual labels:  api, axios
Create Request
Apply interceptors to `fetch` and create a custom request function.
Stars: ✭ 34 (-77.92%)
Mutual labels:  promise, fetch

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'

SSR (and Nuxt in Universal mode)

To make Mande work on Server, make sure to provide a fetch polyfill and to use full URLs and not absolute URLs starting with /. For example, using node-fetch, you can do:

export const BASE_URL = process.server
  ? process.env.NODE_ENV !== 'production'
    ? 'http://localhost:3000'
    : 'https://example.com'
  : // on client, do not add the domain, so urls end up like `/api/something`
    ''

const fetchPolyfill = process.server ? require('node-fetch') : fetch
const contents = mande(BASE_URL + '/api', {}, fetchPolyfill)

Nuxt

When using with Nuxt and SSR, you must wrap exported functions so they automatically proxy cookies and headers on the server:

const fetchPolyfill = process.server ? require('node-fetch') : fetch
const users = mande(BASE_URL + '/api/users', {}, fetchPolyfill)

export const getUserById = nuxtWrap(users, (api, id: string) => api.get(id))

Make sure to add it as a buildModule as well:

// nuxt.config.js
module.exports = {
  buildModules: ['mande/nuxt'],
}

This prevents requests from accidentally sharing headers or bearer tokens.

TypeScript

Make sure to include mande/nuxt in your tsconfig.json:

{
  "types": ["@types/node", "@nuxt/types", "mande/nuxt"]
}

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].