Sync your Webflow database with Airtable Scripts

01 - Introduction


const config = input.config({
    title: 'Script Settings',
    items: [
        input.config.text('webflowAPI', {
            label: 'Webflow API Key',
        }),
        input.config.text('collectionID', {
            label: 'Collection ID',
        })
    ]  
});

//Import table for updating
let table = base.getTable("Category");
let query = await table.selectRecordsAsync();
let records = query.records;

//Run script for each record within the array of records
for (let record of records) {
    //Filter by status
    // if(record.getCellValue("Status").name === "Live" && (record.getCellValue("Status").name === "Archive" || yesterday)){
    if(record.getCellValue("Status").name === "Live"){
        let webflowID = record.getCellValue("Webflow Item ID");
        let body = {"fields":{
            "hero-title": record.getCellValue("Hero Title"),
            "page-description": record.getCellValue("Hero Paragraph"),
            "job-title": record.getCellValue("Job Title (Plural)")        
            }};

        //update record in Webflow
        let response = await remoteFetchAsync(`https://api.webflow.com/collections/${config.collectionID}/items/${webflowID}?live=true`, {
            method: 'PATCH',
            body: JSON.stringify(body),
            headers: {
                    'Content-Type': 'application/json',
                    'Authorization':config.webflowAPI,
                    'accept-version':'1.0.0'
                    },
        });

        //Error Handling
        //200 status - ok
        if (response.status == 200){
            //write script
            console.log(response);
        }
        //400 status - validation error
        else if (response.status == 400){
            let res_body = await response.json();
            if (res_body.name == "ValidationError"){
                //update our airtable record with "error" status
                await table.updateRecordAsync (record.id, {
                    "Status":{
                        "name":"Error"
                    },
                    "Error Message": res_body.problems[0]
                })
                console.log(response);
            }
        }else if (response.status == 429){
            delay(1000);
            console.log(response);
        }
        //429 status - rate limits

        }
    }

//Delay function for when we hit rate limits
function delay(ms) {
    let limit = new Date();
    limit = limit.setMilliseconds(limit.getMilliseconds() + ms);
    while ((new Date()) < limit) {
        // do nothing
        ;
    }
}