in lib/api.ts [49:166]
async function getSiteMap(): Promise<SiteMap> {
let project: Project;
try {
const projectFromDisk = fs.readFileSync(PROJECT_DATA_PATH);
project = JSON.parse(projectFromDisk.toString());
} catch (er) {
try {
const response = await fetch(
`https://api.figma.com/v1/projects/${process.env.FIGMA_PROJECT_ID}/files`,
{
headers: {
"X-FIGMA-TOKEN": process.env.FIGMA_AUTH_TOKEN,
},
}
);
const contentType = response.headers.get("Content-Type");
if (contentType === "application/json; charset=utf-8") {
project = await response.json();
try {
fs.writeFileSync(PROJECT_DATA_PATH, JSON.stringify(project));
} catch (er) {
console.log(
"There was a problem saving the figma project data to disk."
);
console.log(er);
}
} else {
throw new Error(await response.text());
}
} catch (er) {
console.log("There was a problem fetching the figma project.");
console.log(er);
}
}
let siteMap: SiteMap = [];
try {
const siteMapFromDisk = fs.readFileSync(SITE_MAP_DATA_PATH);
siteMap = JSON.parse(siteMapFromDisk.toString());
} catch (er) {
for (const { key: fileKey, name: fileName } of project.files) {
let file: File;
try {
const response = await fetch(
`https://api.figma.com/v1/files/${fileKey}?depth=2`,
{
headers: {
"X-FIGMA-TOKEN": process.env.FIGMA_AUTH_TOKEN,
},
}
);
const contentType = response.headers.get("Content-Type");
if (contentType === "application/json; charset=utf-8") {
file = await response.json();
} else {
throw new Error(await response.text());
}
} catch (er) {
console.log(`There was a problem fetching the figma file ${fileKey}.`);
console.log(er);
}
// Bail early if figma file is mal-formed.
if (!file || !file.document) {
console.log("The figma file we got is mal-formed.");
console.log(file);
return [];
}
// Only use figma canvases and visible frames that start with a capital letter.
// Note, we intentionally leave out most of the data sent over from Figma
// because static prop data is inlined on the page.
for (const canvas of file.document.children) {
console.log(file.name, canvas.name, canvas.type);
if (canvas.name.match(/^[A-Z]/)) {
const section: Section = {
id: canvas.id,
name: canvas.name,
children: [],
};
for (const frame of canvas.children) {
console.log(" ", frame.name, frame.type);
if (
frame.type === "FRAME" &&
frame.name.match(/^[A-Z]/) &&
frame.visible !== false // `visible` is only present when it is false
) {
const page: Page = {
id: frame.id,
name: frame.name,
// Add some additional metadata to make things easier later on.
key: getPageKey(canvas, frame),
fileKey,
fileName,
sectionName: section.name,
};
section.children.push(page);
}
}
if (section.children.length > 0) {
siteMap.push(section);
}
}
}
}
try {
fs.writeFileSync(SITE_MAP_DATA_PATH, JSON.stringify(siteMap));
} catch (er) {
console.log(
`There was a problem saving the figma project files to disk.`
);
console.log(er);
}
}
return siteMap;
}