Microservice Recipe: Local Database Connectivity

Service Recipes > Local Database Connectivity
17 Jun 2017

Connecting an Eventn microservice to a local MySQL Database

When developing microservices it is often useful to be able to connect to a database hosted on your local machine. This makes testing and schema design simple and fast. The challenge however is exposing the local database to the public internet. That's where Ngrok comes in. Ngrok is a fantastic utility that creates secure tunnels to localhost.

Setup

For database connectivity, we will need a TCP tunnel. The TCP functionality requires ngrok to be authenticated which requires signing up at https://ngrok.com/. Its simple and free. Once done, download ngrok to your local machine and install the auth token as per the Getting Started Guide.

In this example we will connect to a MySQL database running onlocalhoston port3306. To create the ngrok tcp tunnel simply run:

./ngrok tcp 3306

That will start the tunnel service and output something like:

Web Interface                 http://127.0.0.1:4040
Forwarding                    tcp://0.tcp.ngrok.io:18065 -> localhost:3306

We can now use the forwarding address to create a database connection using a Store Adapter within Eventn. The Store Adapter interface requires a connection string to connect to the database. We can simply substitute the host and port with those provided by ngrok:

mysql://root:password@0.tcp.ngrok.io:18065/demo

To create a new Store Adapter, either the API or UI can be used. To use the API, see the user guide here or to use the UI, simply select theStoretab for any service:

Microservice Database Connection

Usage

To use the store adapter, simply call it from within the microservice. Here we request all rows from the DB when a GET request is made:

function onGet(context) {
    return context.stores.foo().table().select();
}
module.exports = onGet;

Inserting data on POST:

function onPost(context, request) {
    return context.stores.foo().table().insert({ data: JSON.stringify(request.payload) });
}
module.exports = onPost;

Happy hacking!

Get Started For Free

Get Started