14
Getting started with Fauna and Node.js using Express
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!
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.
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.
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).
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.
We will need to create a collection we're going to be interacting with within our Code.
after that you click the Save
Button
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.
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), 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:
{
ref: Ref(Collection("todos"), "302049452692079110"),
ts: 1624315655320000,
data: { testField: 'testValue' }
}
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})
}
});
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})
}
});
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})
}
});
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})
}
});
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})
}
});
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
Let's try this out by making a GET
request to get a todo by id
:
http://localhost:8000/todos/302052755930874368
Let's try this out by making a POST
request to add/create
a todo:
http://localhost:8000/todos/302052755930874368
Let's try this out by making a PUT
request to update a todo:
http://localhost:8000/todos/302052755930874368
Let's try this out by making a DELETE
request to remove a todo:
http://localhost:8000/todos/302052755930874368
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
14