🚚 Refactored saving logic into mixin

This commit is contained in:
Alicia Sykes 2022-04-24 16:01:30 +01:00
parent 1bc9964374
commit f5a8c30257
3 changed files with 97 additions and 137 deletions

View File

@ -51,20 +51,19 @@
<script> <script>
import axios from 'axios';
import { Progress } from 'rsup-progress';
import VJsoneditor from 'v-jsoneditor'; import VJsoneditor from 'v-jsoneditor';
import jsYaml from 'js-yaml'; import ConfigSavingMixin from '@/mixins/ConfigSaving';
import ErrorHandler, { InfoHandler, InfoKeys } from '@/utils/ErrorHandler'; import { InfoHandler, InfoKeys } from '@/utils/ErrorHandler';
import configSchema from '@/utils/ConfigSchema.json'; import configSchema from '@/utils/ConfigSchema.json';
import StoreKeys from '@/utils/StoreMutations'; import StoreKeys from '@/utils/StoreMutations';
import { localStorageKeys, serviceEndpoints, modalNames } from '@/utils/defaults'; import { modalNames } from '@/utils/defaults';
import Button from '@/components/FormElements/Button'; import Button from '@/components/FormElements/Button';
import Radio from '@/components/FormElements/Radio'; import Radio from '@/components/FormElements/Radio';
import AccessError from '@/components/Configuration/AccessError'; import AccessError from '@/components/Configuration/AccessError';
export default { export default {
name: 'JsonEditor', name: 'JsonEditor',
mixins: [ConfigSavingMixin],
components: { components: {
VJsoneditor, VJsoneditor,
Button, Button,
@ -83,9 +82,6 @@ export default {
name: 'config', name: 'config',
onValidationError: this.validationErrors, onValidationError: this.validationErrors,
}, },
responseText: '',
saveSuccess: undefined,
progress: new Progress({ color: 'var(--progress-bar)' }),
saveOptions: [ saveOptions: [
{ label: this.$t('config-editor.location-disk-label'), value: 'file' }, { label: this.$t('config-editor.location-disk-label'), value: 'file' },
{ label: this.$t('config-editor.location-local-label'), value: 'local' }, { label: this.$t('config-editor.location-local-label'), value: 'local' },
@ -126,9 +122,9 @@ export default {
/* Calls appropriate save method, based on save-type radio selected */ /* Calls appropriate save method, based on save-type radio selected */
save() { save() {
if (this.saveMode === 'local' || !this.allowWriteToDisk) { if (this.saveMode === 'local' || !this.allowWriteToDisk) {
this.saveConfigLocally(); this.saveLocally();
} else if (this.saveMode === 'file') { } else if (this.saveMode === 'file') {
this.writeConfigToDisk(); this.writeToDisk();
} else { } else {
this.$toasted.show(this.$t('config-editor.error-msg-save-mode')); this.$toasted.show(this.$t('config-editor.error-msg-save-mode'));
} }
@ -144,67 +140,11 @@ export default {
this.$store.commit(StoreKeys.SET_EDIT_MODE, true); this.$store.commit(StoreKeys.SET_EDIT_MODE, true);
this.$modal.hide(modalNames.CONF_EDITOR); this.$modal.hide(modalNames.CONF_EDITOR);
}, },
/* Converts config to YAML, and writes it to disk */ writeToDisk() {
writeConfigToDisk() { this.writeConfigToDisk(this.config);
// 1. Convert JSON into YAML
const yaml = jsYaml.dump(this.config);
// 2. Prepare the request
const baseUrl = process.env.VUE_APP_DOMAIN || window.location.origin;
const endpoint = `${baseUrl}${serviceEndpoints.save}`;
const headers = { 'Content-Type': 'text/plain' };
const body = { config: yaml, timestamp: new Date() };
const request = axios.post(endpoint, body, headers);
// 3. Make the request, and handle response
this.progress.start();
request.then((response) => {
this.saveSuccess = response.data.success || false;
this.responseText = response.data.message;
if (this.saveSuccess) {
this.carefullyClearLocalStorage();
this.showToast(this.$t('config-editor.success-msg-disk'), true);
} else {
this.showToast(this.$t('config-editor.error-msg-cannot-save'), false);
}
InfoHandler('Config has been written to disk succesfully', InfoKeys.RAW_EDITOR);
this.$store.commit(StoreKeys.SET_CONFIG, this.jsonData);
this.progress.end();
})
.catch((error) => {
this.saveSuccess = false;
this.responseText = error;
this.showToast(error, false);
ErrorHandler(`Failed to save config. ${error}`);
this.progress.end();
});
}, },
/* Saves config to local browser storage */ saveLocally() {
saveConfigLocally() { this.saveConfigLocally(this.jsonData);
if (!this.allowSaveLocally) {
ErrorHandler('Unable to save changes locally, this feature has been disabled');
return;
}
const data = this.jsonData;
if (data.sections) {
localStorage.setItem(localStorageKeys.CONF_SECTIONS, JSON.stringify(data.sections));
}
if (data.pageInfo) {
localStorage.setItem(localStorageKeys.PAGE_INFO, JSON.stringify(data.pageInfo));
}
if (data.appConfig) {
data.appConfig.auth = this.config.appConfig.auth || {};
localStorage.setItem(localStorageKeys.APP_CONFIG, JSON.stringify(data.appConfig));
}
if (data.appConfig.theme) {
localStorage.setItem(localStorageKeys.THEME, data.appConfig.theme);
}
InfoHandler('Config has successfully been saved in browser storage', InfoKeys.RAW_EDITOR);
this.showToast(this.$t('config-editor.success-msg-local'), true);
},
/* Clears config from browser storage, only removing relevant items */
carefullyClearLocalStorage() {
localStorage.removeItem(localStorageKeys.PAGE_INFO);
localStorage.removeItem(localStorageKeys.APP_CONFIG);
localStorage.removeItem(localStorageKeys.CONF_SECTIONS);
}, },
/* Convert error messages into readable format for UI */ /* Convert error messages into readable format for UI */
validationErrors(errors) { validationErrors(errors) {

View File

@ -79,16 +79,12 @@
</template> </template>
<script> <script>
import axios from 'axios'; import ConfigSavingMixin from '@/mixins/ConfigSaving';
import jsYaml from 'js-yaml';
import { Progress } from 'rsup-progress';
import Button from '@/components/FormElements/Button'; import Button from '@/components/FormElements/Button';
import StoreKeys from '@/utils/StoreMutations'; import StoreKeys from '@/utils/StoreMutations';
import EditPageInfo from '@/components/InteractiveEditor/EditPageInfo'; import EditPageInfo from '@/components/InteractiveEditor/EditPageInfo';
import EditAppConfig from '@/components/InteractiveEditor/EditAppConfig'; import EditAppConfig from '@/components/InteractiveEditor/EditAppConfig';
import { modalNames, localStorageKeys, serviceEndpoints } from '@/utils/defaults'; import { modalNames } from '@/utils/defaults';
import ErrorHandler, { InfoHandler } from '@/utils/ErrorHandler';
import AccessError from '@/components/Configuration/AccessError'; import AccessError from '@/components/Configuration/AccessError';
import SaveLocallyIcon from '@/assets/interface-icons/interactive-editor-save-locally.svg'; import SaveLocallyIcon from '@/assets/interface-icons/interactive-editor-save-locally.svg';
@ -100,6 +96,7 @@ import PageInfoIcon from '@/assets/interface-icons/interactive-editor-page-info.
export default { export default {
name: 'EditModeSaveMenu', name: 'EditModeSaveMenu',
mixins: [ConfigSavingMixin],
components: { components: {
Button, Button,
EditPageInfo, EditPageInfo,
@ -124,13 +121,6 @@ export default {
return this.permissions.allowWriteToDisk || this.permissions.allowSaveLocally; return this.permissions.allowWriteToDisk || this.permissions.allowSaveLocally;
}, },
}, },
data() {
return {
saveSuccess: undefined,
responseText: '',
progress: new Progress({ color: 'var(--progress-bar)' }),
};
},
methods: { methods: {
reset() { reset() {
this.$store.dispatch(StoreKeys.INITIALIZE_CONFIG); this.$store.dispatch(StoreKeys.INITIALIZE_CONFIG);
@ -154,63 +144,11 @@ export default {
showToast(message, success) { showToast(message, success) {
this.$toasted.show(message, { className: `toast-${success ? 'success' : 'error'}` }); this.$toasted.show(message, { className: `toast-${success ? 'success' : 'error'}` });
}, },
carefullyClearLocalStorage() {
localStorage.removeItem(localStorageKeys.PAGE_INFO);
localStorage.removeItem(localStorageKeys.APP_CONFIG);
localStorage.removeItem(localStorageKeys.CONF_SECTIONS);
},
saveLocally() { saveLocally() {
if (!this.permissions.allowSaveLocally) { this.saveConfigLocally(this.config);
ErrorHandler('Unable to save changes locally, this feature has been disabled');
return;
}
const data = this.config;
localStorage.setItem(localStorageKeys.CONF_SECTIONS, JSON.stringify(data.sections));
localStorage.setItem(localStorageKeys.PAGE_INFO, JSON.stringify(data.pageInfo));
localStorage.setItem(localStorageKeys.APP_CONFIG, JSON.stringify(data.appConfig));
if (data.appConfig.theme) {
localStorage.setItem(localStorageKeys.THEME, data.appConfig.theme);
}
InfoHandler('Config has succesfully been saved in browser storage', 'Config Update');
this.showToast(this.$t('config-editor.success-msg-local'), true);
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
}, },
writeToDisk() { writeToDisk() {
if (this.config.appConfig.preventWriteToDisk) { this.writeConfigToDisk(this.config);
ErrorHandler('Unable to write changed to disk, as this functionality is disabled');
return;
}
// 1. Convert JSON into YAML
const yamlOptions = {};
const yaml = jsYaml.dump(this.config, yamlOptions);
// 2. Prepare the request
const baseUrl = process.env.VUE_APP_DOMAIN || window.location.origin;
const endpoint = `${baseUrl}${serviceEndpoints.save}`;
const headers = { 'Content-Type': 'text/plain' };
const body = { config: yaml, timestamp: new Date() };
const request = axios.post(endpoint, body, headers);
// 3. Make the request, and handle response
this.progress.start();
request.then((response) => {
this.saveSuccess = response.data.success || false;
this.responseText = response.data.message;
if (this.saveSuccess) {
this.carefullyClearLocalStorage();
this.showToast(this.$t('config-editor.success-msg-disk'), true);
} else {
this.showToast(this.$t('config-editor.error-msg-cannot-save'), false);
}
InfoHandler('Config has been written to disk succesfully', 'Config Update');
this.progress.end();
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
})
.catch((error) => {
this.saveSuccess = false;
this.responseText = error;
this.showToast(error, false);
ErrorHandler(`Failed to save config. ${error}`);
this.progress.end();
});
}, },
}, },
}; };

View File

@ -0,0 +1,82 @@
import axios from 'axios';
import jsYaml from 'js-yaml';
import { Progress } from 'rsup-progress';
import ErrorHandler, { InfoHandler } from '@/utils/ErrorHandler';
import { localStorageKeys, serviceEndpoints } from '@/utils/defaults';
import StoreKeys from '@/utils/StoreMutations';
export default {
data() {
return {
saveSuccess: undefined,
responseText: '',
progress: new Progress({ color: 'var(--progress-bar)' }),
};
},
methods: {
writeConfigToDisk(config) {
if (config.appConfig.preventWriteToDisk) {
ErrorHandler('Unable to write changed to disk, as this functionality is disabled');
return;
}
// 1. Get the config, and strip appConfig if is sub-page
const isSubPag = !!this.$store.state.currentConfigInfo;
const jsonConfig = config;
if (isSubPag) delete jsonConfig.appConfig;
// 2. Convert JSON into YAML
const yamlOptions = {};
const yaml = jsYaml.dump(jsonConfig, yamlOptions);
// 3. Prepare the request
const baseUrl = process.env.VUE_APP_DOMAIN || window.location.origin;
const endpoint = `${baseUrl}${serviceEndpoints.save}`;
const headers = { 'Content-Type': 'text/plain' };
const filename = isSubPag
? (this.$store.state.currentConfigInfo.confPath || '') : '';
const body = { config: yaml, timestamp: new Date(), filename };
const request = axios.post(endpoint, body, headers);
// 4. Make the request, and handle response
this.progress.start();
request.then((response) => {
this.saveSuccess = response.data.success || false;
this.responseText = response.data.message;
if (this.saveSuccess) {
this.carefullyClearLocalStorage();
this.showToast(this.$t('config-editor.success-msg-disk'), true);
} else {
this.showToast(this.$t('config-editor.error-msg-cannot-save'), false);
}
InfoHandler('Config has been written to disk successfully', 'Config Update');
this.progress.end();
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
})
.catch((error) => { // fucking hell
this.saveSuccess = false;
this.responseText = error;
this.showToast(error, false);
ErrorHandler(`Failed to save config. ${error}`);
this.progress.end();
});
},
saveConfigLocally(config) {
if (!this.permissions.allowSaveLocally) {
ErrorHandler('Unable to save changes locally, this feature has been disabled');
return;
}
localStorage.setItem(localStorageKeys.CONF_SECTIONS, JSON.stringify(config.sections));
localStorage.setItem(localStorageKeys.PAGE_INFO, JSON.stringify(config.pageInfo));
localStorage.setItem(localStorageKeys.APP_CONFIG, JSON.stringify(config.appConfig));
if (config.appConfig.theme) {
localStorage.setItem(localStorageKeys.THEME, config.appConfig.theme);
}
InfoHandler('Config has succesfully been saved in browser storage', 'Config Update');
this.showToast(this.$t('config-editor.success-msg-local'), true);
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
},
carefullyClearLocalStorage() {
localStorage.removeItem(localStorageKeys.PAGE_INFO);
localStorage.removeItem(localStorageKeys.APP_CONFIG);
localStorage.removeItem(localStorageKeys.CONF_SECTIONS);
},
},
};