Created
November 14, 2020 12:58
-
-
Save whal-e3/dfd0c52dcb24816ebca6dd140f28f598 to your computer and use it in GitHub Desktop.
JS custom http library with fetch() & promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* EasyHTTP Library | |
* Library for making HTTP requests | |
* | |
* @version 2.0.0 | |
* @author Eric Whale | |
* @license MIT..? | |
*/ | |
class EasyHTTP { | |
// HTTP GET request | |
get(url) { | |
return new Promise((resolve, reject) => { | |
fetch(url) | |
.then(res => res.json()) | |
.then(data => resolve(data)) | |
.catch(err => reject(err)); | |
}); | |
} | |
// HTTP POST request | |
post(url, data) { | |
return new Promise((resolve, reject) => { | |
fetch(url, { | |
method: 'POST', | |
headers: { | |
'Content-type': 'application/json' | |
}, | |
body: JSON.stringify(data) | |
}) | |
.then(res => res.json()) | |
.then(data => resolve(data)) | |
.catch(err => reject(err)); | |
}); | |
} | |
// HTTP PUT request | |
put(url, data) { | |
return new Promise((resolve, reject) => { | |
fetch(url, { | |
method: 'PUT', | |
headers: { | |
'Content-type': 'application/json' | |
}, | |
body: JSON.stringify(data) | |
}) | |
.then(res => res.json()) | |
.then(data => resolve(data)) | |
.catch(err => reject(err)); | |
}); | |
} | |
// HTTP DELETE request | |
delete(url) { | |
return new Promise((resolve, reject) => { | |
fetch(url, { | |
method: 'DELETE', | |
headers: { | |
'Content-type': 'application/json' | |
} | |
}) | |
.then(res => res.json()) | |
.then(() => resolve('Resource deleted...')) | |
.catch(err => reject(err)); | |
}); | |
} | |
} | |
// ---------------------------------------------------------------------------------------------- | |
const http = new EasyHTTP(); | |
// Get Users | |
http | |
.get('https://jsonplaceholder.typicode.com/users') | |
.then(data => console.log(data)) | |
.catch(err => console.log(err)); | |
// Post data | |
const testData = { | |
name: 'John Doe', | |
username: 'johndoe', | |
email: 'jdoe@gmail.com' | |
}; | |
http | |
.post('https://jsonplaceholder.typicode.com/users', testData) | |
.then(data => console.log(data)) | |
.catch(err => console.log(err)); | |
// Put(update) post | |
http | |
.put('https://jsonplaceholder.typicode.com/users/3', testData) | |
.then(data => console.log(data)) | |
.catch(err => console.log(err)); | |
// Delete post | |
http | |
.delete('https://jsonplaceholder.typicode.com/users/2') | |
.then(message => console.log(message)) | |
.catch(err => console.log(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment