• Stars
    star
    1,188
  • Rank 39,371 (Top 0.8 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

<700 bytes convenient and modern wrapper around fetch with smart extensible defaults

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 2

Note: If you are doing SSR with athentication, Nuxt 3 hasn't been adapted yet. See #308.

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/.

Cookbook

Timeout

You can timeout requests by using the native AbortSignal:

mande('/api').get('/users', { signal: AbortSignal.timeout(200) })

This is supported by all modern browsers.

Related

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

License

MIT

More Repositories

1

vue-promised

๐Ÿ’ Composable Promises & Promises as components
TypeScript
1,792
star
2

unplugin-vue-router

Next Generation file based typed routing for Vue Router
TypeScript
1,643
star
3

vim-vue

Syntax Highlight for Vue.js components
Vim Script
1,286
star
4

catimg

๐Ÿฆฆ Insanely fast image printing in your terminal
C
1,239
star
5

vue-mdc

Material web components for Vue.js
JavaScript
1,201
star
6

pinia-colada

๐Ÿน The smart data fetching layer for Pinia
TypeScript
764
star
7

vuexfire

Check
JavaScript
559
star
8

vite-tailwind-starter

Starter using Vite + Tailwind for super fast prototyping
Vue
459
star
9

vuex-mock-store

โœ…Simple and straightforward Vuex Store mock for vue-test-utils
JavaScript
273
star
10

focus-trap-vue

Vue component to trap the focus within a DOM element
JavaScript
204
star
11

vue-router-mock

๐Ÿงช Easily mock routing interactions in your Vue apps
TypeScript
198
star
12

vue-plugin-template

๐Ÿš€ Solid foundation to start a Vue plugin with the best developer experience and a focus on performance
JavaScript
192
star
13

vue-local-scope

๐Ÿ–‡ Generate local scopes in templates to compute data from other scoped slots or simply to have variables in templates
JavaScript
168
star
14

vue-reactive-refs

Make $refs reactive so they can be used in computed properties and watchers
TypeScript
160
star
15

vue-ts-lib

Vue 3 library starter in TS with lint, auto release, changelog and tests
JavaScript
160
star
16

sounds-webpack-plugin

๐Ÿ”ŠNotify or errors, warnings, etc with sounds
JavaScript
124
star
17

vue-tweezing

๐Ÿ’ƒ Easy, customizable and automatic tweening nicely served in scoped slots
JavaScript
100
star
18

vue-use-spring

๐Ÿ’ซ Naturally fluid animations for Vue
TypeScript
89
star
19

vue-compose-promise

๐Ÿ’ Promises using vue composition api
TypeScript
76
star
20

vue-coerce-props

Coerce props to whatever you want
JavaScript
75
star
21

shapify

๐ŸŒ€Easily transform objects/rename keys with full TypeScript support
JavaScript
67
star
22

pinia-plugin-debounce

Config-based action debouncing made easy
TypeScript
65
star
23

markdown-it-custom-block

Handle custom blocks transformations for markdown-it
JavaScript
53
star
24

state-animation-demos

Demos for Vue.js amsterdam/roadtrip talk: State animations, getting them right
Vue
43
star
25

task-logger.sh

๐ŸŽจ shell library to log tasks with nice output. Supports zsh and bash
Shell
43
star
26

vue-router-view-transition

Properly time out-in transitions with scrollBehavior
JavaScript
40
star
27

event-emitter

<200 bytes type safe extendable event emitter / pubsub class
TypeScript
39
star
28

vuefire-nuxt-example

Example project using VueFire with Nuxt
Vue
33
star
29

vuefire-emoji-panel

Nuxt + VueFire Demo code
TypeScript
32
star
30

vue-prop-data-fallback

Vue mixin to support an optional prop by falling back to a local data
JavaScript
31
star
31

size-check-action

A custom size action
TypeScript
28
star
32

nuxt--vuefire-example-spark-plan

๐Ÿ”ฅ Nuxt + VueFire template to bootstrap your Firebase App
Vue
26
star
33

2021-amsterdam-demos

Vue
25
star
34

rollit

๐ŸŒฏ Zero config js library bundling using rollup with support for Vue
JavaScript
24
star
35

unplugin-vue-router-demo

Demo for the talk "Stop writing your routes"
TypeScript
23
star
36

vuefire-vite-example

Example project using VueFire in a vite project
Vue
23
star
37

talk-vuejs-and-typescript-a-complicated-relationship

Talk Vue.js and Typescript, a complicated relationship
22
star
38

vue-recomputed

Recomputable computed properties
JavaScript
21
star
39

talk-data-loaders

Slides and demo code for Vue.js Live talk
TypeScript
20
star
40

onlysponsors

Tracker for Only Sponsors
20
star
41

nuxt--vuefire-example-blaze-plan

๐Ÿ”ฅ Nuxt + VueFire template to bootstrap your Firebase App with the Blaze plan
Vue
20
star
42

p-singleton

Ensure only one instance of a promise is created until rejected or resolved
JavaScript
19
star
43

clipboard-text

Simple and small copy-text-to-the-clipboard-utility with IE11 support
TypeScript
13
star
44

how2

Exercise building a scalable web app like how2 cli using Vue
JavaScript
12
star
45

faked-promise

Create a fake promise that can be resolve and rejected programatically
JavaScript
11
star
46

lib-boilerplate-ts

personal boilerplate for a lib with ts
JavaScript
11
star
47

esm.dev

๐Ÿ‘จโ€๐Ÿ’ป my personal website
TypeScript
10
star
48

jest-mock-warn

Mock console.log warn calls and assert their calls
JavaScript
10
star
49

paths.esm.dev

๐Ÿ›ฃ A Vue Router path debugger
Vue
10
star
50

dotfiles

๐Ÿ“ My dotfiles
Vim Script
9
star
51

phaser-webpack-ts

Starter for Phaser 3 with Typescript, webpack and weback DLLPlugin
JavaScript
8
star
52

mocha-requirejs-boilerplate

JavaScript
7
star
53

mocha-css

A mocha stylesheet for the HTML reporter that let you append visual tests
CSS
7
star
54

eslint-config-posva

๐Ÿคบ Opinionated eslint set of rules with support for Vue
JavaScript
7
star
55

vitesse-unplugin-vue-router

Test repo for unplugin-vue-router + vitesse
TypeScript
6
star
56

vitepress-theme-nuxt-content

Vitepress theme imitating Nuxt Content
Vue
5
star
57

minesweeper.rs

Learning project with Rust: Minesweeper
Rust
5
star
58

free-workshop-pinia-from-scratch

Free online workshop to build Pinia from scratch
TypeScript
5
star
59

renovate-config

Renovate config for Open Source
5
star
60

nuxt--vuefire-demo

Nuxt VueFire Demo
Vue
5
star
61

pinia-ssr-example-cw

TypeScript
4
star
62

OUTDATED_nuxt-vuefire-example

wip
Vue
4
star
63

instacraper

Scrap images from Instagram post
JavaScript
4
star
64

vercel-nuxt-example

Vue
3
star
65

vue-pinia-example

Created with CodeSandbox
JavaScript
3
star
66

vuefire-core

mirror to test something with codecov
JavaScript
3
star
67

vuefire-vitesse-example

Example of using VueFire with SSR
TypeScript
3
star
68

slides

๐Ÿ“ข Talks I have given somewhere, sometime
HTML
2
star
69

store-code-split-demo

demo to showcase ideal codesplit for a store like Vuex
JavaScript
2
star
70

bug-vue-loader-slot

Vue
2
star
71

bug-report-vca

JavaScript
2
star
72

pinia-colada-example

Example repository for stackblitz
Vue
2
star
73

demo-data-loaders-artwork-gallery

TypeScript
2
star
74

nuxt-composition-api-185

Vue
2
star
75

configure-script

โšก Simple script to generate Makefiles for your project. It's mainly aimed for C/C++ but can be adapted to other languages
Shell
2
star
76

.github

Default .github folder
2
star
77

vuefire-examples

Various examples showcasing vuefire/vuexfire
HTML
2
star
78

2d-collisions

Collision for 2D using the SAT theorem with Rectangles
C++
2
star
79

mille-bornes

mille bornes card game for 2 players only with AI and online
CoffeeScript
1
star
80

blog.esm.dev

Vue
1
star
81

awesome-latex-workspace

๐Ÿ“‘ Watcher + commit based diff generator
Shell
1
star
82

vue-merge-options

Helpers to merge vue custom options
1
star
83

mangare-angular

๐Ÿ™ Download Manga in convenient formats!
JavaScript
1
star
84

bug-report-nuxt-plugin

TypeScript
1
star
85

bcn-marfeel-demo

Demo for the meetup @marfeel the 19/07/2018
Vue
1
star
86

Rndm

Random number generation for vim
Vim Script
1
star
87

portfolio

1
star
88

planet-noise

Test to generate planet terrain using libnoise. SFML to render the image
C++
1
star
89

app-dep-test-renovate

JavaScript
1
star
90

lerna-test

Testing things with lerna
JavaScript
1
star
91

imag-utils

Scripts ou autres infos utiles ร  l'Ensimag
JavaScript
1
star
92

literate-couscous

1
star
93

lab-vue-getting-started

tech.io lab
JavaScript
1
star
94

tetris

โฌ› A simple engine of tetris that can be used along with another printing system
C
1
star
95

pretty-hrtime.sh

๐Ÿ•’ Pretty High Resolution Time in shell
Shell
1
star
96

nuxt--vuefire-repro-template

Nuxt VueFire template for reproductions
Vue
1
star
97

posva

๐ŸŒฎ๐ŸŒฎ๐ŸŒฎ
1
star
98

app-dep-test

JavaScript
1
star
99

test-pr-lib

JavaScript
1
star
100

MangaDown

Allow to download mangas from websites using a parsing file
C++
1
star