JavaScript
// home.js: runs on the front end's server (Node 18 or later)
const SITE = process.env.COREDNA_URL; // https://www.example.com
const KEY = process.env.COREDNA_API_KEY; // never shipped to the browser
const HOME_QUERY = `query {
sections: Page(filter: {parent.id: 1}, orderBy: {position: "ASC"}, first: 6) {
id, name, fullPath
}
latest: BlogPost(filter: {blog.id: 1}, first: 3, orderBy: {published: "DESC"}) {
id, name, fullPath, published(format: "Y-m-d")
}
nav: MenuElement(menu: 1, filter: {parent: null}, orderBy: {position: "ASC"}, first: 10) {
id, name, url
}
}`;
let cached = null;
let cachedAt = 0;
export async function homeContent() {
if (cached && Date.now() - cachedAt < 60_000) return cached;
const response = await fetch(SITE + '/cdna-api/graphql', {
method: 'POST',
headers: { Authorization: 'Bearer ' + KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query: HOME_QUERY }),
});
const body = await response.json();
if (!response.ok || body.result !== 'success') {
throw new Error('GraphQL failed: ' + response.status + ' ' + (body.message || ''));
}
for (const [part, records] of Object.entries(body.data)) {
const bad = records.find(r => Object.values(r).some(v => typeof v === 'string' && v.startsWith('Error: Getter')));
if (bad) throw new Error('Unknown field in part "' + part + '": ' + JSON.stringify(bad));
}
cached = body.data; // { sections: [...], latest: [...], nav: [...] }
cachedAt = Date.now();
return cached;
}
The same request from a shell, for checking a site's data before writing any code:
Shell
curl "$COREDNA_URL/cdna-api/graphql" \
--header "Authorization: Bearer $COREDNA_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"query": "query { sections: Page(filter: {parent.id: 1}, first: 6) { id, name, fullPath }, latest: BlogPost(first: 3, orderBy: {published: \"DESC\"}) { id, name, fullPath }, nav: MenuElement(menu: 1, filter: {parent: null}) { id, name, url } }"}'