[core] Minify requests

This commit is contained in:
Ferdinand Thiessen 2021-11-22 16:40:21 +01:00
parent 53f053a294
commit ade6d06eb6
1 changed files with 37 additions and 1 deletions

View File

@ -3,18 +3,54 @@ import { LocalStorage, Notify } from 'quasar';
import { AxiosError } from 'axios';
import { boot } from 'quasar/wrappers';
import config from 'src/config';
import { clone } from '@flaschengeist/api';
function minify(o: unknown, cloned = false) {
if (!cloned) o = clone(o);
if (typeof o === 'object') {
const obj = o as { [index: string]: unknown };
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && !!obj[prop]) {
if (Array.isArray(obj[prop])) {
obj[prop] = (<Array<unknown>>obj[prop]).map((v) => minify(v, true));
} else if (
typeof obj[prop] === 'object' &&
Object.keys(<object>obj[prop]).includes('id') &&
typeof (<{ id: unknown }>obj[prop])['id'] === 'number' &&
!isNaN((<{ id: number }>obj[prop])['id'])
) {
obj[prop] = (<{ id: unknown }>obj[prop])['id'];
}
}
}
return obj;
}
return o;
}
export default boot(({ router }) => {
api.defaults.baseURL = LocalStorage.getItem<string>('baseURL') || config.baseURL;
/***
* Intercept requests and insert Token if available
* Intercept requests
* - insert Token if available
* - minify JSON requests
*/
api.interceptors.request.use((config) => {
const store = useMainStore();
if (store.session?.token) {
config.headers = { Authorization: 'Bearer ' + store.session.token };
}
// Minify JSON requests
if (
!!config.data &&
(config.headers === undefined ||
config.headers['Content-Type'] === undefined ||
config.headers['Content-Type'] === 'application/json')
)
config.data = minify(config.data);
return config;
});