Skip to content

Instantly share code, notes, and snippets.

@jbmoelker
Created January 23, 2021 17:53
Show Gist options
  • Save jbmoelker/11be7aaf4400d309305c9e5c2c72f0ef to your computer and use it in GitHub Desktop.
Save jbmoelker/11be7aaf4400d309305c9e5c2c72f0ef to your computer and use it in GitHub Desktop.
GraphQL extension for Eleventy
const queryDatoGraphQL = require('./query-dato-graphql.js');
module.exports = function (config) {
// Custom data file formats (https://www.11ty.dev/docs/data-custom/)
config.addDataExtension(
'graphql',
async (query) => await queryDatoGraphQL({ query })
);
// Base Config
return {
dir: {
input: 'src',
output: 'dist',
includes: 'components',
layouts: 'layouts',
data: 'data',
},
templateFormats: ['njk', '11ty.js'],
htmlTemplateEngine: 'njk',
markdownTemplateEngine: 'njk',
};
};
// complete example with caching
const fetch = require('node-fetch');
require('dotenv-safe').config();
const isDevelopment = (process.env.ELEVENTY_ENV === 'development');
const isPreview = (process.env.APP_PREVIEW === 'true');
const endpoint = (isDevelopment || isPreview)
? 'https://graphql.datocms.com/preview'
: 'https://graphql.datocms.com/';
const useCache = true;
let cache = {};
function requestToMessage({ query, variables }) {
const queryName = (query.match(/^query ([A-z]+)/) || [])[1] || '(unnamed query)';
// return `"${queryName}" (${JSON.stringify({ variables })})`;
return `"${queryName}"`;
}
module.exports = ({ query, variables }) => {
const cacheKey = JSON.stringify({ query, variables });
if (useCache && cache[cacheKey]) {
console.log(`using cached data for ${requestToMessage({ query, variables })}`);
return cache[cacheKey];
}
console.log(`fetching fresh data for ${requestToMessage({ query, variables })}`);
cache[cacheKey] = fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${ process.env.DATO_API_TOKEN }`,
},
body: JSON.stringify({ query, variables })
})
.then(response => {
if (response.status != 200) {
throw new Error(`Invalid request (${response.status})`);
} else {
return response.json();
}
})
.then(response => {
if (response.errors && response.errors.length) {
throw new Error(response.errors[0].message);
} else {
return response.data;
}
});
return cache[cacheKey];
}
// simplified
const fetch = require('node-fetch');
const endpoint = 'https://graphql.datocms.com/';
module.exports = ({ query /*, variables */ }) => {
return fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${ process.env.DATO_API_TOKEN }`,
},
body: JSON.stringify({ query /*, variables */ })
})
.then(response => {
if (response.status != 200) {
throw new Error(`Invalid request (${response.status})`);
} else {
return response.json();
}
})
.then(response => {
if (response.errors && response.errors.length) {
throw new Error(response.errors[0].message);
} else {
return response.data;
}
});
}
query Articles {
allArticles {
title
slug
image {
alt
url
width
height
}
etc
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment