Skip to content

Instantly share code, notes, and snippets.

@arlanram
Created March 29, 2021 20:17
Show Gist options
  • Save arlanram/4eb3d0525b6b723c85aabfff00583006 to your computer and use it in GitHub Desktop.
Save arlanram/4eb3d0525b6b723c85aabfff00583006 to your computer and use it in GitHub Desktop.
JavaScript (JS): global function for making query to API and storing response in Cache Storage with query strings and Vuex state for reactivity
//args: API url, commit name, params (qs), headers
export function query(url, commit, params, headers = null) {
//build new url
const q = new URL(process.env.VUE_APP_API + url)
//if params exists then append it to URL with URLSearchParams
if (params) {
q.search = new URLSearchParams(params).toString()
}
//open Cache Storage
caches.open('v1').then(c => {
//find matched key in storage
c.match(q.toString()).then(s => s.json().then(r => {
//if matched, commit response.
//it's needed for data reactivity, because Cache Storage is not reactive
//and set false to loading state
store.commit(commit ? commit: url, r)
store.commit('loading', false, { root: true })
})).catch(() => {
//if matched key not found
//set true to loading
store.commit('loading', true, { root: true })
//begin fetching data from remote API with given URL route
fetch(q.toString(), {
//set API key
//set ...headers if they exist in arg
headers: {
key: process.env.VUE_APP_KEY,
...headers
}
}).then(r => {
//then put response to new Cache with key of URL
//clone response, because used response can't be used second time
//then get json and commit that response to state
c.put(q.toString(), r.clone()).then(() => {
r.json().then(d => {
//commiting changes to state with given name from arg
//set false to loading state
store.commit(commit ? commit : url, d)
store.commit('loading', false, { root: true })
})
})
}).catch(e => {
//if there is errors then commit error response to state
//set false to loading state
store.commit(commit ? commit : url, e.response)
store.commit('loading', false, { root: true })
})
})
})
}
//the end :) if you have questions, feel free to text!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment