This is an example script that will auto create/update a record and increment a value. Follow the instructions in code to play with it.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
// How to use:
//
// 1. Copy this Airtable Base.
// 👉 https://airtable.com/invite/l?inviteId=invyenIPlRvVXfxYe&inviteToken=68995afd8f87ea4b2b4ecb30211685e041b632f3e1415b9dad6700ab4fe711e0&utm_source=email
//
// 2. Set the BASE_ID environment variable to your base ID.
// It should look like 'app2otWR3klf9FbhJ' and be in the url.
//
// 3. Click 'Run' a fw times and watch the row changes in Airtable.
// You should notice rows are added and updated with varying values.
const tableName = 'MyTable';
const userId = Math.floor(Math.random() * 3) + 1;
// Try find the row with our user ID
const selectResponse = await lib.airtable.query['@1.0.0'].select({
baseId: process.env.BASE_ID,
table: tableName,
where: [
{
UserId__is: userId,
},
],
});
const records = selectResponse.rows;
// Does the record already exist?
if (records.length) {
// The record exists, let's update it.
const record = records[0];
console.log(`Found record`, JSON.parse(JSON.stringify(record)));
const fields = record.fields;
await lib.airtable.query['@1.0.0'].records.update({
baseId: process.env.BASE_ID,
table: tableName,
id: record.id,
fields: {
Notes: `Updated!`,
UpdateCount: fields.UpdateCount + 1,
},
});
} else {
// The record doesn't exist yet, let's create it.
console.log(`Creating record for ID`, userId);
await lib.airtable.query['@1.0.0'].insert({
baseId: process.env.BASE_ID,
table: tableName,
fieldsets: [
{
UserId: userId,
Notes: `Created!`,
UpdateCount: 0,
},
],
});
}