Last active
August 2, 2021 16:15
-
-
Save d4rekanguok/70175a936faa4ab708c3d5cb418d920f to your computer and use it in GitHub Desktop.
Script to fetch metadata w/ Sanity before initiating Gatsby/Next/etc.
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
const path = require('path') | |
const fs = require('fs/promises') | |
require('dotenv').config({ | |
// vvvvvvvvvv replace w/ your env | |
path: path.resolve(process.cwd(), '.env.local') | |
}) | |
const createClient = require('@sanity/client') | |
const client = createClient({ | |
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, | |
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, | |
token: process.env.SANITY_EDITOR_TOKEN, | |
useCdn: process.env.NEXT_PUBLIC_ENV === 'production', | |
}) | |
const fetchMeta = async () => { | |
console.log(`Pre-export: Fetching metadata`) | |
const data = await client.fetch(`*[_id == 'config_site'][0]`) | |
// { "url": "https://www.foo.bar", etc. } | |
if (!data) { | |
throw new Error(`No data found.`) | |
} | |
await fs.writeFile(path.resolve(process.cwd(), 'temp/data.json'), JSON.stringify(data)) | |
console.log(`Pre-export: Successfully fetched metadata.`) | |
} |
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
{ | |
"name": "foo", | |
"scripts": { | |
"preexport": "node ./scripts/fetch-meta.js", | |
"export": "next build && next export", | |
"prebuild": "node ./scripts/fetch-meta.js", | |
"build": "next build" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment