import { allRecordsForProject } from './records'; import { getName, MERCHANT_RECORDS, TYPE } from './constants'; const ErrorType = { MultipleSameRecordType: 'Multiple of same record type', DoesntExist: 'Zero records for merchant', NoMerchant: 'No merchant record', MultipleRecords: 'Multiple records', MissingRecord: 'Missing record' }; interface ErrorFormat { type: string; info: any; } async function reportCounts(merchantRecords: string[]): Promise { const counts: any = {}; const errors: ErrorFormat[] = []; const SINGLE_RECORDS = [ TYPE.merchant, TYPE.themeConfiguration, TYPE.siteConfig, TYPE.footerLayout, TYPE.headerLayout, TYPE.globalButton ]; MERCHANT_RECORDS.forEach(itemTypeId => { const key = getName(itemTypeId); const count: number = merchantRecords.filter((record: any) => { return record.itemType === itemTypeId; }).length; if (SINGLE_RECORDS.includes(itemTypeId)) { if (count === 0) { errors.push(createError(ErrorType.MissingRecord, { key })); } if (count > 1) { errors.push(createError(ErrorType.MultipleRecords, { key })); } } counts[key] = count; }); return {counts, errors}; } function createError(type: string, info: any): ErrorFormat { return { type, info }; } /* Setup here refers to setting up initial DatoCMS records */ async function shouldSetupProject(projectId: string): Promise { const merchantRecords = await allRecordsForProject(projectId); if (merchantRecords == null) { console.log('Project doesnt exist', projectId); return true; } const report: any = await projectHealth(projectId, merchantRecords); const allZero = Object.keys(report.counts) .every((value: any) => { return value === 0; }); return allZero; } /* Build here refers to 'gatsby build' */ async function canBuildProject(projectId: string): Promise { const merchantRecords = await allRecordsForProject(projectId); if (merchantRecords == null) { console.error('Project doesnt exist', projectId); return false; } const report: any = await projectHealth(projectId, merchantRecords); if (report.errors.length > 0) { console.error(`canBuildProject:: Cant build project cause of ${report.errors.length} errors`); console.error(JSON.stringify(report.errors, null, 4)); return false; } return true; } async function projectHealth(projectId: string, merchantRecords: any): Promise { const errors: ErrorFormat[] = []; if (merchantRecords === null) { return ErrorType.DoesntExist; } const countsReport: any = await reportCounts(merchantRecords); // TODO Netlify js doesn't like .flat()... countsReport.errors.forEach((error: ErrorFormat) => { errors.push(error); }); return { projectId, counts: countsReport.counts, errors }; } exports.projectHealth = projectHealth; exports.shouldSetupProject = shouldSetupProject; exports.canBuildProject = canBuildProject;