Skip to content

Instantly share code, notes, and snippets.

@jazibsawar
Created January 5, 2018 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jazibsawar/e25721015b56659991dd5aae166f756e to your computer and use it in GitHub Desktop.
Save jazibsawar/e25721015b56659991dd5aae166f756e to your computer and use it in GitHub Desktop.
src/plugins/resource/index.js
import cache from './cache'
import _merge from 'lodash.merge'
import config from '../../config'
// install $resource as a Vue plugin
export default {
install(Vue, { endpoint = '', resources = {} }) {
Vue.prototype.$getResource = function(method, options) {
let name = this.$options.resource
if (!name || !resources[name] || !resources[name][method]) return;
// get fetch path and response resolver/mapper
let { path, resolve } = resources[name][method](options)
let uri = '';
if (method === 'blog') {
uri = '/static/api' + path
} else {
uri = endpoint + path + '?hide_metafields=true&read_key=' + config.COSMIC_READ_KEY
}
// methods return promise to allow chaining
const mappers = {
// only return promise without modifying instance $data
pipe: dataSet => Promise.resolve(dataSet),
// deep merge object with instance $data
merge: dataSet => {
_merge(this.$data, dataSet)
return Promise.resolve(dataSet)
},
// set individual props on instance $data
set: dataSet => {
Object.keys(dataSet).forEach(prop => {
this.$set(this.$data, prop, dataSet[prop])
})
return Promise.resolve(dataSet)
}
}
// check to see if the resource has been cached already
if (cache.has(uri)) return resolve(cache.get(uri), mappers)
// fetch, parse and cache resource then pass to resolver
return fetch(uri)
.then(response => response.json())
.then(response => cache.set(uri, response))
.then(response => resolve(response, mappers))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment