Accessing a database as a state logic

Accessing a Database

It is very common to use a database to retrieve, store or analyze information. Usually, performing an operation on a database can be seen as one logical action, i.e "Retrieve user with ID 42", or "Update user details", etc. Each such operation may then result in a series of other database actions, based on whether the previous action succeeded or failed.

This works perfectly within a flow, so let's examine how to access a database from a certain state;

  1. Create a connection string to your database using a Secret (ensure every environment points to the correct database instance)

  2. Create a "Serverless Function" state

  3. Install the right driver for your database, i.e‚Äč

  4. Initialize your database client, and perform your queries as part of the serverless function body

To easily reuse you database connection code, simply Duplicate the state (By clicking on the state options [three dots] button at the top of the state, and selecting "Duplicate") you created in the steps above, and change the query according to your needs.

Remember, you can always use outputs from other states, the entryPayload and secrets inside a serverless functions as described in the code example.