diff --git a/src/api/LocalStorageAPI.js b/src/api/LocalStorageAPI.js new file mode 100644 index 0000000..4cba8ef --- /dev/null +++ b/src/api/LocalStorageAPI.js @@ -0,0 +1,35 @@ +/** + * Класс работы с Local Storage браузера + * @class LocalStorageAPI + * @param {string} key - ключ по которому будет хранится информация + */ +class LocalStorageAPI { + constructor (key) { + this.key = key; + } + + /** + * Возвращает распарсенный объект из Local Storage по ключу из конструктора + */ + request () { + const value = localStorage.getItem(this.key) || '{}'; + return JSON.parse(value); + } + + /** + * Записывает данные в Local Storage по ключу из конструктора + * @param {*} value - значение в Local Storage + */ + createOrUpdate (value) { + localStorage.setItem(this.key, JSON.stringify(value)); + } + + /** + * Очищает значение Local Storage по ключу из конструктора + */ + remove () { + localStorage.removeItem(this.key); + } +} + +export default LocalStorageAPI; diff --git a/src/api/StorageLogsAPI.js b/src/api/StorageLogsAPI.js index a49538b..b8c6b92 100644 --- a/src/api/StorageLogsAPI.js +++ b/src/api/StorageLogsAPI.js @@ -1,8 +1,12 @@ import axios from 'axios'; -import {API_URL, ENDPOINTS} from './consts'; +import {ENDPOINTS} from './consts'; +import adminConfigsService from '../services/AdminConfigsService'; class StorageLogsApi { - URL = `${API_URL}`; + constructor () { + const {url} = adminConfigsService.getApi(); + this.URL = url; + } requestServerLogs = async () => { const {data} = await axios.get(`${this.URL}${ENDPOINTS.SERVER_LOGS}`); diff --git a/src/api/StorageServiceAPI.js b/src/api/StorageServiceAPI.js index 8958885..463586e 100644 --- a/src/api/StorageServiceAPI.js +++ b/src/api/StorageServiceAPI.js @@ -1,6 +1,7 @@ import axios from 'axios'; -import {API_URL, ENDPOINTS, TESTING_HEADERS} from './consts'; +import {ENDPOINTS} from './consts'; +import adminConfigsService from '../services/AdminConfigsService'; /** * @interface Store @@ -17,15 +18,12 @@ import {API_URL, ENDPOINTS, TESTING_HEADERS} from './consts'; * @class */ class StorageServiceApi { - URL = `${API_URL}${ENDPOINTS.STORE}`; - - get defaultConfig () { - if (location.hostname.includes('localhost')) { - return { - headers: TESTING_HEADERS, - }; - } - return {}; + constructor () { + const {url, headers} = adminConfigsService.getApi(); + this.URL = `${url}${ENDPOINTS.STORE}`; + this.OPTIONS = { + headers, + }; } /** @@ -33,7 +31,7 @@ class StorageServiceApi { * @returns {Promise} - Возвращает список всех api */ request = async () => { - const {data} = await axios.get(this.URL, this.defaultConfig); + const {data} = await axios.get(this.URL, this.OPTIONS); return data; } @@ -43,7 +41,7 @@ class StorageServiceApi { * @returns {Promise} - Возвращает api по указанному ключу */ find = async (key) => { - const {data} = await axios.get(`${this.URL}/${key}`, this.defaultConfig); + const {data} = await axios.get(`${this.URL}/${key}`, this.OPTIONS); return data; } @@ -53,7 +51,7 @@ class StorageServiceApi { * @returns {Promise} - Возвращает вновь созданный элемент */ create = async (createData) => { - const {data} = await axios.post(this.URL, createData, this.defaultConfig); + const {data} = await axios.post(this.URL, createData, this.OPTIONS); return data; } @@ -63,7 +61,7 @@ class StorageServiceApi { * @returns {Promise} - Возвращает обновленный элемент */ update = async (updateData) => { - const {data} = await axios.put(this.URL, updateData, this.defaultConfig); + const {data} = await axios.put(this.URL, updateData, this.OPTIONS); return data; } @@ -73,7 +71,7 @@ class StorageServiceApi { * @returns {Promise} - Возвращает удаленный элемент */ remove = async (key) => { - const {data} = await axios.delete(`${this.URL}/${key}`, this.defaultConfig); + const {data} = await axios.delete(`${this.URL}/${key}`, this.OPTIONS); return data; } } diff --git a/src/api/consts.js b/src/api/consts.js index 7f23508..86dc3b6 100644 --- a/src/api/consts.js +++ b/src/api/consts.js @@ -1,5 +1,29 @@ +export const API_NAMES = { + PRODUCTION: 'api-p', + TESTING: 'api-t', + DEVELOP: 'api-l', +}; -export const API_URL = 'http://api.storage.vigdorov.ru'; +export const LOCALHOST = 'localhost'; + +export const API_OPTIONS = { + [API_NAMES.PRODUCTION]: { + url: 'http://api.storage.vigdorov.ru', + options: {}, + }, + [API_NAMES.TESTING]: { + url: 'http://api.storage.vigdorov.ru', + options: { + headers: { + 'Api-Name': 'store-service-test', + }, + }, + }, + [API_NAMES.DEVELOP]: { + url: 'http://localhost:4001', + options: {}, + }, +}; export const ENDPOINTS = { STORE: '/store', diff --git a/src/app.js b/src/app.js index 255e59a..eaeaf92 100644 --- a/src/app.js +++ b/src/app.js @@ -2,6 +2,7 @@ import './app.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap'; +import './services/AdminConfigsService'; import ApiPage from './components/api-page'; import MainPage from './components/main-page'; import navMenuButtons from './components/navigation-buttons-component/NavButtonComponent'; diff --git a/src/services/AdminConfigsService.js b/src/services/AdminConfigsService.js new file mode 100644 index 0000000..e8da0ee --- /dev/null +++ b/src/services/AdminConfigsService.js @@ -0,0 +1,59 @@ +import LocalStorageAPI from '../api/LocalStorageAPI'; +import {API_NAMES, API_OPTIONS, LOCALHOST} from '../api/consts'; + +/** + * Класс для команд приложению через консоль браузера, работает только в режиме + * разработки на localhost + */ +class AdminConfigsService { + constructor () { + this.api = new LocalStorageAPI('storageServiceAdminConfigsApi'); + } + + /** + * Возвращает все опции которые сервис хранит в памяти + */ + getOptions () { + return this.api.request(); + } + + /** + * Метод получения информации о текущем api + */ + getApi () { + const {apiName} = this.getOptions(); + if (apiName) { + return API_OPTIONS[apiName]; + } + if (location.hostname.includes(LOCALHOST)) { + return API_OPTIONS[API_NAMES.TESTING]; + } + return API_OPTIONS[API_NAMES.PRODUCTION]; + } + + /** + * Метод переключает api через консоль браузера + * @param {'api-p' | 'api-t' | 'api-l'} apiName - api с которым хотим работать + * @example + * // Переключаем api на localhost, пишем в консоли браузера + * __adminConfigs.setApi('api-l') + */ + setApi (apiName) { + const options = this.getOptions(); + if (Object.values(API_NAMES).includes(apiName)) { + this.api.createOrUpdate({ + ...options, + apiName, + }); + location.reload(); + } + } +} + +const adminConfigsService = new AdminConfigsService(); + +if (location.hostname === LOCALHOST) { + window.__adminConfigs = adminConfigsService; +} + +export default adminConfigsService;