DEV Community

Cover image for Getting started with Fauna and Node.js using Express
Abdulfatai Suleiman
Abdulfatai Suleiman

Posted on

Getting started with Fauna and Node.js using Express

What is Fauna?

FaunaDB is a global cloud database created to integrate with the JAMStack and modern serverless architecture. FaunaDb is not just a flexible and transactional database; it is a developer-friendly database that exposes you to building a fast, secured, and scalable cloud API with native GraphQL.

Some of the great things about FaunaDB are that you don’t even need to worry about database provisioning, scaling, sharding, replication, or correctness again because these are handled at the core of the database infrastructure.

In this article, we will explore the FaunaDB practically by building a fully functioning API and demonstrating the popular CRUD application using Node.js and FaunaDB.

Let’s dive right into building it!

Step 1: Set Up Our Fauna Database

To get started with our CRUD app, we need to create the database for our CRUD app in the Fauna dashboard.

To create an account, head over to the official website and register https://dashboard.fauna.com/accounts/register.

In the dashboard, click on the "NEW DATABASE" button, provide a name for your database then press the SAVE button.

Image

You will be asked for the database name on this screen, whether you want to pre-populate the database, and there's a tip for you if you are migrating from another database to Fauna.

For now, we will enter the database name and press the "SAVE" button. Then, it will present you with a screen like the one below.

Image

Step 2: Generating the Fauna API Key

We will need to create a Fauna API key to connect the database to our CRUD app. To do this, navigate to the security settings on the Fauna sidebar (left side of the screen).

Image

Image

Image

Once you have done this, it will present you with your API key. You should copy the API key as soon as it is generated then stored somewhere easily retrievable.

Step 3: Creating the Fauna Collection

We will need to create a collection we're going to be interacting with within our Code.

Image

Image

after that you click the Save Button

Step 4: Connecting Fauna into Nodejs

Next, we need to get the Nodejs package for Fauna and Express. It's available on npm and can be installed with a single line in our terminal.

$ npm install --save faunadb express
Enter fullscreen mode Exit fullscreen mode

After this is installed, we are going to run the sample code provided in Fauna Javascript driver docs.

    const express = require('express');
    const faunadb = require('faunadb'),
      q = faunadb.query;

    const client = new faunadb.Client({
      secret: 'YOUR_FAUNADB_SECRET',
    });

    const app = express();
    app.use(express.json())
    const PORT = process.env.PORT || 8000;

    app.get('/', async (req, res) => {
      try {
        const createP = await client.query(
          q.Create(q.Collection('todos'), { data: { testField: 'testValue' } })
        );
        console.log(createP);
      } catch (error) {
        console.log(error);
      }
    });

    app.listen(PORT, () => console.log(`Listening at port ${PORT}`));

Enter fullscreen mode Exit fullscreen mode

To test this route, we can use any HTTP client. I will be using Postman (which you can download here), but you can use whatever you're most comfortable with (e.g., cURL, Insomnia, Postwoman, etc.).

Don't forget to use this command to your start dev server:

node src/index.js
Enter fullscreen mode Exit fullscreen mode

Let's make a GET request to:

http://localhost:8000/
Enter fullscreen mode Exit fullscreen mode

After doing that, if you check your terminal, you should see something like this:

    {
      ref: Ref(Collection("todos"), "302049452692079110"),
      ts: 1624315655320000,
      data: { testField: 'testValue' }
    }
Enter fullscreen mode Exit fullscreen mode

Step 5: Retrieving all todos

Let's create our first express route which will allow us to get all todos from a collection.

    app.get('/todos', async (req, res) => {
      try {
        let todos = await client.query(
          q.Map(
            q.Paginate(q.Documents(q.Collection("todos"))),
            q.Lambda("X", q.Get(q.Var("X")))
          )
        )

        res.status(200).json(todos)
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });

Enter fullscreen mode Exit fullscreen mode

Step 6: Retrieving single todo

This section we will be creating express route which will allow us to retrieve todo from a collection by specifying it id

    app.get('/todos/:id', async (req, res) => {
      try {
        const {data} = await client.query(
          q.Get(q.Ref(q.Collection('todos'), req.params.id))
        );
        res.status(200).json(data)
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });

Enter fullscreen mode Exit fullscreen mode

Step 7: Create todo

In this section, we will be creating an express route that will allow us to create/add todo into a collection.

    app.post('/todos', async (req, res) => {

      try {
        const {title, description } = req.body;
        const { data } = await client.query(
          q.Create(q.Collection('todos'), { data: { title, description } })
        );

        res.status(201).json(data);
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });

Enter fullscreen mode Exit fullscreen mode

Step 8: Update todo

In this section, we will be creating an express route that will allow us to update a todo by specifying its id

    app.put('/todos/:id', async (req, res) => {

      try {
        const {title, description } = req.body;
        const { data } = await client.query(
          q.Update(q.Ref(q.Collection('todos'), req.params.id), 
          { data: { title, description } },
          )
        );

        res.status(201).json(data);
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });

Enter fullscreen mode Exit fullscreen mode

Step 7: Delete todo

In this section, we will be creating an express route that will allow us to delete a todo by specifying its id

   app.delete('/todos/:id', async (req, res) => {

      try {
        const { data } = await client.query(
          q.Delete(q.Ref(q.Collection('todos'),  req.params.id))
        );

        res.status(204).json(data);
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });
Enter fullscreen mode Exit fullscreen mode

Next, we will be testing our Code using Postman, which I talked about earlier:

Let's make a GET request to get all todos:

http://localhost:8000/todos
Enter fullscreen mode Exit fullscreen mode

Get Todos

Let's try this out by making a GET request to get a todo by id:

http://localhost:8000/todos/302052755930874368
Enter fullscreen mode Exit fullscreen mode

Get Todo

Let's try this out by making a POST request to add/create a todo:

http://localhost:8000/todos/302052755930874368
Enter fullscreen mode Exit fullscreen mode

Add todo

Let's try this out by making a PUT request to update a todo:

http://localhost:8000/todos/302052755930874368
Enter fullscreen mode Exit fullscreen mode

Update todo

Let's try this out by making a DELETE request to remove a todo:

http://localhost:8000/todos/302052755930874368
Enter fullscreen mode Exit fullscreen mode

Delete todo

Conclusion

In this article, you learned how to make CRUD operations with Fauna and Nodejs using ExpressJs.
The source code of the demo application is available on GitHub.

If you have any questions, don't hesitate to contact me on Twitter: @iamnotstatic

Top comments (0)