Skip to content

Commit

Permalink
Remove axios (#1369)
Browse files Browse the repository at this point in the history
* chore: remove axios from app store

* chore: remove more axios

* chore: wip

* chore: simplify fetch

 - use await to flatten code
 - must await dispatch otherwise there's a race for the background
   updating correctly

* chore: remove axios as a dep
  • Loading branch information
yanfali authored Nov 5, 2024
1 parent d0d00db commit 6c25d2b
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 99 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"@fortawesome/free-solid-svg-icons": "^5.15.4",
"@fortawesome/vue-fontawesome": "^2.0.8",
"autoprefixer": "^10.4.2",
"axios": "1.7",
"howler": "^2.1.3",
"keypress.js": "^2.1.5",
"lodash": "4.17.21",
Expand Down
44 changes: 23 additions & 21 deletions src/api.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from 'axios';
import store from './store';
import { useStatusStore } from './store/status';

Expand All @@ -13,30 +12,34 @@ function statusError(message) {
statusStore.scrollToEnd();
}

function compileLayout(_keyboard, _keymapName, _layout) {
function compileLayout(keyboard, keymap, layout) {
disableCompileButton();
let template = store.state.keymap.templates.keymap;
const layers = store.getters['keymap/exportLayers']({ compiler: true });
let request = JSON.stringify(
Object.assign(template, {
keyboard: _keyboard,
keymap: _keymapName,
layout: _layout,
layers: layers
})
);
let request = JSON.stringify({
...template,
keyboard,
keymap,
layout,
layers
});
console.log(request);
const statusStore = useStatusStore();
if (statusStore.empty) {
statusStore.append('\n');
}
statusStore.append(`* Sending ${_keyboard}:${_keymapName} with ${_layout}`);
axios
.post(backend_compile_url, request)
.then((resp) => {
const { status, data } = resp;
if (status === 200) {
statusStore.append(`* Sending ${keyboard}:${keymap} with ${layout}`);
fetch(backend_compile_url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: request
})
.then(async (resp) => {
if (resp.ok) {
store.commit('app/setShowSpinner', true);
const data = await resp.json();
if (data.enqueued) {
statusStore.append(`\n* Received job_id: ${data.job_id}`);
statusStore.scrollToEnd();
Expand Down Expand Up @@ -81,13 +84,12 @@ function check_status() {
const url = `${backend_compile_url}/${store.state.app.jobID}`;
const start = performance.now();
const statusStore = useStatusStore();
axios
.get(url)
.then((resp) => {
fetch(url)
.then(async (resp) => {
console.log(`response in ${performance.now() - start}ms`, resp);
let msg;
let { status, data } = resp;
if (status !== 200) {
const data = await resp.json();
if (!resp.ok) {
console.log('Unexpected status', data.status);
enableCompileButton();
} else {
Expand Down
22 changes: 11 additions & 11 deletions src/components/StatusBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
</div>
</template>
<script>
import axios from 'axios';
import { backend_status_url } from '@/store/modules/constants';
import { mapState, mapMutations } from 'vuex';
/**
Expand Down Expand Up @@ -90,10 +89,11 @@ export default {
getPollInterval() {
return 25000 + 5000 * Math.random();
},
fetchData() {
axios
.get(backend_status_url)
.then(({ data }) => {
async fetchData() {
try {
const resp = await fetch(backend_status_url);
if (resp.ok) {
const data = await resp.json();
this.version = data.version;
this.jobCount = parseInt(data.queue_length, 10);
if (this.jobCount === 0) {
Expand All @@ -108,12 +108,12 @@ export default {
this.status = 'Redis is probably down. Please contact devs on ';
this.hasError = true;
}
})
.catch((json) => {
this.status = 'DOWN';
this.hasError = true;
console.error('API status error', json);
});
}
} catch (error) {
this.status = 'DOWN';
this.hasError = true;
console.error('API status error', error);
}
setTimeout(this.fetchData, this.getPollInterval());
},
clickSettings() {
Expand Down
8 changes: 5 additions & 3 deletions src/components/VisualKeymap.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@
</template>
<script>
import isUndefined from 'lodash/isUndefined';
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
import { mapState, mapGetters, mapMutations } from 'vuex';
import * as pinia from 'pinia';
import BaseKeymap from '@/components/BaseKeymap.vue';
import BaseKey from '@/components/BaseKey.vue';
import AnyKey from '@/components/AnyKey.vue';
import LayerKey from '@/components/LayerKey.vue';
import ContainerKey from '@/components/ContainerKey.vue';
import LayerContainerKey from '@/components/LayerContainerKey.vue';
import { useStatusStore } from '@/store/status';
export default {
name: 'VisualKeymap',
components: { BaseKey, AnyKey, LayerKey, ContainerKey },
Expand Down Expand Up @@ -109,8 +112,7 @@ export default {
'resizeConfig',
'setLoadingKeymapPromise'
]),
...mapMutations('status', ['append']),
...mapActions('status', ['scrollToEnd']),
...pinia.mapActions(useStatusStore, ['append', 'scrollToEnd']),
/**
* Due to a quirk in how reactivity works we have to clear the layout
* name to reset the UI to it's old value.
Expand Down
59 changes: 35 additions & 24 deletions src/store/modules/app/actions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from 'axios';
import isUndefined from 'lodash/isUndefined';
import { keypress } from 'keypress.js';
import { generateKeypressCombos } from './keypress-utils.js';
Expand All @@ -16,15 +15,21 @@ const actions = {
* fetchKeyboards - fetch keyboard list from API
*/
async fetchKeyboards({ commit }) {
const r = await axios.get(backend_keyboard_list_url);
if (r.status === 200) {
const exclude = getExclusionList();
const results = r.data.keyboards.filter((keeb) => {
return isUndefined(exclude[keeb]);
});
commit('setKeyboards', results);
return results;
try {
const r = await fetch(backend_keyboard_list_url);
if (r.ok) {
const data = await r.json();
const exclude = getExclusionList();
const results = data.keyboards.filter((keeb) => {
return isUndefined(exclude[keeb]);
});
commit('setKeyboards', results);
return results;
}
} catch (error) {
console.error('Error fetching keyboards', error);
}
// always return an empty array if we fail to fetch
return [];
},
/**
Expand All @@ -33,20 +38,24 @@ const actions = {
async loadDefaultKeymap({ state }) {
const keyboardPath = state.keyboard.slice(0, 1).toLowerCase();
const keyboardName = state.keyboard.replace(/\//g, '_');
const resp = await axios.get(
`keymaps/${keyboardPath}/${keyboardName}_default.json`
);
if (resp.status === 200) {
return resp.data;
try {
const resp = await fetch(
`keymaps/${keyboardPath}/${keyboardName}_default.json`
);
if (resp.ok) {
return await resp.json();
}
} catch (error) {
console.error('Error fetching default keymap', error);
}
return undefined;
},
/**
* load keymap from the selected URL
*/
async loadKeymapFromUrl(_, url) {
return axios.get(url).then((r) => {
return r.data;
return fetch(url).then(async (r) => {
return await r.json();
});
},
/**
Expand Down Expand Up @@ -99,7 +108,7 @@ const actions = {
* We use this instead of loading layout from API.
* @return {object} promise that is fulfilled once action is complete
*/
loadLayouts({ commit, state }, preview) {
async loadLayouts({ commit, state }, preview) {
if (!isUndefined(preview)) {
preview.layouts[' '] = { layout: [] };
let p = new Promise((resolve) => {
Expand All @@ -113,13 +122,15 @@ const actions = {
});
return p;
}
return axios
.get(`${backend_keyboards_url}/${state.keyboard}/info.json`)
.then((resp) => {
commit('setKeyboardMeta', resp);
commit('processLayouts', resp);
return resp;
});
const resp = await fetch(
`${backend_keyboards_url}/${state.keyboard}/info.json`
);
if (resp.ok) {
const data = await resp.json();
commit('setKeyboardMeta', data);
commit('processLayouts', data);
return resp;
}
},
saveConfiguratorSettings({ state }) {
localStorageSet(
Expand Down
17 changes: 7 additions & 10 deletions src/store/modules/app/mutations.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ const mutations = {
* in same format containing keyboard layouts
* @return {object} layouts map or empty object
*/
processLayouts(state, resp) {
if (resp.status === 200 || state.isPreview) {
processLayouts(state, data) {
if (data || state.isPreview) {
let layouts = {};
if (state.isPreview) {
layouts = resp.keyboards[PREVIEW_LABEL].layouts;
layouts = data.keyboards[PREVIEW_LABEL].layouts;
} else {
if (resp.data && resp.data.keyboards) {
layouts = resp.data.keyboards[state.keyboard].layouts;
if (data && data.keyboards) {
layouts = data.keyboards[state.keyboard].layouts;
}
}
if (size(layouts) === 0) {
Expand Down Expand Up @@ -195,11 +195,8 @@ const mutations = {
toggleSnowflakes(state) {
state.snowflakes = !state.snowflakes;
},
setKeyboardMeta(state, value) {
if (value.status === 200) {
state.keyboardMeta =
value.data && value.data.keyboards ? value.data.keyboards : {};
}
setKeyboardMeta(state, data) {
state.keyboardMeta = data?.keyboards ? data.keyboards : {};
}
};

Expand Down
11 changes: 7 additions & 4 deletions src/store/modules/keymap.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import reduce from 'lodash/reduce';
import isUndefined from 'lodash/isUndefined';
import colorways from '@/components/colorways';
import defaults from './config';
import axios from 'axios';
import { backend_skeletons_url } from './constants';
import { parseKeycode } from './parse.js';

Expand Down Expand Up @@ -180,9 +179,10 @@ const actions = {
},
async initTemplates({ commit }) {
try {
const resp = await axios.get(`${backend_skeletons_url}/keymap`);
if (resp.status === 200) {
let template = Object.assign({}, resp.data);
const resp = await fetch(`${backend_skeletons_url}/keymap`);
if (resp.ok) {
const data = await resp.json();
let template = { ...data };
delete template.keyboard;
delete template.keymap;
delete template.layout;
Expand Down Expand Up @@ -402,6 +402,9 @@ const mutations = {
},
initKeymap(state, { layout, layer, code = 'KC_NO' }) {
const { name } = this.getters['keycodes/lookupKeycode'](code);
if (!layout) {
return;
}
Vue.set(
state.keymap,
layer,
Expand Down
27 changes: 2 additions & 25 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -995,15 +995,6 @@ aws4@^1.8.0:
resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.11.0.tgz#d61f46d83b2519250e2784daf5b09479a8b41c59"
integrity sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==

[email protected]:
version "1.7.4"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.4.tgz#4c8ded1b43683c8dd362973c393f3ede24052aa2"
integrity sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
proxy-from-env "^1.1.0"

axios@^0.21, axios@^0.27.2:
version "0.21.4"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.4.tgz#c67b90dc0568e5c1cf2b0b858c43ba28e2eda575"
Expand Down Expand Up @@ -1262,7 +1253,7 @@ colorette@^2.0.16:
resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.16.tgz#713b9af84fdb000139f04546bd4a93f62a5085da"
integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==

combined-stream@^1.0.6, combined-stream@^1.0.8, combined-stream@~1.0.6:
combined-stream@^1.0.6, combined-stream@~1.0.6:
version "1.0.8"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
Expand Down Expand Up @@ -1949,7 +1940,7 @@ flatted@^3.2.9:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.3.1.tgz#21db470729a6734d4997002f439cb308987f567a"
integrity sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==

follow-redirects@^1.14.0, follow-redirects@^1.15.6:
follow-redirects@^1.14.0:
version "1.15.6"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.6.tgz#7f815c0cda4249c74ff09e95ef97c23b5fd0399b"
integrity sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==
Expand All @@ -1959,15 +1950,6 @@ forever-agent@~0.6.1:
resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91"
integrity sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==

form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452"
integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"

form-data@~2.3.2:
version "2.3.3"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.3.tgz#dcce52c05f644f298c6a7ab936bd724ceffbf3a6"
Expand Down Expand Up @@ -3023,11 +3005,6 @@ [email protected]:
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.0.0.tgz#33c50398f70ea7eb96d21f7b817630a55791c7ee"
integrity sha1-M8UDmPcOp+uW0h97gXYwpVeRx+4=

proxy-from-env@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==

[email protected]:
version "1.2.0"
resolved "https://registry.yarnpkg.com/ps-tree/-/ps-tree-1.2.0.tgz#5e7425b89508736cdd4f2224d028f7bb3f722ebd"
Expand Down

0 comments on commit 6c25d2b

Please sign in to comment.