From 63132abc202b215e52ec5776c30f0f2f75610d5b Mon Sep 17 00:00:00 2001 From: b1ek Date: Wed, 17 May 2023 04:39:30 +1000 Subject: [PATCH] add api client --- pairent_frontend_react/src/API/Client.js | 72 ++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 pairent_frontend_react/src/API/Client.js diff --git a/pairent_frontend_react/src/API/Client.js b/pairent_frontend_react/src/API/Client.js new file mode 100644 index 0000000..35c8b5d --- /dev/null +++ b/pairent_frontend_react/src/API/Client.js @@ -0,0 +1,72 @@ +import axios, { Axios } from "axios"; + +import { User } from "./User"; +import { APIToken } from './APIToken'; + +class ClientCreateOptions { + /** Key used to access APIs, if you don't have user data + * @type {APIToken?} + */ + key; + + /** Current user's data + * @type {User?} + */ + user; +} + +/** + * An API client which is basically a User but with + * API token and with access to private fields. + */ +class Client extends User { + /** @type {APIToken} */ + key; + + /** @type {string} */ + openid_id; + + /** @type {string} */ + favorites_apartments; + + /** @type {string} */ + comparison_apartments; + + /** + * + * @param {ClientCreateOptions} options + */ + constructor(options) { + super(); + + if (options.key === undefined & options.user === undefined) { + throw new Error('Either key or user is required.'); + } + + this.key = options.key; + if (options.user) { + for (const key in options.user) { + this[key] = options.user[key]; + } + } + } + + /** + * + * @param {string} uri + * @param {string} method + * @param {import('axios').AxiosRequestConfig} options + */ + fetchData(url, method, options) { + axios.request({ + url, + method, + headers: { + ...(options.headers ? options.headers : {}), + 'X-Pairent-Auth': this.key.key + }, + + ...options + }); + } +} \ No newline at end of file