diff --git a/.gitignore b/.gitignore index c575cdc..4af5d5f 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,6 @@ yarn-error.log* # Local Netlify folders .netlify -functions # Logs logs diff --git a/functions/get-questions/get-questions.js b/functions/get-questions/get-questions.js new file mode 100755 index 0000000..1d15cfc --- /dev/null +++ b/functions/get-questions/get-questions.js @@ -0,0 +1,57 @@ +// import Airtable.js package +// import Airtable from 'airtable'; // produces a SyntaxError ('cannot use import statement outside a module') +const Airtable = require('airtable'); + +// import local environment variables if in dev environment - is this necessary? +// import dotenv from 'dotenv'; +// if (process.env.NODE_ENV === 'development') { +// dotenv.config() +// { AIRTABLE_API_URL, AIRTABLE_API_KEY, AIRTABLE_BASE_ID } = process.env; +// } + +// Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method +// the handler function can take event and context params (not required in this case) +// it can also take a callback as third argument, but we will stick to promises +exports.handler = async () => { + // grab airtable variables from Netlify environment (uploaded via UI) + const { AIRTABLE_API_KEY, AIRTABLE_BASE_ID, AIRTABLE_API_URL } = process.env; + + // configure connection to airtable base + Airtable.configure({ + endpointUrl: AIRTABLE_API_URL, + apiKey: AIRTABLE_API_KEY, + }); + const base = Airtable.base(AIRTABLE_BASE_ID); + + let data = []; + + // select all records - only need to check first page since questions won't exceed 100 entries + // need an await to ensure data is assigned to records before returning response + await base('UserQuestions') + .select({ + maxRecords: 100, + view: 'Grid view', + }) + .firstPage() + .then(records => { + records.forEach(record => { + data.push(record.fields); + }); + }) + .catch(err => { + console.log(err.status); + }); + + // finally return any data collected as body of a response object + try { + return { + statusCode: 200, + body: JSON.stringify(data), + headers: { + 'content-type': 'application/json', + }, + }; + } catch (err) { + return { statusCode: 500, body: err.toString() }; + } +}; diff --git a/src/App/App.js b/src/App/App.js index e4605bb..4fb21a8 100644 --- a/src/App/App.js +++ b/src/App/App.js @@ -9,6 +9,8 @@ import { getQuestions } from '../utils/getData'; function App() { const [questions, setQuestions] = useState(null); + console.log(process.env.NODE_ENV); + useEffect(() => { getQuestions().then(records => { console.log(records);