Last active
August 11, 2018 20:02
-
-
Save unr/64790cdf236b2d8acbcbf81634475956 to your computer and use it in GitHub Desktop.
Bare minimum example of Prismic API exposed as a Nuxt.js plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Prismic API | |
* Creates a prismic api instance on the app, for use in asyncData for loading content. | |
*/ | |
import Vue from 'vue'; | |
import prismic from 'prismic-javascript'; | |
export default ({ app, env, error }) => { | |
const PrismicApi = { | |
// use this to access singular api instance in app | |
// in vue: this.prismic.api | |
// in asyncData/fetch: app.prismic.api | |
api: { | |
// This default object, prevents failures when calling `this.prismic.api.query` before it | |
// has fully initialized. This will be overwritten when its ready. | |
// This is mostly to track which pages are causing the call to occur early, for improved debugging | |
query(queryPredicates) { | |
if (process.client) { | |
app.$raven.captureMessage('Prismic Called Before Creation', { | |
extra: { | |
error: 'prismic.api.query was called before prismic.getApi finished', | |
queryPredicates, | |
}, | |
}); | |
} | |
error({ statusCode: 500, message: 'Something went wrong, please refresh and try again.' }); | |
return new Promise(resolve => resolve({ failed: true, results: [] })); | |
}, | |
}, | |
// ready is true, when we've loaded the prismic api and not our default above. | |
hasApi: false, | |
// allows us to build queries via app.prismic.Predicates | |
Predicates: prismic.Predicates, | |
// returns existing api, or makes a new one for use in app via app.prismic.api | |
async getApi() { | |
this.api = await prismic.getApi(env.prismicApi, { accessToken: env.prismicToken }) | |
.catch((err) => { | |
if (process.client) { | |
app.$raven.captureMessage('Failed loading prismic api', { extra: { error: err } }); | |
} | |
return error({ statusCode: 500, message: 'Something went wrong, please refresh and try again.' }); | |
}); | |
}, | |
}; | |
app.prismic = PrismicApi; | |
Vue.prototype.prismic = PrismicApi; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated, to remove the preservation of api.
Should be making a new version for each request.