From ade6d06eb6df430ed842a10d2bc867c8371c866d Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Mon, 22 Nov 2021 16:40:21 +0100 Subject: [PATCH] [core] Minify requests --- src/boot/axios.ts | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/boot/axios.ts b/src/boot/axios.ts index 3a5ede1..c8cd602 100644 --- a/src/boot/axios.ts +++ b/src/boot/axios.ts @@ -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] = (>obj[prop]).map((v) => minify(v, true)); + } else if ( + typeof obj[prop] === 'object' && + Object.keys(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('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; });