Created
June 7, 2019 17:07
-
-
Save mturnwall/83e639781a9aa063cdec54aa560f90a7 to your computer and use it in GitHub Desktop.
Promise wrapper for @fdaciuk/ajax
This file contains hidden or 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
// Requires https://www.npmjs.com/package/@fdaciuk/ajax | |
import ajax from '@fdaciuk/ajax'; | |
/** | |
* Object that holds all the API endpoints. | |
* @example | |
* { | |
* apiName: '/apiPath' | |
* } | |
*/ | |
const endpoints = {}; | |
/** | |
* The URL (host) of your API | |
* @example https://private-0fde15-pto.apiary-mock.com/ | |
*/ | |
const API_HOST = ''; | |
/** | |
* The path to the API, this is the part that comes after the host | |
* @example https://private-0fde15-pto.apiary-mock.com/API_PATH | |
*/ | |
const API_PATH = ''; | |
/** | |
* | |
* @param {string} endpoint - api endpoint to call | |
* @param {*} data - data that will be sent to the server | |
* @param {string} [method=POST] - the http action such as GET or POST | |
* @returns {Promise} - Promise wrapper for the ajax call | |
*/ | |
const api = (endpoint, data, method = 'POST') => new Promise((resolve, reject) => { | |
if (!(endpoint in endpoints)) { | |
reject(new Error(`The api endpoint "${endpoint}" was not found`)); | |
return false; | |
} | |
ajax({ | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
method, | |
data, | |
url: `${API_HOST}${API_PATH}${endpoints[endpoint]}`, | |
}).then(response => { | |
resolve(response); | |
}).catch(err => { | |
reject(err); | |
}); | |
return true; | |
}); | |
export { | |
api | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment