fetchival implementation with typescript
Before
``ts`
// 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
`ts`
// POST /users
fitsh('/users').post({
name: 'Typicode',
login: 'typicode'
}).then(users => {
// ...
});
Fisht has .get(), .put(), .patch() and .delete() methods
sh
yarn add fitsh
`Usage examples
`ts
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
`ts
const posts = fitsh('/posts', fetchOptions);
const comments = posts('1/comments'); // Will inherit fetchOptions
`To catch errors
`ts
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
`ts
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`ts
import * as nodeFetch from 'node-fetch';
import { fitsh } from 'fitsh';const posts = fitsh(nodeFetch as any, '/posts');
`or set it one time globally
`ts
import * as nodeFetch from 'node-fetch';
import { fitsh } from 'fitsh';fitsh.fetch = nodeFetch;
``