Store data in a database

Every Joule can store data which can be accessed at any time. This is important because Joules are stateless and do not typically retain any information across requests.

The built-in database provided for your Joule is a simple key/value datastore. You are not limited to the built-in database though. If you'd like to use another database then include your connection information as environment variables and require the needed packages in your Joule.

You can look at this Joule which connects to MongoDB as an example.

Simulating the database for local verification

You can set an environment variable in your events.json file when working on your Joule locally. Simply add an environment variable named DB_LOCAL and provide any value you'd like.

{
  "env": {
    "DB_LOCAL": "any_value"
  }
}

Requiring the built-in database's client

Install joule-node-database if you'd like to use the built-in database.

npm install joule-node-database --save

Once the built-in database client has been installed you can require it in your code.

var JouleNodeDatabase = require('joule-node-database');
var myDb = new JouleNodeDatabase();

How to store data in your Joule database

In order to store data into your database you need to pass a key and value to the set() method.

var JouleNodeDatabase = require('joule-node-database');
var myDb = new JouleNodeDatabase();

myDb.set('user@example.com', {username: 'example_user'}).done(function(data) {
  console.log(data);
});

How to fetch data from your Joule database

If you'd like to read data out of your database you need to pass a key to the get() method.

var JouleNodeDatabase = require('joule-node-database');
var myDb = new JouleNodeDatabase();

myDb.get('user@example.com').done(function(data) {
  console.log(data);
});

Callbacks using promises

The joule-node-database module uses promises to handle asynchronous writes to the database. You can provide a callback function to the then() or done() methods. Your function will receive two parameters; err and data.

Here is an example of handling both a failure and a success when accessing the database.

var JouleNodeDatabase = require('joule-node-database');
var myDb = new JouleNodeDatabase();

myDb.get('user@example.com').done(function(data) {
  if(!data) {
    console.log('There was an error');
    return;
  }

  console.log('Database accessed successfully');
  console.log(data);
});

You can learn all about promises on the promisejs.org website.