How to inject metadata, after pages API?
Summary
I feel like all the pieces I need exist, I'm just not sure how to piece them together. What I want to do is after all my pages have been created within GraphQL (I'm using the filesystem plugin, but that shouldn't matter).
I then want to create a search index, and add the generated JSON to my metadata, for use on a search page later on. This means the index can be generated at build time, rather than on all page loads. My issue is that I can only do this before the pages API is generated.
Basic example
This works inside my components mounted hook, (using lunr.js for the search):
mounted() {
const self = this;
this.index = lunr(function () {
this.ref('id');
this.field('title');
this.field('excerpt');
this.metadataWhitelist = ['position'];
self.allContent.forEach(post => {
this.add(post.node);
});
});
}
I want to be able to do this within gridsome.server.js:
module.exports = function (api) {
api.loadSource(async store => {
// no data has been loaded for my pages at this point
store.addMetaData('searchIndex', 'This is my search index');
});
api.beforeBuild(() => {
// Load source isn't triggered at this point, and doesn't work in dev
api.loadSource(async store => {
store.addMetaData('searchIndex', 'This is my search index');
});
});
};
Motivation
To be able to inject metadata into the site based on page level data that has already been processed, such as a search index.
I have this exact same question. I tried referencing api._app.store.addMetaData but surprise, surprise! That extremely hacky solution doesn't work. So far I haven't been able to find any good option for generating static metadata based on GraphQL content.
I came across this usecase today. @hjvedvik any pointers on how this can be done? I need to create some information based on a GraphQL query and inject it as global metadata.
I'm in the same spot. I'm trying to use a custom resolver for the metadata field, but it's still unclear how to run a graphql query from inside the resolver.