0.1.9 • Published 2 years ago
@eis/fetchutils v0.1.9
What is this?
fetchutils
is a wrapper around Javascript's fetch API that attempts to solve a few common issues:
- fetch does not throw for non-200 status codes
- fetch requires a separate async call to .json() or .text() to read the body
Example Usage
interface Book {
id: string;
title: string;
author: string;
}
const client = new HttpClient('http://example.com', {
headers: { authorization: "Bearer <token>" }
})
async function doStuff() {
try {
// Pass the expected type of the return value.
// No need to call response.json() or check response.ok here.
const books = await client.get<Book[]>('/books');
// Access the result
books.forEach(book=> {
console.log('id', book.id);
console.log('author', book.author);
console.log('title', book.title);
});
} catch (e: unknown) {
// get() will wrap any non-2xx status codes and throw an instance
// of HttpError. If the response body was a json object, the message
// will be the serialized json value. Otherwise, the body text or
// the http status text is returned.
if (e instanceof HttpError){
console.log(`Error ${e.code}: ${e.message}`);
}
throw e;
}
}
POST
interface Book {
id: string;
title: string;
author: string;
}
const client = new HttpClient('http://example.com', {
headers: { authorization: "Bearer <token>" }
})
async function doStuff() {
try {
// you can call post() like this:
// const books = await client.post<Book>('/books', {
// body: JSON.stringify({
// title: 'my new book',
// author: 'myself',
// })
// });
// or you can call the postJson() shortcut:
const book = await client.postJson<Book>('/books', {
title: 'my new book',
author: 'myself',
});
// you can also postJson() without a response:
// await client.postJson('/books', {
// title: 'my new book',
// author: 'myself',
// });
console.log(`Created book ${book.id}`)
} catch (e: unknown) {
// ...
}
}
There are similar APIs for PUT and DELETE requests.