Skip to content

Commit

Permalink
groq conversion, start preparing changes to schema, refetch data with…
Browse files Browse the repository at this point in the history
… groq, remove postcss reference and remove sanity-source-plugin`
  • Loading branch information
iamkevingreen committed Feb 6, 2021
1 parent e2ac95f commit 860eecb
Show file tree
Hide file tree
Showing 14 changed files with 372 additions and 242 deletions.
23 changes: 0 additions & 23 deletions web/gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,6 @@ module.exports = {
layout: require.resolve(`./src/layouts/index.tsx`)
}
},
{
resolve: 'gatsby-source-sanity',
options: {
projectId: process.env.SANITY_PROJECT_ID,
dataset: process.env.SANITY_DATASET,
token: process.env.SANITY_API_TOKEN,
watchMode: true
}
},
{
resolve: `gatsby-plugin-create-client-paths`,
options: { prefixes: [`/account/*`, `/docs/*`, `/previews/*`] },
Expand All @@ -100,20 +91,6 @@ module.exports = {
},
`gatsby-plugin-typescript`,
`gatsby-plugin-tslint`,
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [
require(`postcss-preset-env`)({ stage: 0 }),
require('postcss-import'),
require('postcss-nested'),
require('postcss-cssnext'),
require('postcss-calc'),
require('postcss-discard-comments'),
require('postcss-reporter')
]
}
},

// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
Expand Down
200 changes: 67 additions & 133 deletions web/gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,139 +1,73 @@

exports.createPages = async ({graphql, actions}) => {
const {createPage} = actions

// Handle Redirects
const redirectsQuery = await graphql(`
{
allSanityRedirect {
edges {
node {
id
fromPath
statusCode
toPath
}
}
}
}
`)

if (redirectsQuery.errors) {
throw redirectsQuery.errors
}

//
// === Redirects ===
//
const redirects = redirectsQuery.data.allSanityRedirect.edges || []
redirects.forEach(redirect => {
const {
fromPath,
toPath,
statusCode
} = redirect.node
actions.createRedirect({
fromPath: fromPath,
toPath: toPath,
isPermanent: statusCode === 301, // use as fallback. this is part of Gatsby's API
statusCode: statusCode || 302 // Netlify specific. Will override `isPermanent`
// Setup environment variables
require('dotenv').config({ path: `.env.${process.env.NODE_ENV || 'development'}` });

const { filter } = require('rxjs/operators');
const client = require('./src/api/sanity');

const {
getAllPageData,
createAllPages,
} = require('./src/build/createPages');

const CURRENT_COMMIT = require('child_process')
.execSync('git rev-parse HEAD')
.toString()
.trim();

exports.createPages = ({ actions }) => new Promise((resolve, reject) => {
getAllPageData()
.then(allResponses => {
createAllPages(
allResponses,
actions,
resolve,
reject
)
});
});

exports.onCreateWebpackConfig = ({
plugins,
actions,
}) => {
actions.setWebpackConfig({
plugins: [
plugins.define({
'process.env.GITCOMMIT': JSON.stringify(CURRENT_COMMIT),
}),
],
});
};

// Query Pages
const pagesQuery = await graphql(`
{
allSanityPage {
edges {
node {
_rawContent(resolveReferences: {maxDepth: 9})
}
}
}
}
`)
exports.onCreatePage = async ({ page, actions }) => {
const { deletePage } = actions;

if (pagesQuery.errors) {
throw pagesQuery.errors
// Delete dev 404 page for accounts to work in dev
if (page.internalComponentName === 'ComponentDev404Page') {
deletePage(page);
}

const pages = pagesQuery.data.allSanityPage.edges || []
pages.forEach((edge, index) => {
const path = `/${edge.node._rawContent.main.slug.current === 'home' ? '' : edge.node._rawContent.main.slug.current}`

createPage({
path,
component: require.resolve('./src/templates/page.tsx'),
context: {...edge.node._rawContent},
};

exports.sourceNodes = async ({
actions,
createContentDigest,
createNodeId,
}) => {
client
.listen('*[!(_id in path("_.**"))]')
.pipe(filter(event => !event.documentId.startsWith('drafts.')))
.subscribe(() => {
const update = { date: new Date() };

actions.createNode({
id: createNodeId(1),
internal: {
type: 'update',
content: JSON.stringify(update),
contentDigest: createContentDigest(update),
},
});

console.log('[gatsby-node]: CMS update triggered');
})
})

// Query Products
const productsQuery = await graphql(`
{
allSanityProduct {
edges {
node {
_rawContent(resolveReferences: {maxDepth: 9})
}
}
}
}
`)

if (productsQuery.errors) {
throw productsQuery.errors
}

const products = productsQuery.data.allSanityProduct.edges || []
products.forEach((edge, index) => {
const path = `/products/${edge.node._rawContent.main.slug.current}`

createPage({
path,
component: require.resolve('./src/templates/product.tsx'),
context: {...edge.node._rawContent},
})
})

// Query Collections
const collectionsQuery = await graphql(`
{
allSanityCollection {
edges {
node {
_rawContent(resolveReferences: {maxDepth: 9})
}
}
}
}
`)

if (collectionsQuery.errors) {
throw collectionsQuery.errors
}

const collections = collectionsQuery.data.allSanityCollection.edges || []
collections.forEach((edge, index) => {
const path = `/collection/${edge.node._rawContent.main.slug.current}`

createPage({
path,
component: require.resolve('./src/templates/page.tsx'),
context: {...edge.node._rawContent},
})
})
}

exports.onCreatePage = ({ page, actions }) => {
const { createPage } = actions
if (page.path.startsWith('/docs')) {
page.context.layout = 'docs'
createPage(page)
}

if (page.path.startsWith('/account')) {
page.context.layout = 'accounts'
createPage(page)
}
}
};
72 changes: 72 additions & 0 deletions web/src/api/queries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const groq = require('groq')

const slugQuery = groq`
'slug': content.main.slug.current
`

const asset = groq`{
_type,
_key,
alt,
caption,
'_id': image.asset->_id,
'dimensions': image.asset->metadata.dimensions,
'url': image.asset->url,
}`


const moduleQuery = groq`
_type == 'nestedPages' => {
...,
page[] {
...,
linkedPage->
}
},
_type == 'productGrid' => {
...,
products[]-> {
...,
}
}
`

const pageQuery = groq`
${slugQuery},
...,
'modules': content.main.modules[] {
...,
${moduleQuery}
},
`

const productQuery = groq`
${slugQuery},
...,
'modules': content.main.modules[] {
...,
${moduleQuery}
},
'main': content.main {
...,
mainImage {
asset-> {
_id
}
}
}
`
module.exports.collections = groq`*[_type == "collection"] {
${pageQuery}
}`
module.exports.pages = groq`*[_type == "page"] {
${pageQuery}
}`

module.exports.products = groq`*[_type == "product"]{
${productQuery}
}`


module.exports.pageQuery = pageQuery
module.exports.productQuery = productQuery
8 changes: 8 additions & 0 deletions web/src/api/sanity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const sanityClient = require('@sanity/client');

module.exports = sanityClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
token: process.env.SANITY_API_TOKEN,
useCdn: false
});
Loading

0 comments on commit 860eecb

Please sign in to comment.