Getting started with Fauna and Node.js using Express
Tags: javascript, webdev, fauna, serverless
Published: 2021-07-03 09:03:29


## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awrssqddj1e04kyfv64w.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1p86humssudzd81zecpe.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k20ygg933bb49hv0646s.png)

![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xb8z7x0unio5qpqngm4u.png)

![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/recmhdz00f52d7j9o6qy.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yuk1cs8o1v2s6i0c9jgs.png)

![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3bqobrosdh9i4361z3v.png)


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

After this is installed, we are going to run the sample code provided in Fauna [Javascript driver docs](https://docs.fauna.com/fauna/current/drivers/javascript.html).

```js
    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}`));

```

To test this route, we can use any HTTP client. I will be using Postman (which you can [download here](https://www.postman.com/downloads/)), 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

Let's make a GET request to:


    http://localhost:8000/

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

```bash
    {
      ref: Ref(Collection("todos"), "302049452692079110"),
      ts: 1624315655320000,
      data: { testField: 'testValue' }
    }
```

### Step 5: Retrieving all todos

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

```js
    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})
      }
    });

```

### 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`

```js
    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})
      }
    });

```

### 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.

```js
    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})
      }
    });

```

### 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`

```js
    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})
      }
    });

```

### 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`

```js
   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})
      }
    });
```

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
![Get Todos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fie4dqmlosty7jpzscui.png)


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


    http://localhost:8000/todos/302052755930874368
![Get Todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/el2fm5pfqxi4olxnddgc.png)


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


    http://localhost:8000/todos/302052755930874368
![Add todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8sr7n93igw5rkmzn19i2.png)


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


    http://localhost:8000/todos/302052755930874368
![Update todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yeta4k85uucgrl2z06m.png)


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


    http://localhost:8000/todos/302052755930874368
![Delete todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/resmitkkapggwpkqa806.png)




### 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](https://github.com/iamnotstatic/intro-fauna-nodejs).

If you have any questions, don't hesitate to contact me on Twitter: [@iamnotstatic](https://twitter.com/iamnotstatic)