Skip to content

Instantly share code, notes, and snippets.

@mhluska
Created June 18, 2018 08:56
Show Gist options
  • Save mhluska/8fb90664656b34ca75010505a203975a to your computer and use it in GitHub Desktop.
Save mhluska/8fb90664656b34ca75010505a203975a to your computer and use it in GitHub Desktop.
Sanity-ember-service
import Service, { inject as service } from '@ember/service';
export default Service.extend({
ajax: service(),
store: service(),
fastboot: service(),
client: null,
init() {
// TODO: Use this when it starts working.
// See https://github.com/sanity-io/sanity/issues/877
// const client = sanity({
// projectId: '',
// dataset: 'production',
// useCdn: true,
// });
this.setProperties({
// client,
client: {
fetch: this.fetch.bind(this),
},
})
this._super(...arguments);
},
fetch(query) {
const projectId = 'foo'; // Add your project ID here.
const dataset = 'production';
const url = `https://${projectId}.apicdn.sanity.io/v1/data/query/${dataset}?query=${encodeURIComponent(query)}`
const ajaxService = this.get('ajax');
const shoebox = this.get('fastboot.shoebox');
const shoeboxStore = shoebox.retrieve('sanity') || {};
if (this.get('fastboot.isFastBoot')) {
return ajaxService.request(url).then(response => {
shoeboxStore[query] = response.result;
shoebox.put('sanity', shoeboxStore);
return response.result;
});
} else {
return Promise.resolve(shoeboxStore[query]);
}
},
load() {
return this.get('client').fetch('*[_type == "post"]').then(result => {
this.get('store').push({
data: result.map((post, index) => ({
id: index + 1,
type: 'blog-post',
attributes: {
title: post.title,
createdAt: post._createdAt,
updatedAt: post._updatedAt,
body: post.body,
categories: post.categories,
mainImage: post.mainImage,
slug: post.slug,
rev: post._rev,
sanityId: post._id,
sanityType: post._type,
},
})),
});
return result;
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment