const express = require('express');
const app = express()
app.use(express.json());
var Airtable = require('airtable');
var base = new Airtable({apiKey: process.env.AIRTABLE_API_KEY}).base(process.env.PLANETS_BASE);
app.listen(3000, () => console.log('Example app listening on port 3000!'))
app.get('/', (req, res) => {
var resp = '';
let responseJson = {};
responseJson.fulfillmentText = 'This is an endpoint published to RunKit'; // displayed response
base('PlanetsTable').select({
maxRecords: 1,
filterByFormula: 'AND({Planet} = "Earth",{Attribute}="Volume")',
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
resp += 'The ' + record.get('Attribute')+' of '+ record.get('Planet')+ ' is '+record.get('Value');
console.log('Retrieved', record.get('Value'));
});
fetchNextPage();
}, function done(err) {
if (err) { console.error(err); return; }
res.send(resp);
});
})
app.post('/', function (req, res) {
console.log(req);
let action = req.body.queryResult.action;
console.log(action);
let responseJson = {};
responseJson.fulfillmentText = 'This is an endpoint published to RunKit'; // displayed response
if(action === 'getPlanetAttribute'){
let planetName = req.body.queryResult.parameters.planet;
let attributeName = req.body.queryResult.parameters.attribute;
var request = require("request");
let responseJson = {};
responseJson.fulfillmentText = 'This is an endpoint published to RunKit'; // displayed response
base('PlanetsTable').select({
maxRecords: 1,
filterByFormula: 'AND({Planet} = "'+planetName+'",{Attribute}="'+attributeName+'")',
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
console.log('Retrieved', record.get('Value'));
responseJson.fulfillmentText = 'The ' + attributeName+' of '+ planetName+ ' is '+record.get('Value');
res.json(responseJson);
});
fetchNextPage();
}, function done(err) {
if (err) { console.error(err); return; }
res.send(resp);
});
}
else if(action === 'changedAttribute'){
//let planetName = req.body.queryResult.parameters.planet;
let attributeName = req.body.queryResult.parameters.attribute;
let contexts = req.body.queryResult.outputContexts;
console.log(contexts);
var item = contexts.find(item => item.name.endsWith('/contexts/planet-attribute-set'));
var planetName = item.parameters.planet;
var request = require("request");
let responseJson = {};
responseJson.fulfillmentText = 'This is an endpoint published to RunKit'; // displayed response
base('PlanetsTable').select({
maxRecords: 1,
filterByFormula: 'AND({Planet} = "'+planetName+'",{Attribute}="'+attributeName+'")',
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
console.log('Retrieved', record.get('Value'));
responseJson.fulfillmentText = 'The ' + attributeName+' of '+ planetName+ ' is '+record.get('Value');
res.json(responseJson);
});
fetchNextPage();
}, function done(err) {
if (err) { console.error(err); return; }
res.send(resp);
});
}
})