menu

Gatsby.js

Fast in every way that matters. Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps.

Channels
# All channels
view-forward
# General
view-forward
# I Made This
view-forward
# Meta
view-forward
# Themes
view-forward
Team

Executing apollo mutations when creating pages.

August 31, 2019 at 10:34am

Executing apollo mutations when creating pages.

August 31, 2019 at 10:34am
I'm managing content through system files with MDX. but i need to send the slugs of created posts to a another database(Hasura in this case). so i can perform other mutations on each post page.
like adding a comment system, a reaction system, etc..
so is there a way to perform graphql mutations(with apollo) in the gatsby-node file.
or if there is a better solution to this.

October 18, 2019 at 6:56am
Seems like you want to manage content via a CMS (in this case Gatsby + MDX) but want to plug in dynamic content from a database.
I have written an example of how this can be done.
const path = require(`path`);
const fetch = require('isomorphic-fetch');
const gql = require('graphql-tag');
const ApolloBoost = require('apollo-boost');
const ApolloClient = ApolloBoost.default;
const client = new ApolloClient({
uri: 'http://localhost:8080/v1/graphql',
fetch,
});
const mutateQuery = gql`
mutation upsert_article($objects: [article_insert_input!]!) {
insert_article(
objects: $objects,
on_conflict: {
constraint: article_pkey,
update_columns: [slug],
}
) {
affected_rows
}
}
`;
exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions
const blogPostTemplate = path.resolve(`src/templates/blogTemplate.js`)
return graphql(`
{
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
limit: 1000
) {
edges {
node {
frontmatter {
path
}
}
}
}
}
`).then(result => {
if(result.data) {
const edges = result.data.allMarkdownRemark.edges;
const mutateObjects = [];
edges.map((edge) => {
const currentPath = edge.node.frontmatter.path;
mutateObjects.push({slug: currentPath});
})
client.mutate({mutation: mutateQuery, variables: {objects: mutateObjects}})
.then(result => { console.log(result) })
.catch(error => { console.log(error) });
}
if (result.errors) {
return Promise.reject(result.errors)
}
return result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.path,
component: blogPostTemplate,
context: {}, // additional data can be passed via context
})
})
})
}
like-fill
1
  • reply
  • like
This is exactly what i'm looking for, my current solution is hardcoding the slugs in hasura and perform mutations depending on the slug. this will make it a lot more robust. thank you Praveen
  • reply
  • like