GithubHelp home page GithubHelp logo

hhy5277 / mande Goto Github PK

View Code? Open in Web Editor NEW

This project forked from posva/mande

0.0 1.0 0.0 2.57 MB

600 bytes convenient and modern wrapper around fetch with smart extensible defaults

Home Page: https://posva.net/mande/

License: MIT License

JavaScript 25.55% TypeScript 70.22% Shell 4.23%

mande's Introduction

mande Build Status npm package coverage thanks

Simple, light and extensible wrapper around fetch with smart defaults

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'

TypeScript

All methods defined on a mande instance accept a type generic to type their return:

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

todos.get<{ text: string, id: number, isFinished: boolean }[]>().then(todos => {
  // todos is correctly typed
})

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:

import { mande, nuxtWrap } from 'mande'
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

mande's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar posva avatar renovate-bot avatar renovate[bot] avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.