Skip to content

Instantly share code, notes, and snippets.

@jazibsawar

jazibsawar/index.js Secret

Created Jan 5, 2018
Embed
What would you like to do?
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