Created
July 15, 2018 18:35
-
-
Save mraerino/dee37c4d5d0c7268356f3e4dbd811b60 to your computer and use it in GitHub Desktop.
GatsbyJS: Fetching the Graphql schema as soon as it is available and saving it into a local file in `.cache`
This file contains hidden or 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 request = require('request-promise-native'); | |
const fs = require('fs').promises; | |
const delay = require('delay'); | |
const { introspectionQuery } = require('graphql/utilities/introspectionQuery'); | |
const maxRetries = 4 | |
exports.onPostBootstrap = () => { | |
(async () => { | |
let remainingRetries = maxRetries; | |
while(remainingRetries > 0) { | |
const delaytime = (maxRetries - remainingRetries + 1) * 1500; | |
await delay(delaytime); | |
try { | |
const schema = await request.post({ | |
uri: 'http://localhost:8000/___graphql', | |
body: { query: introspectionQuery }, | |
json: true, | |
}); | |
try { | |
await fs.writeFile(path.resolve(__dirname, './.cache/content-schema.json'), JSON.stringify(schema)); | |
} catch(e) { | |
console.error('Schema writing failed:', e.message); | |
} | |
return; | |
} catch(e) { | |
remainingRetries--; | |
if (remainingRetries <= 0) { | |
console.warn("Could not fetch GraphQL Schema:", e.message); | |
} | |
} | |
} | |
})(); | |
// don't return a promise to run while build continues | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment