DEV Community

Cover image for A Beginner's Guide To Fauna
samaby213
samaby213

Posted on • Updated on

A Beginner's Guide To Fauna

After having a hard time trying to grasp Fauna and serverless databases, I came up with the idea of demystifying what I have learned and the quickest way to get up and running with the Fauna.

Who is this for?

Those new to serverless databases who would like to try out Fauna to use in a project. You need basic programming knowledge to walk you through the lesson.

Concept

In this tutorial, we will show how to create a basic Twitter social graph and get it on the web using NodeJS.

Fauna is a next generation cloud database that simplifies the complexity of building complex relationships. It uses the same codebase as SQL, but is completely serverless and fast.
This tutorial shows how to create a basic social graph with Fauna, which is powered by Node.js. You will also learn how to query the database using the Fauna Query Language.

Initial setup

Start by creating a Node project, then install the Fauna JS package and Express.

npm init -y

npm install faunadb express
Enter fullscreen mode Exit fullscreen mode

Initialize Fauna

fauna
From the Fauna security tab, create a server key. Initialize the client with your server key, then import the FQL functions required for this demo.

// src/index.js 

const faunadb = require('faunadb');
const client = new faunadb.Client({ secret: 'YOUR-KEY' })

// FQL functions
const {
    Ref,
    Paginate,
    Get,
    Match,
    Select,
    Index,
    Create,
    Collection,
    Join,
    Call,
    Function: Fn,
} = faunadb.query;
Enter fullscreen mode Exit fullscreen mode

Initialize Express

Express will be used to serve the API.

// src/index.js 
const app = require('express')();

app.listen(5000, () => console.log('API on http://localhost:5000'))
Enter fullscreen mode Exit fullscreen mode

An API like Insomnia is recommended when making a request to the API at port http://localhost:5000

Database structure

fauna
The database contains three collections - users, tweets, and relationships. Create three collections: users, tweets, and relationships.

Users and tweets

In the next section, we will create an API that will allow users to read and write tweets to Fauna.

Create a tweet

We want to associate many tweets to this user account, so next we Create a document with your username as the username.So we go to our dashboard and create a document with our name as username.
fauna
A relationship can be established between a user and a document by retrieving its data from the Create function.

// src/index.js 
app.post('/tweet', async (req, res) => {

    const data = {
        user: Select('ref', Get(Match(Index('users_by_name'), 'fireship_dev'))),
        text: 'Hello world!'
    }

    const doc = await client.query(
        Create(
            Collection('tweets'),
            { data }
        )
    )

    res.send(doc)
});
Enter fullscreen mode Exit fullscreen mode

Read a tweet by ID

Reading a document by its ID does not require an index. Doing so can be done by pointing to its ID and creating a new document.

// src/index.js 
app.get('/tweet/:id', async (req, res) => {

    const doc = await client.query(
        Get(
            Ref(
                Collection('tweets'),
                req.params.id
            )
        )
    )

    res.send(doc)

});
Enter fullscreen mode Exit fullscreen mode

Query a user’s tweets

Creating an index for each tweet document that a user has tweeted is required. The index will return all the documents that contain the user's name.

// src/index.js
app.get('/tweet', async (req, res) => {

    const docs = await client.query(
        Paginate(
            Match(
                Index('tweets_by_user'), 
                Select('ref', Get(Match(Index('users_by_name'), 'fireship_dev')))
            )
        )
    )

    res.send(docs)
});
Enter fullscreen mode Exit fullscreen mode

Fauna functions

The code presented above duplicates the following line of FQL several times:

Select('ref', Get(Match(Index('users_by_name'), '<username>')))
Enter fullscreen mode Exit fullscreen mode

Fauna Functions are a way to extract the logic of your system to the cloud. They can be used to reduce duplicated and improve maintainability.

Create a function

Extract the duplicated code from the Fauna function. The function returns the username and the full document reference.
fauna

Call a function

A Call can be used to execute this function in a query. For example, let's refactor the previous example like so:

// src/index.js
const {
    Call,
    Function: Fn,
} = faunadb.query;

app.get('/tweet', async (req, res) => {

    const docs = await client.query(
        Paginate(
            Match(
                Index('tweets_by_user'), 
                Call(Fn("getUser"), '<username>v')
            )
        )
    )

    res.send(docs)
});
Enter fullscreen mode Exit fullscreen mode

User-to-user relationships

The following section shows a graph where users can connect to other users and query their tweets.

Create a relationship

Two user reference are contained in a relationship document β€” the follower and followee.

// src/index.js
app.post('/relationship', async (req, res) => {


    const data = {
        follower: Call(Fn("getUser"), 'bob'),
        followee: Call(Fn("getUser"), '<username>')
    }
    const doc = await client.query(
        Create(
            Collection('relationships'),
            { data }
        )
    )

    res.send(doc)
});
Enter fullscreen mode Exit fullscreen mode

Query a feed of tweets

You probably want to query the tweets of followed users after establishing a relationship with them. To do so, create an index called followees_by_follower with a search term and a value of follower.

src/index.js
app.get('/feed', async (req, res) => {
    const docs = await client.query(
        Paginate(
            Join(
                Match(
                    Index('followees_by_follower'),
                    Call(Fn("getUser"), 'bob')
                ),
                Index('tweets_by_user'),
            )
        )
    )

    res.send(docs)
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we learned how to create a basic Twitter social graph and get it on the web using Node.js.

Written in connection with the Write with Fauna Program.

Discussion (0)