Brain - 18F/charlie GitHub Wiki

Charlie developer documentation > Brain

The "brain" is a persistent key-value store that scripts can use to store information across restarts/redeploys. The entire brain is kept in memory at runtime, but writes to the database on every update. Values need to be serializable to JSON in order to be stored, so that means no Map, Set, or Symbol objects. Plain objects and arrays work well, though.

The "brain" is attached to the app object passed into scripts' default exports, so you can generally access it with app.brain. Its methods can also be imported directly for scripts that don't take an app object.

Implementation details

For Charlie deployed in cloud.gov, the brain is implemented as a table in a PostgreSQL service. The table is called brain and has two columns: key and value, both strings. When Charlie starts, if the brain table does not exist, it is created. Then, also at startup, the contents of the brain table are loaded into memory and made available through the "brain" object as a Javascript Map object. The keys of the map come directly from the key table, and the values are the result of calling JSON.parse on the value column of the table.

function initialize(Object config) : Promise

Initialize the brain. For Charlie scripts, this should never be necessary. But the main.js script uses this function to connect to the database. This function accepts a configuration option that contains a DATABASE_URL to be used to initialize the database, load the data into memory, and persist changes.

Argument Description
config The configuration object for the database. Requires the DATABASE_URL property.

Defaults to process.env, including environment configuration from cloud.gov.

Returns

  • A promise that resolves when the database resolves. No errors are handled by the brain itself.

function get(String key) : [JSON serializable]

Get a value from the brain. Because the brain's contents are stored in memory at runtime, this function is synchronous.

Argument Description
key The key of the value to retrieve

Returns

  • The JSON-deserialized value in the brain for the given key, or undefined.

function set(String key, [JSON serializable] value) : Promise

Set a value in the brain. This value will be JSON-serialized and saved to the persistent database.

Argument Description
key The key for the value to set
value The value to be set. This must be JSON-serializable

Returns

  • A promise that resolves when the value has been persisted to the database. No errors are handled by the brain itself.
⚠️ **GitHub.com Fallback** ⚠️