Last active
February 21, 2022 14:55
-
-
Save theGove/ba7616483c4a44ea0fdc8a2cdf9e5511 to your computer and use it in GitHub Desktop.
Tools for integrating JADE with airtable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jade.use("excel_tools") | |
class airtable_tools{ | |
static async query(base_id, table, token, fields, filter_formula, sheet_name, address){ | |
const data=await airtable_tools.get_airtable_data(base_id, token, table, filter_formula,fields) | |
if(!fields){ | |
fields=[] | |
//fields were not specified so we must scan all the data to find the complete set of fields | |
for(const record of data.records){ | |
for(const key of Object.keys(record.fields)){ | |
//console.log(key) | |
if(!fields.includes(key)){ | |
fields.push(key) | |
} | |
} | |
} | |
} | |
const range_data=[fields] | |
for(const record of data.records){ | |
const row=[] | |
for(const field of fields){ | |
const element=record.fields[field] | |
if(element){ | |
if(Array.isArray(element)){ | |
if(element.length===1){ | |
if(element[0].url){ | |
row.push(element[0].url) | |
}else{ | |
row.push(element[0]) | |
} | |
}else{ | |
row.push("") | |
} | |
}else{ | |
row.push(element) | |
} | |
}else{ | |
row.push("") | |
} | |
} | |
range_data.push(row) | |
} | |
if(sheet_name){ | |
if(!address){address="a1"} | |
await excel_tools.array_to_table(sheet_name,address,range_data) | |
} | |
return range_data | |
} | |
static async get_airtable_data(base_id, token, table, filter_formula, fields){ | |
let field_list="" | |
for(const field of fields){ | |
field_list += "&fields%5B%5D=" + encodeURIComponent(field) | |
} | |
let record_limit = 100 | |
let offset="" | |
let filter_by_formula="" | |
if(filter_formula){filter_by_formula = "&filterByFormula=" + encodeURIComponent(filter_formula)} | |
const url="https://api.airtable.com/v0/" + base_id + "/" + table + "?maxRecords=" + record_limit + filter_by_formula + field_list | |
//console.log("url",url) | |
const airtable={records:[]} | |
try{ | |
do { | |
const response = await fetch(url + offset,{ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: 'Bearer ' + token }}) | |
const airtable_fetch = await response.json() | |
airtable.records=airtable.records.concat(airtable_fetch.records) | |
if (airtable_fetch.offset){ | |
offset="&offset=" + airtable_fetch.offset | |
}else{ | |
offset="" | |
} | |
} while (offset!==""); | |
return airtable | |
}catch(err){ | |
;console.log("Error in getting airtable data", err) | |
return {} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment