Mantil-template-form-to-dynamodb - Receive form data and write it to a DynamoDB table

About

This template is an example of serverless integration between Google Forms and DynamoDB. An AWS Lambda function built with Mantil receives data from a Google Form and saves the data to a DynamoDB table.

Prerequisites

This template is created with Mantil. To download Mantil CLI on Mac or Linux use Homebrew:

brew tap mantil-io/mantil
brew install mantil

or check direct download links.

To deploy this application you will need:

Installation

To locally create a new project from this template run:

mantil new app --from https://github.com/mantil-io/template-form-to-dynamodb
cd app

Setup

Deploy the application

Note: If this is the first time you are using Mantil you will first need to install Mantil Node on your AWS account. For detailed instructions please follow these simple, one-step setup instructions

mantil aws install

Now you can deploy the appliation to AWS.

mantil deploy

This command will create a new stage for your project with default name development and deploy it to your node.

Now test the API by calling

mantil invoke form/list

This call lists all rows in the database table. Initially, there are none, and so the result is empty. You'll see some log output that shows that everything works fine.

$ mantil invoke form/list
λ github.com/mantil-io/go-mantil-template/api/form/form.go:81: List called
λ github.com/mantil-io/go-mantil-template/api/form/form.go:88: 0 []

To fill the table with data, we will use a Google form.

Deploy a Google Form

Create the form

First, create a new form in Google from the "Party Invite" template.

  • Open https://docs.google.com/forms/u/0/

  • Log in to Google if not logged in already

  • For this example, select the predefined template named "Party Invite" and save a copy to your Google Drive.

    Party Invite

Add an App Script to trigger a webhook call

Standard Google forms cannot call a webhook on form submit. You might find a plugin on the Forms Marketplace, but here we want to look into setting up a script for that purpose.

  • On the Form design page, click the three-dots menu and select Script editor.

    script editor menu

    A new script project opens.

    script project

  • Replace the default code with the following script.

    var POST_URL = "https://CHANGEME.execute-api.REGION.amazonaws.com";
    function onSubmit(e) {
    	var form = FormApp.getActiveForm();
    	var allResponses = form.getResponses();
    	var latestResponse = allResponses[allResponses.length - 1];
    	var response = latestResponse.getItemResponses();
    	var payload = {};
    	for (var i = 0; i < response.length; i++) {
    		var question = response[i].getItem().getTitle();
    		var answer = response[i].getResponse();
    		payload[question] = answer;
    	}
    
    	console.log(JSON.stringify(payload))
    
    	var options = {
    		"method": "post",
    		"contentType": "application/json",
    		"payload": JSON.stringify(payload)
    	};
    UrlFetchApp.fetch(POST_URL + "/form/save", options);
    };
  • In your shell, call

    mantil env --url
    

    and replace the POST_URL value in the script with the URL from your Mantil environment.

    You can paste the URL to the script as it is. The script adds the final endpoint form/save automatically.

    Note: if you destroy the current stage and create it again, the URL will change, and you need to adjust the URL in the script accordingly. Same applies to switching to a different stage.

  • You can give the project a suitable title, like, e.g., Mantil Webhook.

    webhook script

Add a trigger

  • Now switch from the script editor to the trigger page (click the alarm clock symbol on the left side bar) and create a new trigger.

    add trigger

  • In the Edit Trigger form, select Event Type = On Form Submit and save the trigger.

    Note: Google Forms might ask you at this point to approve the script, if you trust the developer (that is, yourself).

    on form submit

    This setup causes the form to send a Webhook to the Lambda function endpoint /forms/save every time someone submits the form.

    trigger created

Test the Lambda function

Now it is time for a first test.

  • On the form designer page, click the Preview icon.

    preview icon

  • In the form preview, fill out and submit the form one or two times.

  • Then call

    mantil invoke form/list
    

    and see if the data appears in the output. You should see the forms that you submitted previously. They have been stored to a DynamoDB table that form/list retrieves them from.

    200 OK
    [
       {
          "What is your name?": "Mantil",
          "Can you attend?": "Yes,  I'll be there",
          "How many of you are attending?": "20",
          "What will you be bringing?": [
             "Drinks",
             "Sides/Appetizers"
          ],
          "Do you have any allergies or dietary restrictions?": "",
          "What is your email address?": "[email protected]"
       }
    ]
    

And that's all! Now you can save the RSVP's of all your party guests right in DynamoDB.

Bonus: stage-specific behavior

The code reads the table name from the environment. Mantil provides an environment.yml file that allows setting stage-specific variables.

For this demo, the table name is set at stage level:

project:
  stages:
    - name: development
      env:
        TABLE_NAME: MantilPartyDev
    - name: production
      env:
        TABLE_NAME: MantilParty

Look into your Amazon account and inspect the DynamoDB tables. After having deployed to the development stage as described above, you should see a table whose name contains "MantilPartyDev".

If you now create a new stage named "production" and invoke the Lambda function there...

mantil stage new production
mantil stage use production
mantil invoke form/list

...then you can see a new table in DynamoDB whose name contains "MantilParty" without the "Dev".

dynamodb tables

Modification

If you want different behavior out of your project you can add more triggers by creating new webhooks and new functions. Examples of payloads for all Github events can be found in their docs.

Adding new function will be demonstrated with fork function which sends slack notification every time your repository gets forked. Implementation of this function is already available in the repository.

New function was created with

mantil generate api fork

This generated necessary files for our new lambda function which was then further edited to suit our needs. In the case of fork function api/fork.go contains necessary logic for this trigger.

Together with the function another Github trigger was created containing $(mantil env -u)/fork payload URI and Fork as an event.

After each change you have to deploy your changes with mantil deploy, or instruct Mantil to automatically deploy all saved changes with mantil watch.

For more detailed instructions please refer to Mantil documentation.

Cleanup

To remove the created stage with all resources from your AWS account destroy it with

mantil stage destroy development

To uninstall Mantil from your AWS account completely, run

mantil aws uninstall

(Remember to pass the credentials and the region to this command, as you did with the install command - either through flags or env variables, or from the AWS config.)

Final thoughts

With this template you learned how to use Mantil to create a simple AWS Lambda application that saves a Google form to a DynamoDB table. Check out our documentation to find more interesting templates.

If you have any questions or comments on this concrete template or would just like to share your view on Mantil contact us at [email protected] or create an issue.


The Google Forms script was taken over from Sending a Webhook for each Google Forms Submission | by Eyal Gershon | Medium, with thanks to the author.

Similar Resources

Distributed reliable key-value store for the most critical data of a distributed system

etcd Note: The master branch may be in an unstable or even broken state during development. Please use releases instead of the master branch in order

Jan 9, 2023

VectorSQL is a free analytics DBMS for IoT & Big Data, compatible with ClickHouse.

NOTICE: This project have moved to fuse-query VectorSQL is a free analytics DBMS for IoT & Big Data, compatible with ClickHouse. Features High Perform

Jan 6, 2023

datatable is a Go package to manipulate tabular data, like an excel spreadsheet.

datatable is a Go package to manipulate tabular data, like an excel spreadsheet.

datatable is a Go package to manipulate tabular data, like an excel spreadsheet. datatable is inspired by the pandas python package and the data.frame R structure. Although it's production ready, be aware that we're still working on API improvements

Nov 23, 2022

This is a mongodb data comparison tool.

mongo-compare This is a mongodb data comparison tool. In the mongodb official tools, mongodb officially provides a series of tools such as mongodump,

Sep 13, 2022

Membin is an in-memory database that can be stored on disk. Data model smiliar to key-value but values store as JSON byte array.

Membin Docs | Contributing | License What is Membin? The Membin database system is in-memory database smiliar to key-value databases, target to effici

Jun 3, 2021

Nipo is a powerful, fast, multi-thread, clustered and in-memory key-value database, with ability to configure token and acl on commands and key-regexes written by GO

Welcome to NIPO Nipo is a powerful, fast, multi-thread, clustered and in-memory key-value database, with ability to configure token and acl on command

Dec 28, 2022

Being played at The Coffee House and try to find and play it on Spotify

Being played at The Coffee House and try to find and play it on Spotify

The Coffee House Muzik Follow the music that is being played at The Coffee House and try to find and play it on Spotify. Installation Clone this proje

May 25, 2022

Walrus - Fast, Secure and Reliable System Backup, Set up in Minutes.

Walrus - Fast, Secure and Reliable System Backup, Set up in Minutes.

Walrus is a fast, secure and reliable backup system suitable for modern infrastructure. With walrus, you can backup services like MySQL, PostgreSQL, Redis, etcd or a complete directory with a short interval and low overhead. It supports AWS S3, digitalocean spaces and any S3-compatible object storage service.

Jan 5, 2023

BuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support

BuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support

BuntDB is a low-level, in-memory, key/value store in pure Go. It persists to disk, is ACID compliant, and uses locking for multiple readers and a sing

Dec 30, 2022
A go library for testing Amazon DynamoDB.

minidyn Amazon DynamoDB testing library written in Go. Goals Make local testing for DynamoDB as accurate as possible. Run DynamoDB tests in a CI witho

Nov 9, 2022
🔑A high performance Key/Value store written in Go with a predictable read/write performance and high throughput. Uses a Bitcask on-disk layout (LSM+WAL) similar to Riak.

bitcask A high performance Key/Value store written in Go with a predictable read/write performance and high throughput. Uses a Bitcask on-disk layout

Sep 26, 2022
Time Series Database based on Cassandra with Prometheus remote read/write support

SquirrelDB SquirrelDB is a scalable high-available timeseries database (TSDB) compatible with Prometheus remote storage. SquirrelDB store data in Cass

Oct 20, 2022
Multiple databases, read-write splitting FOR GORM

DBResolver DBResolver adds multiple databases support to GORM, the following features are supported: Multiple sources, replicas Read/Write Splitting A

Jan 6, 2023
Owl is a db manager platform,committed to standardizing the data, index in the database and operations to the database, to avoid risks and failures.

Owl is a db manager platform,committed to standardizing the data, index in the database and operations to the database, to avoid risks and failures. capabilities which owl provides include Process approval、sql Audit、sql execute and execute as crontab、data backup and recover .

Nov 9, 2022
A simple, fast, embeddable, persistent key/value store written in pure Go. It supports fully serializable transactions and many data structures such as list, set, sorted set.

NutsDB English | 简体中文 NutsDB is a simple, fast, embeddable and persistent key/value store written in pure Go. It supports fully serializable transacti

Jan 1, 2023
Distributed cache and in-memory key/value data store.

Distributed cache and in-memory key/value data store. It can be used both as an embedded Go library and as a language-independent service.

Dec 30, 2022
Efficient cache for gigabytes of data written in Go.

BigCache Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. BigCache keeps entries on hea

Jan 4, 2023
:handbag: Cache arbitrary data with an expiration time.

cache Cache arbitrary data with an expiration time. Features 0 dependencies About 100 lines of code 100% test coverage Usage // New cache c := cache.N

Jan 5, 2023
Lightweight RESTful database engine based on stack data structures
Lightweight RESTful database engine based on stack data structures

piladb [pee-lah-dee-bee]. pila means stack or battery in Spanish. piladb is a lightweight RESTful database engine based on stack data structures. Crea

Nov 27, 2022