diff options
Diffstat (limited to 'static/api-client.js')
| -rw-r--r-- | static/api-client.js | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/static/api-client.js b/static/api-client.js new file mode 100644 index 0000000..4a1b81e --- /dev/null +++ b/static/api-client.js @@ -0,0 +1,70 @@ +/* jshint esversion: 2024, module: true */ + +/** + * API Client for network operations + * @class ApiClient + */ +class ApiClient { + /** + * API utility function + * @method request + * @param {string} path - API endpoint + * @param {Object} [options] - Fetch options + * @returns {Promise<Response>} + */ + async request(path, options = {}) { + const response = await fetch(path, options); + + if (!response.ok) { + const text = await response.text(); + throw new Error(`${response.status} ${text}`); + } + + return response; + } + + /** + * GET request returning JSON + * @method get + * @param {string} path - API endpoint + * @returns {Promise<Object>} + */ + async get(path) { + const response = await this.request(path); + return response.json(); + } + + /** + * GET request returning text + * @method getText + * @param {string} path - API endpoint + * @returns {Promise<string>} + */ + async getText(path) { + const response = await this.request(path); + return response.text(); + } + + /** + * POST request with JSON body + * @method post + * @param {string} path - API endpoint + * @param {Object} [data] - Request body + * @returns {Promise<Object>} + */ + async post(path, data = null) { + const options = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }; + + if (data) { + options.body = JSON.stringify(data); + } + + const response = await this.request(path, options); + return response.json(); + } +} + +export { ApiClient }; |
