From b0c76dcc159ead3d67314da3a71d60bad9385991 Mon Sep 17 00:00:00 2001 From: Petri Hienonen Date: Sun, 28 Sep 2025 13:41:46 +0300 Subject: Split the system --- static/api-client.js | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 static/api-client.js (limited to 'static/api-client.js') 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} + */ + 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} + */ + 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} + */ + 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} + */ + 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 }; -- cgit v1.2.3-70-g09d2