<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: FesserBlondie</title>
    <description>The latest articles on DEV Community by FesserBlondie (@fesserblondie).</description>
    <link>https://dev.to/fesserblondie</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F665223%2F4e51913e-dc4e-4c36-8c82-f79c167534a2.jpeg</url>
      <title>DEV Community: FesserBlondie</title>
      <link>https://dev.to/fesserblondie</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fesserblondie"/>
    <language>en</language>
    <item>
      <title>How To Build REST APIs With Golang And Fauna
</title>
      <dc:creator>FesserBlondie</dc:creator>
      <pubDate>Wed, 08 Dec 2021 06:08:37 +0000</pubDate>
      <link>https://dev.to/fesserblondie/how-to-build-rest-apis-with-golang-and-fauna-4j0b</link>
      <guid>https://dev.to/fesserblondie/how-to-build-rest-apis-with-golang-and-fauna-4j0b</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;Golang has become very popular nowadays. It’s fast, has an easy-to-learn syntax, and is gaining ground among backend developers. Today, we will learn how to use Golang to perform Create, Read, Update, and Delete (CRUD) operations against an equally popular database, Fauna.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://fauna.com/?utm_source=DevTo&amp;amp;utm_medium=referral&amp;amp;utm_campaign=WritewithFauna_GolangREST_Fesse"&gt;Fauna&lt;/a&gt; is a flexible, developer-friendly, transactional cloud database delivered as a secure Data API that provides two interfaces: GraphQL and the Fauna Query Language (FQL). Fauna is a unique indexed document system that supports relations, documents, and graphs for unmatched modeling flexibility. It includes functionality to store collections, indexes, and other databases (multi-tenancy). To learn more about Fauna, visit the &lt;a href="https://docs.fauna.com/fauna/current/start/index.html?utm_source=DevTo&amp;amp;utm_medium=referral&amp;amp;utm_campaign=WritewithFauna_GolangREST_Fesse"&gt;official documentation&lt;/a&gt;. &lt;a href="https://fauna.com/?utm_source=DevTo&amp;amp;utm_medium=referral&amp;amp;utm_campaign=WritewithFauna_GolangREST_Fesse"&gt;Fauna&lt;/a&gt; uses a pre-existing infrastructure to build web applications without usually setting up a custom API server. This efficiently helps to save time for developers, and the stress of choosing regions and configuring storage that exists among other databases. All maintenance we need is actively taken care of by engineers and automated DevOps at Fauna.&lt;/p&gt;

&lt;p&gt;Here’s the &lt;a href="https://github.com/IkehAkinyemi/faunaDB-golang"&gt;full code&lt;/a&gt; of the project we would build in this tutorial. And throughout the tutorial, we’ll modularize the different API routes defined within the project. This will help us test out the different API request without it being dependent.&lt;/p&gt;

&lt;h1&gt;
  
  
  Initial setup
&lt;/h1&gt;

&lt;p&gt;Let’s set up our development environment. First, we will need to install Golang because that is the language we will be using here. Click this &lt;a href="https://golang.org/doc/install"&gt;link to learn how to install it for your operating system&lt;/a&gt;.&lt;br&gt;
Next, we need to create an account on the Fauna either through the dashboard UI or through &lt;code&gt;fauna-shell&lt;/code&gt; CLI. For this tutorial, we’ll make use of the dashboard to setup and interact with our database. Follow this &lt;a href="https://fauna.com/https://dashboard.fauna.com/accounts/register?utm_source=DevTo&amp;amp;utm_medium=referral&amp;amp;utm_campaign=WritewithFauna_GolangREST_Fesse"&gt;link&lt;/a&gt; to create an account. Then create your first database and navigate to the &lt;strong&gt;Security&lt;/strong&gt; webpage by clicking on the &lt;strong&gt;Security&lt;/strong&gt; link on the sidebar to generate an API key for our application. Fill the input field and click the &lt;code&gt;SAVE&lt;/code&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6dD89yVx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1638942715559_Screenshot%2B2021-12-08%2Bat%2B06.51.41.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6dD89yVx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1638942715559_Screenshot%2B2021-12-08%2Bat%2B06.51.41.png" alt="SECRET API key" width="880" height="517"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;N.B., make sure you take note of your connection string, especially the Secret API key, as it is only shown once. This secret won't be displayed again, so please copy and save it somewhere safe. This tutorial also assumes you have some knowledge of programming with &lt;a href="https://golang.org/"&gt;Golang&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Next, let’s jump into building the different parts of our application.&lt;/p&gt;

&lt;h1&gt;
  
  
  Project overview
&lt;/h1&gt;

&lt;p&gt;For the project, we’ll build the REST API that allows us to make API request to create, read, update, and delete items from the Fauna database. We’ll build a Blog-like platform, where we can create, retrieve, update and delete a post from the application. We’ll use &lt;a href="https://www.postman.com/"&gt;Postman&lt;/a&gt; to make API requests to the server that we’ll setup up with Golang.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup Local Environment
&lt;/h2&gt;

&lt;p&gt;Let’s start with creating our root folder within the Golang &lt;code&gt;GOPATH&lt;/code&gt; at the root directory of your local machine, &lt;code&gt;$HOME/go/src/&lt;/code&gt;. The default &lt;code&gt;$GOPATH&lt;/code&gt; on Unix is &lt;code&gt;$HOME/go&lt;/code&gt;. We'll store our programs there.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir faunadb-go
cd faunadb-go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, let’s start with initializing and adding the go-modules required for our application by using the &lt;code&gt;go get&lt;/code&gt; command. Let install the Fauna’s open source Go driver, which provides the resources required to interact with Fauna, and also build the REST API using the &lt;code&gt;**gorilla/mux**&lt;/code&gt; router instead of the traditional &lt;code&gt;**net/http**&lt;/code&gt; router.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/fauna/faunadb-go/v5/faunadb
go get github.com/gorilla/mux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Please note that the driver undergoes breaking changes from time to time. It is recommended to use one of the following methods instead:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;JSON&lt;/strong&gt;&lt;br&gt;
For the purpose of this tutorial I’ll be using JavaScript Object Notation as a means of sending and receiving all information and thankfully Go comes with some excellent support for encoding and decoding these formats using the standard library package, encoding/json.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Marshalling&lt;/strong&gt;&lt;br&gt;
There’s a good support within Golang to easily convert data structures in GO into JSON by using something called marshalling which produces a byte slice containing a very long string with no extraneous white space.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup a server to handle HTTP requests
&lt;/h2&gt;

&lt;p&gt;To setup a server using Golang, we’ll first create a new file called &lt;code&gt;**main.go**&lt;/code&gt;. Within this &lt;code&gt;**main.go**&lt;/code&gt; file we’ll want to define 3 different functions. A &lt;code&gt;**homePage**&lt;/code&gt; function that will handle all requests to our root URL, a &lt;code&gt;**handleRequests**&lt;/code&gt; function that will match the URL path hit with a defined function and a &lt;code&gt;**main**&lt;/code&gt; function which will act as the default entrance into our REST API.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
  "fmt"
  "net/http"

  f "github.com/fauna/faunadb-go/faunadb"
  "github.com/gorilla/mux"
)

var client = f.NewFaunaClient(os.Getenv("FAUNADB_SECRET_KEY"))
// Create a class to store Blog
_, _ = client.Query(f.CreateCollection(f.Obj{"name": "Blog"}))

func homePage(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Welcome to REST API with FaunaDB")
  fmt.Println("We've reached the Home page endpoint!")
}

func handleRequests() {
  r := mux.NewRouter().StrictSlash(true)
  r.HandleFunc("/", homePage)

  log.Fatal(http.ListenAndServe(":10000", r))
}

func main() {
  handleRequests()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, let run the Go program using the &lt;code&gt;go run&lt;/code&gt; command in the terminal as below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let’s open Postman to test that our server is actually listening for incoming requests. Now, make a &lt;strong&gt;GET&lt;/strong&gt; request to the &lt;strong&gt;localhost:10000/&lt;/strong&gt; URL to hit call the &lt;code&gt;homePage&lt;/code&gt; function:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--43Cey0pr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637241328983_faunadb-go-1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--43Cey0pr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637241328983_faunadb-go-1.png" alt="API request-response on localhost:10000" width="880" height="747"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Create a Fauna collection instance
&lt;/h2&gt;

&lt;p&gt;Here, we’ll create a route to create a collection on Fauna. Within this collection, we’ll create a Document. To create new documents in a Fauna collection, we’ll first make a connection to the database using the client provided by Fauna, then use the &lt;code&gt;Create&lt;/code&gt; method that allows us to insert a single document into our database. We named our &lt;strong&gt;Document&lt;/strong&gt; &lt;code&gt;Blog&lt;/code&gt; in this tutorial&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func createNewPost(w http.ResponseWriter, r *http.Request) {
  req, _ := ioutil.ReadAll(r.Body)
  var post Post
  json.Unmarshal(req, &amp;amp;post)
  // Save post at FaunaDB
  newProfile, _ := client.Query(
    f.Create(
      f.Collection("Blog"),
      f.Obj{"data": post},
    ),
  )
  // Get generated post ID
  _ = newProfile.At(ref).Get(&amp;amp;postId)
  Blog = append(Blog, post)
  json.NewEncoder(w).Encode(post)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, let’s update the &lt;code&gt;handleRequests&lt;/code&gt; function, defining a new route to handle the &lt;code&gt;createNewPost&lt;/code&gt; function:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
  r := mux.NewRouter().StrictSlash(true)
  r.HandleFunc("/", homePage)
  r.HandleFunc("/blog/post", createNewPost)

  log.Fatal(http.ListenAndServe(":10000", r))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let’s open Postman to test that our server is actually listening for incoming requests. Now, make a &lt;strong&gt;POST&lt;/strong&gt; request to the &lt;strong&gt;localhost:10000/blog/post&lt;/strong&gt; URL to hit call the &lt;code&gt;createNewPost&lt;/code&gt; function:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BeM3hHRd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637276430301_faunadb-go-2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BeM3hHRd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637276430301_faunadb-go-2.png" alt="Create a new post and stored it on DB" width="880" height="747"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, let’s navigate to our database to confirm that our &lt;strong&gt;Document&lt;/strong&gt; was successfully created on the database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BZHvBKRS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637276791578_faunadb-go-3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BZHvBKRS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637276791578_faunadb-go-3.png" alt="Confirmed the Document (Post) was created on the DB" width="880" height="641"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Retrieve a Document from Fauna collection instance
&lt;/h2&gt;

&lt;p&gt;We’ll define a &lt;code&gt;gorilla/mux&lt;/code&gt; route which will allow us to easily do things such as retrieve path based on the current value of query parameter, &lt;code&gt;var postId f.RefV&lt;/code&gt; in this tutorial.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func getSinglePost(w http.ResponseWriter, r *http.Request) {
  req, _ := ioutil.ReadAll(r.Body)
  var post Post
  json.Unmarshal(req, &amp;amp;post)
  // Retrieve post by its ID
  value, _ := client.Query(f.Get(postId))
  _ = value.At(data).Get(&amp;amp;post)
  json.NewEncoder(w).Encode(value)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above code, we’ll use the &lt;code&gt;json&lt;/code&gt; to parse the &lt;code&gt;value&lt;/code&gt; from the call of &lt;code&gt;f.Get()&lt;/code&gt; method as we pass in the &lt;code&gt;postId&lt;/code&gt; into it. Next, let’s update the &lt;code&gt;handleRequests&lt;/code&gt; function, defining a new route to handle the &lt;code&gt;getSinglePost&lt;/code&gt; function:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
  r := mux.NewRouter().StrictSlash(true)
  r.HandleFunc("/", homePage)
  r.HandleFunc("/blog/post", createNewPost)
  r.HandleFunc("/blog", getSinglePost).Methods("GET")

  log.Fatal(http.ListenAndServe(":10000", r))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let’s open Postman to test that our server is actually listening for incoming requests. Now, make a &lt;strong&gt;GET&lt;/strong&gt; request to the &lt;strong&gt;localhost:10000/blog/post&lt;/strong&gt; URL to hit call the &lt;code&gt;getSinglePost&lt;/code&gt; function:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6wdkrc17--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637278534031_faunadb-go-4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6wdkrc17--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637278534031_faunadb-go-4.png" alt="Retrieves Document (Post) from the Db using a ref." width="880" height="744"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Update a Document from Faunacollection instance
&lt;/h2&gt;

&lt;p&gt;Fauna provides the &lt;code&gt;f.Update&lt;/code&gt; operation to change documents in a collection. &lt;code&gt;f.Update&lt;/code&gt; function changes the specified fields or overwrites existing data with new fields you provided in a document.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func updatePost(w http.ResponseWriter, r *http.Request) {
  // Update existing post entry
  _, _ = client.Query(
    f.Update(
      postId,
      f.Obj{"data": f.Obj{
        "Title": "Adieu to Fauna blog posts", "Content": "In the next article, we'll build a simple micro-service", "Summary": "This article featured Golang architectures",
      }},
    ),
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above code, we hardcoded our update using the &lt;code&gt;f.Obj&lt;/code&gt;, &lt;code&gt;Obj&lt;/code&gt; is a expression shortcut to represent any valid JSON object. Next, let’s update the &lt;code&gt;handleRequests&lt;/code&gt; function, defining a new route to handle the &lt;code&gt;updatePost&lt;/code&gt; function:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
  r := mux.NewRouter().StrictSlash(true)
  r.HandleFunc("/", homePage)
  r.HandleFunc("/blog/post", createNewPost)
  r.HandleFunc("/blog", getSinglePost).Methods("GET")
  r.HandleFunc("/blog", updatePost).Methods("PUT")

  log.Fatal(http.ListenAndServe(":10000", r))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let’s open Postman to test that our server is actually listening for incoming requests. Now, make a &lt;strong&gt;GET&lt;/strong&gt; request to the &lt;strong&gt;localhost:10000/blog/post&lt;/strong&gt; URL to hit call the &lt;code&gt;updatePost&lt;/code&gt; function. Once we’ve made the API request through Postman, let’s navigate to our database to confirm that our &lt;strong&gt;Document&lt;/strong&gt; was successfully updated on the database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lCSgOinc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637281246597_faunadb-go-5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lCSgOinc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637281246597_faunadb-go-5.png" alt="Updated Document (Post) in the DB" width="880" height="539"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Delete a Document from Fauna collection instance
&lt;/h2&gt;

&lt;p&gt;We’ll always at a point need to delete the data being exposed by your REST API. In order to do this, you need to expose a &lt;code&gt;**DELETE**&lt;/code&gt; endpoint within our API route that will make request to the database to delete whatever is associated with that identifier.&lt;br&gt;
In this section of this tutorial, you are going to be creating another endpoint which receives &lt;code&gt;**HTTP DELETE**&lt;/code&gt; requests and deletes a post if they match the given &lt;code&gt;ref&lt;/code&gt; parameter.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func deletePost(w http.ResponseWriter, r *http.Request) {
  // Delete post using its ID
  _, _ = client.Query(f.Delete(postId))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;With the &lt;code&gt;f.Delete()&lt;/code&gt; will delete a particular &lt;strong&gt;Document&lt;/strong&gt; from the &lt;code&gt;**Blog**&lt;/code&gt; collection within our database. Next, let’s update the &lt;code&gt;handleRequests&lt;/code&gt; function, defining a new route to handle the &lt;code&gt;deletePost&lt;/code&gt; function:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
  r := mux.NewRouter().StrictSlash(true)
  r.HandleFunc("/", homePage)
  r.HandleFunc("/blog", getSinglePost).Methods("GET")
  r.HandleFunc("/blog/post", createNewPost)
  r.HandleFunc("/blog", deletePost).Methods("DELETE")
  r.HandleFunc("/blog", updatePost).Methods("PUT")

  log.Fatal(http.ListenAndServe(":10000", r))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, let’s make a &lt;strong&gt;DELETE&lt;/strong&gt; request to the &lt;strong&gt;localhost:10000/blog/post&lt;/strong&gt; URL to hit call the &lt;code&gt;updatePost&lt;/code&gt; function on Postman. Once we’ve made the API request through Postman, let’s navigate to our database to confirm that our &lt;strong&gt;Document&lt;/strong&gt; was successfully deleted from the database:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EhKB4nam--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637287824422_faunadb-go-6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EhKB4nam--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://paper-attachments.dropbox.com/s_E60027E445A7458A172C34FC7BE2876075869582DC96788EE86253E537C82054_1637287824422_faunadb-go-6.png" alt="alt text" width="880" height="539"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now our &lt;strong&gt;COLLECTION&lt;/strong&gt;  on the database is empty as we have deleted all the posts from the database.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;I hope this was helpful to guide you through what could be considered often to be a challenging task. The lack of straightforward resources on using Fauna with Go requires developers to spend a lot of time exploring documentation. With this article as a reference guide, you can confidently integrate Fauna into a Go application.&lt;br&gt;
You can head over to the official &lt;a href="https://fauna.com/?utm_source=DevTo&amp;amp;utm_medium=referral&amp;amp;utm_campaign=WritewithFauna_GolangREST_Fesse"&gt;Fauna&lt;/a&gt; and &lt;a href="https://pkg.go.dev/github.com/fauna/faunadb-go/faunadb#Select"&gt;Go driver documentation&lt;/a&gt; to explore more functionalities that Fauna provides.&lt;/p&gt;

</description>
      <category>fauna</category>
      <category>go</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Building Optimised Image Gallery With Fauna</title>
      <dc:creator>FesserBlondie</dc:creator>
      <pubDate>Sun, 11 Jul 2021 15:47:41 +0000</pubDate>
      <link>https://dev.to/fesserblondie/building-optimised-image-gallery-with-fauna-53ok</link>
      <guid>https://dev.to/fesserblondie/building-optimised-image-gallery-with-fauna-53ok</guid>
      <description>&lt;p&gt;A quick outline of what we’ll cover within this tutorial:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction to what image optimization is?&lt;/li&gt;
&lt;li&gt;Explain different techniques and methods to optimize image gallery applications.&lt;/li&gt;
&lt;li&gt;Build a React component using the HTML5 tags to increase accessibility on the images, and also implement Lazy Loading Technique &lt;/li&gt;
&lt;li&gt;Introduction to Fauna

&lt;ul&gt;
&lt;li&gt;How to setup our database on Fauna and integrate it into our frontend application using the Fauna JavaScript Driver&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Perform CRUD requests to our database to make our image gallery dynamic.&lt;/li&gt;

&lt;li&gt;Use cases for Fauna services.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Typical issue developers face when building a web application, like an image gallery application, is how to optimize large file sizes to gain faster load time on a web application while maintaining the image quality and reducing the application's overall performance. Also, the possible issue of &lt;strong&gt;accessibility&lt;/strong&gt; and &lt;strong&gt;usability&lt;/strong&gt; on the images in the web application.&lt;/p&gt;

&lt;p&gt;We’ll cover different approaches that would provide feasible solutions to these common issues within this tutorial. We will explore the other solutions ranging from image compression to using the appropriate HTML5 elements, which would solve the  accessibility and usability issue, then to using third-party services. Then we’ll go-ahead to implement a simple Image Gallery component using HTML5 elements, also applying the Lazy Loading Technique discussed later in this tutorial.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;This tutorial requires that you have experience with front-end development, experience in using React, and React hooks to build frontend applications. &lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction To Image Optimisation
&lt;/h2&gt;

&lt;p&gt;Image optimization is simply the act of decreasing file size without losing its quality. Reducing the file size of images using any available technique, either through a third-party plugin, script, or otherwise, speeds up the web application's load time. The main target of image optimizing is the large image files that slow down your web application, creating a less than optimal user experience. To find the delicate balance between the smallest file size and a well desired—acceptable image quality, following the best image optimization techniques will help keep our file size small and optimal enough.Image optimization is also about image SEO, making the images—either the product images and decorative images, to rank more on Google and other image search engines improving the website’s components visibility, as Google uses page load time as a &lt;a href="https://webmasters.googleblog.com/2018/01/using-page-speed-in-mobile-search.html" rel="noopener noreferrer"&gt;ranking factor&lt;/a&gt; in their algorithm.&lt;/p&gt;

&lt;p&gt;Next, let’s discuss the different techniques in Image optimization.&lt;/p&gt;

&lt;h3&gt;
  
  
  Image Compression:
&lt;/h3&gt;

&lt;p&gt;The first technique that we’ll discuss is image compression. Image compression involves minimizing the file size in bytes of a graphics file without degrading the quality of the image to an unacceptable level. The reduction in file size allows more images to be downloaded and stored in a given amount of available disk or memory space.&lt;/p&gt;

&lt;p&gt;While compressing images to reduce the file size is a feasible solution, this can drastically reduce the image quality, which isn’t a good experience for our web application. Distorted, blurry images, and greyish image effects are possible outcomes of excessive image compression.These images can’t be used as product images or even decorative images within our web application. &lt;/p&gt;

&lt;p&gt;Three common file types are used to post images to the web: JPEG, GIF, and PNG, and compression happen differently for each of them. Choosing and compressing the right file types helps to maintain the quality of the compressed image. The JPEG format allows decent quality at a low file size after compression than other image formats. It will be advisable to compress the JPEG image format more than other formats for it will still maintain good quality unlike others. &lt;a href="https://tinypng.com/" rel="noopener noreferrer"&gt;TinyPNG&lt;/a&gt; is an excellent example of an image compressing tool available on the web.&lt;/p&gt;

&lt;h3&gt;
  
  
  Choose the right file type
&lt;/h3&gt;

&lt;p&gt;When working with images within your web application, choosing the right image format for the right use case helps the web application's performance.  There are mainly JPEG, SVG, PNG—PNG-8 and PNG-24, and GIF file formats for image files. These different image formats have different use cases when building your web application, and appropriate usage helps SEO and the overall performance of the web application. JPEG file formats are more suitable for use when adding non-product images to the web application. Images with the JPEG file format provide the best quality for the smallest file size and isbeing the oldest file format, and they are well supported by older browsers and on the new ones. The SVG file formats are vector images that are very lightweight in file size and are best used for icons, shapes and also good for image animation. The SVG file formats are vector images that are very lightweight in file size and used for icons, shapes, and suitable image animation. The SVG files have good support on the browser. The PNGs are new formats of image files ideal for product images when building e-commerce web applications.  PNGs also excel as simple decorative images making them an excellent alternative to JPEGs. PNG-24 file formats are up to 3x larger than the PNG-8 file formats. It's safer to use the PNG-8 over the PNG-24 file format. GIF file formats are well designed for animated images, making them the best use for animation on web applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Manually Resizing Image File Size
&lt;/h3&gt;

&lt;p&gt;Another safer way to optimize images for the web is by resizing them before using them on our web application.Working with raw images with unnecessary parts that are not needed can be cropped out to reduce file sizes Images taken by the camera would often contain unnecessary portions, and these can be removed through cropping the image with Adobe Photoshop or a similar tool. Using Adobe Photoshop,you can reduce image file size by using the "Save for Web" command in Adobe Photoshop. When using this command, you want to adjust the image to the smallest file size possible while keeping an eye out for image quality. &lt;/p&gt;

&lt;h3&gt;
  
  
  Using HTML5 Tags
&lt;/h3&gt;

&lt;p&gt;This is a more robust method of image optimization on the web. These are built-in browser capacities for handling images for better performance on the web:&lt;/p&gt;

&lt;p&gt;The HTML5 &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; element is designed to give developers the full ability to optimize the images according to the screen resolution of the viewing device. We instruct the browser using these two attributes, &lt;code&gt;srcset&lt;/code&gt; and &lt;code&gt;sizes&lt;/code&gt;, to decide which image size is needed.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;&amp;lt;picture&amp;gt;&lt;/code&gt; tag is another way to provide alternative sources for image files so that the browser can choose depending on device capabilities. It’s used to give flexibility to the web developers to specify different image resources. The &lt;code&gt;&amp;lt;picture&amp;gt;&lt;/code&gt; tag contains &lt;code&gt;&amp;lt;source&amp;gt;&lt;/code&gt; tag and &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; tag as child elements. The attribute value is set to load a more appropriate image. The &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; element is used for the last child element of the &lt;code&gt;&amp;lt;picture&amp;gt;&lt;/code&gt; declaration block. Read more on using &lt;code&gt;&amp;lt;picture&amp;gt;&lt;/code&gt; element on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture" rel="noopener noreferrer"&gt;MDN&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Progressive image loading
&lt;/h3&gt;

&lt;p&gt;It is a known technique to effectively and smartly load the images of our web application by demand, using small placeholders. In contrast,the original image is loaded behind the background. A progressive image starts off with a low-resolution and progressively enhances itself over time. This method helps the user experience your web application by preventing users with a slow network connection from leaving your site because it displays a white screen for a long time. &lt;/p&gt;

&lt;h3&gt;
  
  
  Lazy loading the images
&lt;/h3&gt;

&lt;p&gt;Lazy loading helps eliminate the browser from downloading all the images when loading the page. Only download the essential images, and make a lazy loading of the other resources. Chrome and Firefox both support lazy-loading with the &lt;code&gt;loading&lt;/code&gt; attribute. We'll add this attribute to &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; elements, and also to &lt;code&gt;&amp;lt;iframe&amp;gt;&lt;/code&gt; elements. A value of lazy will tell the browser to load the image immediately if it is in the viewport and also fetch other images when the user scrolls near them. This image optimization method depends on the two DOM events, namely the &lt;code&gt;scroll&lt;/code&gt; and &lt;code&gt;resize&lt;/code&gt; events.&lt;/p&gt;

&lt;h2&gt;
  
  
  Build React Components Using The HTML5 Tags
&lt;/h2&gt;

&lt;p&gt;We will implement a simple component structure to add images to your web application. We’ll build this component, ensuring that &lt;strong&gt;Accessibility&lt;/strong&gt; and &lt;strong&gt;Usability&lt;/strong&gt; is well implemented for optimal performance for &lt;strong&gt;SEO&lt;/strong&gt; on the web application.&lt;/p&gt;

&lt;p&gt;We’ll use the &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; element for its great support on all the browsers, both old and new browsers. Let’s start with the simplest structure of the &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import react from "react";

const Image = ({imgLink}) =&amp;gt; {
  return (&amp;lt;img src={imgLink} /&amp;gt;)
}

export default Image;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above gives us the bare minimum need to add an image element to our web application. But there are some shortcomings with the above code that I will handle next. These shortcomings are centred around &lt;strong&gt;accessibility&lt;/strong&gt; and &lt;strong&gt;usability&lt;/strong&gt; for images that are naturally inaccessible to people who are unable to see them. Our first line of action would be to make it available to users using screen readers to navigate through our web application. Adding an &lt;code&gt;alt&lt;/code&gt; attribute will cause the image accessible for users who use a screen reader to navigate through our web application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import react from "react";

const Image = ({imgLink, altText}) =&amp;gt; {
  return (&amp;lt;img src={imgLink} alt={altText} /&amp;gt;)
}

export default Image;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code provides a means for us to add descriptive text describing our image through the &lt;code&gt;alt&lt;/code&gt; attribute. Providing an alternative means for screen reader users with a description of the image element. The &lt;code&gt;title&lt;/code&gt; offers similar capacity but mainly for users using the mouse to navigate the web application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import react from "react";

const Image = ({imgLink, altText}) =&amp;gt; {
  return (&amp;lt;img src={imgLink} alt={altText} title={altText}/&amp;gt;)
}

export default Image;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Adding &lt;code&gt;title&lt;/code&gt; attributes to images provides further supporting information if needed to mouse users.&lt;/p&gt;

&lt;p&gt;A more efficient way of providing caption or description to an image is through the use of &lt;code&gt;&amp;lt;figure&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;figcaption&amp;gt;&lt;/code&gt; HTML5 elements. They are designed to provide a semantic container for figures and to link the figure to the caption. The above code structure will be rewritten like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import react from "react";

const Image = ({imgLink, altText, additionalInfo}) =&amp;gt; {
  return (
    &amp;lt;figure&amp;gt;
      &amp;lt;img src={imgLink} alt={altText} /&amp;gt;
      &amp;lt;figcaption&amp;gt;{additionalInfo}&amp;lt;/figcaption&amp;gt;
    &amp;lt;/figure&amp;gt;)
}

export default Image;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use the &lt;code&gt;&amp;lt;figcaption&amp;gt;&lt;/code&gt; element to provide additional caption/description to the browsers and assistive technology that this is the information to describe the other content within the &lt;code&gt;&amp;lt;figure&amp;gt;&lt;/code&gt; element. Also, note that a &lt;code&gt;&amp;lt;figure&amp;gt;&lt;/code&gt; could be used for several images.&lt;/p&gt;

&lt;p&gt;The above code structure would help us implement a unit image component for any web application with images. Next, we look at using Intersection Observer API to implement &lt;strong&gt;Lazy Loading&lt;/strong&gt; on images.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implement Lazy Loading With Intersection Observer API
&lt;/h2&gt;

&lt;p&gt;With Intersection Observer API, we can easily observe and detect when an element enters the viewport and takes action.This is very efficient for we are conditional rendering our images or contents only when the user scrolls the image into the viewport. So only the needed contents, the images, are loaded when the user wants to see them. &lt;/p&gt;

&lt;p&gt;We’ll demonstrate this with a basic structure of what an image gallery would look like—Let’s give an overview of the markup structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;img src="https://images.unsplash.com/photo-1622495546876-3fccb94d3e2c?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=750&amp;amp;q=80" /&amp;gt;
&amp;lt;img src="https://images.unsplash.com/photo-1622495550744-dd25b569e6c0?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=750&amp;amp;q=80" /&amp;gt;
&amp;lt;img src="https://images.unsplash.com/photo-1623973676476-a9152edbe397?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=590&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1619625713173-fce47ce8d960?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=750&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1622495893617-38b112b30790?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=799&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1623894201770-efa76ccc00f8?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=750&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1608790672303-e6931dbff2d8?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=1500&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1623851467157-5eb7199d0f18?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=668&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1623929147453-b0abf89a9363?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=667&amp;amp;q=80" /&amp;gt;
&amp;lt;img class="lazy" data-src="https://images.unsplash.com/photo-1623885065412-300800bcadb3?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=751&amp;amp;q=80" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above are sample images that would be loaded into the browser, but we’ll control how we’ll load them into the browser using a script written with the help of the browser’s &lt;strong&gt;Intersection Observer API&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.addEventListener("DOMContentLoaded", function() {
  var lazyloadImages;    

  if ("IntersectionObserver" in window) {
    lazyloadImages = document.querySelectorAll(".lazy");
    var imageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          var image = entry.target;
          image.src = image.dataset.src;
          image.classList.remove("lazy");
          imageObserver.unobserve(image);
        }
      });
    });

    lazyloadImages.forEach(function(image) {
      imageObserver.observe(image);
    });
  } else {  
    var lazyloadThrottleTimeout;
    lazyloadImages = document.querySelectorAll(".lazy");

    function lazyload () {
      if(lazyloadThrottleTimeout) {
        clearTimeout(lazyloadThrottleTimeout);
      }    

      lazyloadThrottleTimeout = setTimeout(function() {
        var scrollTop = window.pageYOffset;
        lazyloadImages.forEach(function(img) {
            if(img.offsetTop &amp;lt; (window.innerHeight + scrollTop)) {
              img.src = img.dataset.src;
              img.classList.remove('lazy');
            }
        });
        if(lazyloadImages.length == 0) { 
          document.removeEventListener("scroll", lazyload);
          window.removeEventListener("resize", lazyload);
          window.removeEventListener("orientationChange", lazyload);
        }
      }, 20);
    }

    document.addEventListener("scroll", lazyload);
    window.addEventListener("resize", lazyload);
    window.addEventListener("orientationChange", lazyload);
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the above code, we closely monitor when the user scrolls or resizes the browser. These events’ listeners trigger a function, this function looks for all the images on the page that are currently deferred and, from this image collection, it checks which images are currently in the view-port by calculating their top offset, that’s the current top position of the document and the window’s height. Once an image has entered the viewport, we pick the URL from the data-src attribute if there exists such attribute on the image and move it to the src attribute and the image will load as a result.  Find the code and the live demo &lt;a href="https://codepen.io/FesseBlondie/pen/ZEeZLLv" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction To Fauna And How Set-up database on Fauna
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://fauna.com/" rel="noopener noreferrer"&gt;Fauna&lt;/a&gt; is a flexible, developer-friendly, transactional cloud database delivered as a secure Data API that provides two interfaces: GraphQL and the Fauna Query Language (FQL). Fauna is a unique indexed document system that supports relations, documents, and graphs for unmatched modeling flexibility. It includes functionality to store collections, indexes, and other databases (multi-tenancy). To learn more about Fauna, visit the &lt;a href="https://docs.fauna.com/fauna/current/start/index.html" rel="noopener noreferrer"&gt;official documentation&lt;/a&gt;. &lt;a href="https://fauna.com/" rel="noopener noreferrer"&gt;Fauna&lt;/a&gt; uses a pre-existing infrastructure to build web applications without usually setting up a custom API server. This efficiently helps to save time for developers, and the stress of choosing regions and configuring storage that exists among other databases, which is global/multi-region by default, are nonexistent with Fauna. All maintenance we need is actively taken care of by engineers and automated DevOps at Fauna.&lt;/p&gt;

&lt;p&gt;We’ll go through the steps involved and set up a database on Fauna, ready for use on the frontend part of any application. First, step is creating an account with Fauna or signing into an existing account. We can register for a new account &lt;a href="https://dashboard.fauna.com/accounts/register" rel="noopener noreferrer"&gt;here&lt;/a&gt;. Once signed in, the dashboard would look like the below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2msh72ufp4njtlrivtxh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2msh72ufp4njtlrivtxh.png" alt="altText"&gt;&lt;/a&gt;&lt;br&gt;
Within the dashboard screen, click on the &lt;code&gt;NEW DATABASE&lt;/code&gt; button, and the next screen is where we’ll provide any name appropriate for the database that we plan to use within our frontend application. Here we’ll call the sample we’re creating &lt;strong&gt;image_gallery&lt;/strong&gt;, then go ahead to click on the SAVE button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl16ixmr41whv0vzfut9e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl16ixmr41whv0vzfut9e.png" alt="altText"&gt;&lt;/a&gt;&lt;br&gt;
Next screen after clicking on the &lt;code&gt;SAVE&lt;/code&gt; button would be the screen providing us with the button to create a &lt;strong&gt;COLLECTION&lt;/strong&gt;.  A Collection is similar to SQL tables containing similar characteristics, e.g. a user collection with information about users in the database. Click on the &lt;code&gt;NEW COLLECTION&lt;/code&gt; button to navigate to the form for creating a collection:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foeb2ypseqewolefhrqex.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foeb2ypseqewolefhrqex.png" alt="altText"&gt;&lt;/a&gt;&lt;br&gt;
Within the collection name field on the form we’ll name our data collection. In this tutorial, we’ll call it &lt;strong&gt;image_gallery_collection&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Next we create the &lt;strong&gt;INDEXES&lt;/strong&gt; for the collection of the database. A Fauna index allows us to browse through data stored in a database collection based on specific attributes. On the sidebar of the screen, click on the &lt;code&gt;Indexes&lt;/code&gt; link. The next screen contains a &lt;code&gt;NEW INDEX&lt;/code&gt; button, click on it to bring out the form for creating an index: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fibo3kdc8mre1m7t7rngl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fibo3kdc8mre1m7t7rngl.png" alt="altText"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above form, select the current collection we’re creating the index for. Then provide the name for the new index and save it.&lt;/p&gt;

&lt;p&gt;After creating the above index, it’s time to create our &lt;strong&gt;DOCUMENT&lt;/strong&gt;, this will contain the links/data we’ll use to populate our we application. Click on the &lt;code&gt;NEW DOCUMENT&lt;/code&gt; button to get started. With the provided text editor we’ll create document to contain the image links with any extra information:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw07ip9ksxi4x9tbfr9bk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw07ip9ksxi4x9tbfr9bk.png" alt="altText"&gt;&lt;/a&gt;&lt;br&gt;
The above &lt;code&gt;image&lt;/code&gt; object represents the unit data we need to create a simple image gallery. Your choice of data can be so different from what we have here, serving the purpose whatever you want it for within your web application. We can create multiple document to server our database purpose. Let’s create two extra:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr7fp5cd2ttzz138mjm22.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr7fp5cd2ttzz138mjm22.png" alt="altText"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we have a basic set up of a database, let’s look explore how to integrate Fauna into any React frontend application.&lt;/p&gt;
&lt;h2&gt;
  
  
  Integrating Fauna Into Frontend Application With Fauna JavaScript Driver
&lt;/h2&gt;

&lt;p&gt;Install the dependency, &lt;code&gt;faunadb&lt;/code&gt;, through &lt;code&gt;npm&lt;/code&gt; or &lt;code&gt;yarn&lt;/code&gt; into the React app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add faunadb 
or
npm install faunadb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;faunadb&lt;/code&gt; package is Fauna JavaScript driver for interacting with Fauna API to get data from the database. Next, we set up the faunadb within the application and integrate it into our application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import faunadb from 'faunadb';
const client = new faunadb.Client({
  secret: process.env.REACT_APP_DB_KEY,
});
const q = faunadb.query;

const getAllImageLinks = client
  .query(q.Paginate(q.Match(q.Ref("indexes/all_image_links"))))
  .then((res) =&amp;gt; {
    const linkRef = res.data;
    const getAllDataQuery = linkRef.map((ref) =&amp;gt; {
      return q.Get(ref);
    });
    return client.query(getAllDataQuery).then((data) =&amp;gt; data);
  })
  .catch((err) =&amp;gt; err.message);

const createImageLink = (imageLink) =&amp;gt;
  client
    .query(q.Create(q.Collection("image_gallery_collection"), { data: { imageLink } }))
    .then((ref) =&amp;gt; ref)
    .catch((err) =&amp;gt; err.message);

const deleteImageLink = (imageLinkId) =&amp;gt;
  client
    .query(q.Delete(q.Ref(q.Collection("image_gallery_collection"), imageLinkId)))
    .then((ref) =&amp;gt; ref)
    .catch((err) =&amp;gt; err.message);
export { getAllImageLinks, createImageLink, deleteImageLink };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code we created and exported three basic CRUD actions: &lt;code&gt;getAllImageLinks&lt;/code&gt;, &lt;code&gt;createImageLink&lt;/code&gt;, and &lt;code&gt;deleteImageLink&lt;/code&gt;. With these actions, we will create, fetch, and delete the &lt;strong&gt;ImageLink&lt;/strong&gt; data from the database through some react hooks. Within the &lt;code&gt;getAllImageLinks&lt;/code&gt; action, we’ll get all the date in the database under the &lt;code&gt;all_image_links&lt;/code&gt; index. The &lt;code&gt;all_image_links&lt;/code&gt; index groups the &lt;code&gt;image_link_collection&lt;/code&gt; data, within the database, into a single group search. The &lt;code&gt;createImageLink&lt;/code&gt; action gives us the interface to create more &lt;strong&gt;imageLink&lt;/strong&gt; if the need be, within our Collection. The &lt;code&gt;deleteImageLink&lt;/code&gt; takes an ID, looks for the document on the database with that ID and deletes it.&lt;/p&gt;

&lt;p&gt;Rewriting our image gallery prototype to contain these action:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react";
import { getAllImageLinks, createImageLink, deleteImageLink } from "./actions";
import Image from "./Image";

const App = () =&amp;gt; {
    const [imgLinkArr, setImgLinkArr] = useState([]);

    useEffect(() =&amp;gt; {
        getAllImageLinks.then((res) =&amp;gt; {
            setImgLinkArr(res);
        });
    }, [imgLinkArr]);

    const createImgLink = (imageLink) =&amp;gt; {
        const image = {
            imageLink,
            altText: "Put the description for the image here",
            additionalInfo: "Any caption goes here"
        };
        createImageLink(image).then((res) =&amp;gt; {
            console.log("Image has been added to the database");
        });
        setImgLinkArr([...imgLinkArr, image]);
    };

    const deleteImgLink = (id) =&amp;gt; {
        const newLinkArr = imgLinkArr.filter((link) =&amp;gt; link.ref.id !== id);
        setImgLinkArr(newLinkArr);
        deleteImageLink(id).then((res) =&amp;gt; res);
    };

    const extractLinkArr = () =&amp;gt; {
        return (
            &amp;lt;&amp;gt;
                {imgLinkArr &amp;amp;&amp;amp;
                    imgLinkArr.map((imgLink) =&amp;gt; (
                        &amp;lt;li key={imgLink.ref.id} id={imgLink.ref.id}&amp;gt;
                            &amp;lt;Image
                                imgLink={imgLink.data.image.imageLink}
                                altText={imgLink.data.image.altText}
                                additionalInfo={imgLink.data.image.additionalInfo}
                            /&amp;gt;
                            &amp;lt;div&amp;gt;
                                &amp;lt;button type="button" onClick={(e) =&amp;gt; deleteImgLink(imgLink.ref.id)} /&amp;gt;
                            &amp;lt;/div&amp;gt;
                        &amp;lt;/li&amp;gt;
                    ))}
            &amp;lt;/&amp;gt;
        );
    };

    return (
        &amp;lt;div className="container"&amp;gt;
            &amp;lt;h1&amp;gt;A simple demo of integrating Fauna into Frontent Application&amp;lt;/h1&amp;gt;
            &amp;lt;div className="image-container"&amp;gt;
                &amp;lt;ul className="image-list"&amp;gt;{extractLinkArr()}&amp;lt;/ul&amp;gt;
                &amp;lt;button type="button" onClick={createImgLink("./cute-cate.jpeg")} /&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    );
};
export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we imported all the utility actions for interaction with our database. Within the useEffect react hook, we reach out to the database to get all the items within it; that’s our image documents containing the imageLink field and other fields. Next is the createImgLink function that accepts an image link as its argument, then creates an image object containing the fields necessary to our database. We pass this image object to the utility action, createImageLink, which takes this object and updates our database. The following function, deleteImgLink takes an ID value, looks through our current imgLinkArr array, and deletes the array element with that ID. Then it goes ahead to request the database with that ID to delete any document with the same ID by calling the deleteImageLink utility action passing the ID as an argument. Then the extractLinkArr function takes our imgLinkArr array, looping through it to get the imageLink, altText, and additionalInfo values to update the UI of our application. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We’ve covered two things within this tutorial, how to optimize your images within your web applications. Discussing the different techniques in Image optimization and also giving examples where needed. Next, we covered what Fauna is, how to set up a database on Fauna.Then proceeded to integrate Fauna into our frontend application using the Fauna JavaScript Driver. Make CRUD requests to our database to update our frontend UI. &lt;/p&gt;

&lt;p&gt;I will love to see your opinions on the tutorial and any suggestions for the article. Also, love to see what you’ve built with Fauna. Reach out to me via email at, &lt;a href="//privatefesserblondie@gmail.com"&gt;privatefesserblondie@gmail.com&lt;/a&gt;, and also through the comment section.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
