fitsh
v1.3.0
Published
fetchival implementation with typescript
Downloads
11
Maintainers
Readme
Fitsh
Supported by browser and Node, Fitsh is a tiny / easy to use fetch wrapper based on Fetchival but with typescript support
Before
// POST /users
fetch('/users', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Typicode',
login: 'typicode',
})
}).then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json()
}
throw new Error(response.statusText)
}).then(users => {
// ...
});
After
// POST /users
fitsh('/users').post({
name: 'Typicode',
login: 'typicode'
}).then(users => {
// ...
});
Fisht has .get()
, .put()
, .patch()
and .delete()
methods
Installation
yarn add fitsh
Usage examples
const posts = fitsh('/posts')
// posts
posts.get();
posts.post({ title: 'Fetchival' });
// posts?category=javascript
posts.get({ category: 'javascript' });
// posts/1
posts(1).get();
posts(1).put({ title: 'Fetchival is simple' });
posts(1).patch({ title: 'Fetchival is simple' });
posts(1).delete();
const comments = posts('1/comments');
// posts/1/comments
comments.get();
// posts/1/comments/1
comments(1).get();
You can set fetch options to Fitsh
const posts = fitsh('/posts', fetchOptions);
const comments = posts('1/comments'); // Will inherit fetchOptions
To catch errors
fitsh('/posts')
.get()
.catch(function(error) {
console.log(error)
console.log(error.response); // Raw response object
});
The response type can be setted as argument in Fitsh methods
const post = await fitsh('/post/1')
.get('text'); // arrayBuffer | blob | formData | json | text | raw
To use in Node you need a fetch library like node-fetch
and send it as argument
import * as nodeFetch from 'node-fetch';
import { fitsh } from 'fitsh';
const posts = fitsh(nodeFetch as any, '/posts');
or set it one time globally
import * as nodeFetch from 'node-fetch';
import { fitsh } from 'fitsh';
fitsh.fetch = nodeFetch;