1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-25 14:52:20 +01:00

73 lines
2.3 KiB
TypeScript
Raw Normal View History

import apiClient from './api-client';
import { AxiosResponse } from 'axios';
2021-03-30 15:56:36 +02:00
import { Setting, SettingBulkResult, SettingError, SettingName } from '../models/setting';
import wrapPromise, { IWrapPromise } from '../lib/wrap-promise';
export default class SettingAPI {
2020-11-24 16:26:18 +01:00
async get (name: SettingName): Promise<Setting> {
const res: AxiosResponse = await apiClient.get(`/api/settings/${name}`);
return res?.data?.setting;
}
2020-11-24 16:26:18 +01:00
async query (names: Array<SettingName>): Promise<Map<SettingName, any>> {
2021-03-30 15:56:36 +02:00
const params = new URLSearchParams();
params.append('names', `['${names.join("','")}']`);
const res: AxiosResponse = await apiClient.get(`/api/settings?${params.toString()}`);
2021-03-24 17:31:50 +01:00
return SettingAPI.toSettingsMap(res?.data);
2020-11-24 16:26:18 +01:00
}
2021-03-30 15:56:36 +02:00
async bulkUpdate (settings: Map<SettingName, any>): Promise<Map<SettingName, SettingBulkResult>> {
const res: AxiosResponse = await apiClient.patch('/api/settings/bulk_update', { settings: SettingAPI.toObjectArray(settings) });
return SettingAPI.toBulkMap(res?.data?.settings);
}
2020-11-24 16:26:18 +01:00
static get (name: SettingName): IWrapPromise<Setting> {
const api = new SettingAPI();
return wrapPromise(api.get(name));
}
2020-11-24 16:26:18 +01:00
static query(names: Array<SettingName>): IWrapPromise<Map<SettingName, any>> {
const api = new SettingAPI();
return wrapPromise(api.query(names));
}
2021-03-24 17:31:50 +01:00
2021-03-30 15:56:36 +02:00
private static toSettingsMap(data: Object): Map<SettingName, any> {
2021-03-24 17:31:50 +01:00
const dataArray: Array<Array<string | any>> = Object.entries(data);
const map = new Map();
dataArray.forEach(item => {
2021-03-30 15:56:36 +02:00
map.set(item[0] as SettingName, item[1]);
2021-03-24 17:31:50 +01:00
});
return map;
}
2021-03-30 15:56:36 +02:00
private static toBulkMap(data: Array<Setting|SettingError>): Map<SettingName, SettingBulkResult> {
const map = new Map();
data.forEach(item => {
const itemData: SettingBulkResult = { status: true };
if ('error' in item) {
itemData.error = item.error;
itemData.status = false;
}
if ('value' in item) {
itemData.value = item.value;
}
map.set(item.name as SettingName, itemData)
});
return map;
}
private static toObjectArray(data: Map<SettingName, any>): Array<Object> {
const array = [];
data.forEach((value, key) => {
array.push({
name: key,
value
})
});
return array;
}
}