Revamping 1klb comments part three: displaying comments

Published
2021-04-25
Tagged

In the previous two posts on this subject I showed off the big picture overview of how this whole system was going to work, and showed you how I set up my database in Fauna to deal with those comments. Assuming that all went according to plan, let’s explore how we actually go from bits in a database, to, yknow, comments on the website.

Two ways of talking to Fauna

I’ve mentioned previously that there’s two ways of talking to the Fauna database:

  • via Fauna Query Language, Fauna’s proprietary language for interacting with the database. The javascript driver for this language is smooth like butter, but it is a few hundred kb.
  • via GraphQL, a more widely-used web-based query API. GraphQL queries are more difficult to write, but don’t require their own library to submit. This makes them ideal for places where we’re trying to keep things light and breezy.

We’re going to get stuck into the FQL driver for Fauna when we design the admin panel, don’t worry. But for the web-based commenting system, we’re going to fetch the data entirely using GraphQL. This will make individual page loads quicker on the blog pages themselves, which I figure is where it counts.

A proof of concept

Note that for the following section I assume you have some kind of static website blog that you can include javascript on.

Before we can start building anything, we’ll need an API key. In our previous step we created a role called ReadComments. As you may guess, that’s the role that our website will take - all it needs to do is read individual comments so it can display them on the webpage. We’ll need to grab an API key for this role and embed it into our javascript, for us to use when we make our queries. It doesn’t matter if other people know this API key - it just means they can read the comments on the website.

To grab that API key:

  1. Log into your Fauna account and open the database you’re working in.
  2. Click Security > + NEW KEY.
  3. Select the correct role, fill in the text fields as you see fit, and click save.
  4. Copy the provided API key.

Now create a javascript file that will be loaded into your blog page. Right now we’re just going to set up that API key:

1
let FAUNA_API_KEY = "your-api-key-here"
2
let FAUNA_GRAPHQL_ENDPOINT = "https://graphql.fauna.com/graphql"

Now we’ve got an API key, we can try getting in touch with the Fauna website. This is what a GraphQL query looks like1:

1
// Specify the post slug. This is the unique text string that identifies a given blog post
2
let post_slug = window.location.pathname.replace("^/posts/", "")
3
4
5
// Make GraphQL query
6
let query = {
7
  operationName: "PostComments",
8
  query: `query PostComments {commentsByPostSlug(post_slug:"${post_slug}") { data { body submitter created_at} }}`
9
}
10
11
// Populate options, including header, method, and body
12
let fetchOptions = {
13
  headers: { Authorization: `Bearer ${FAUNA_API_KEY}` },
14
  method: "POST",
15
  body: JSON.stringify(query)
16
}
17
18
// Perform the operation
19
fetch(
20
  FAUNA_GRAPHQL_ENDPOINT,
21
  fetchOptions
22
)
23
  .then(r => r.json())
24
  .then(payload => console.log(payload))
25

So what did we do here? In three easy steps, we:

  1. Determined the “post slug” for this blog post. This assumes that all your blog posts sit in the directory /posts/ on your website.
  2. Created the body of a GraphQL query. We called this query “PostComments” (this can be any name you want it to be), and set it up to download the comments for the current post we’re looking at.
  3. Populated the options for the GraphQL query. This includes the authentication (via API key) and HTTP method as well as the body we’ve just created.
  4. Ran the fetch, parsed the result, and spat it out to the console.

Some notes at this stage:

  • We’re not doing any checking here. If this runs on every page, we should probably check that the page is actually a blog post before running queries against the database.
  • We’re not doing anything with the result. We’re just outputting it to the console. So don’t expect anything fancy to happen.
  • In fact, we shouldn’t expect anything fancy to happen at all, as we don’t have any comments in our database.

Let’s test it

To test this, we’ll need to go to Fauna and make a test comment. Once everything is set up, you should be able to submit a comment via the website, but for now we’ll just make one through the back-end.

To do this properly, you’ll first need to work out the slug for a page you can test this on. Once you have that, go to your Fauna dashboard and create a new Comment record that looks like this:

1
{
2
  "post_slug": <your post slug here>,
3
  "body": "This is a sample comment",
4
  "submitter": "Me",
5
  "created_at": Now()
6
}

This should mean that Fauna will retrieve this comment when it hits the GraphQL endpoint we made above. Try refreshing your page (with the javascript loaded into it) and see if the comment appears in your console. If it does, you know it’s working!

Populating a comment section

So we’re fetching the comment, and it should be coming through via our javascript fetch. Our next goal is to actually turn raw JSON into a nice set of comments.

First, let’s make sure there’s somewhere on the blog page where comments go. Perhaps…

1
<div class="comments-section"><noscript>You need to turn javascript on to see comments here.</noscript></div>

Now how do we populate this section? Well, we’ll need to do the following:

  • Get the “slug” (URL identifier) for this post
  • Hit that GraphQL endpoint we set up above, with the relevant options
  • And then populate the page with those comments

Let’s do it!

1
// Set up useful values
2
let commentsSection = document.querySelector(".comments-section")
3
let FAUNA_GRAPHQL_ENDPOINT = "https://graphql.fauna.com/graphql"
4
let FAUNA_API_KEY = "add your API key here"
5
6
// Post slug = URL path
7
let post_slug = window.location.pathname
8
9
10
// Assemble graphql query and headers
11
let query = {
12
  operationName: "PostComments",
13
  query: `query PostComments {commentsByPostSlug(post_slug:"${post_slug}") { data { body submitter created_at} }}`
14
}
15
16
let fetchOptions = {  
17
  headers: { Authorization: `Bearer ${FAUNA_API_KEY}` },
18
  method: "POST",
19
  body: JSON.stringify(query)
20
}
21
22
// Perform the fetch operation
23
fetch(
24
  FAUNA_GRAPHQL_ENDPOINT,
25
  fetchOptions
26
)
27
  .then(r => r.json())
28
  .then(payload => {
29
    // Payload should be an array of comments, each of which
30
    // contains `post_slug`, `body`, `submitter`, `created_at`
31
32
    payload.forEach(comment => {
33
      // Make a date in the form dd/mm/yyyy
34
      let dateString =
35
        [
36
          comment.created_at.getDate(),
37
          comment.created_at.getMonth() + 1,
38
          comment.created_at.getFullYear()
39
        ]
40
        .map(e => e.toString().padStart(2, "0"))
41
        .join("/")
42
43
      // And let's ensure we escape html in user-supplied values
44
      let submitter = new Option(comment.submitter).innerHTML
45
      let body = new Option(comment.body).innerHTML
46
47
      // Build the comment. Use Option().innerHTML to escape html in the comment text
48
      let thisComment = document.createElement("div")
49
      thisComment.classList.add("comment")
50
      thisComment.innerHTML = `
51
        <div class="comment-metadata">
52
          <div class="comment-submitter">${submitter}</div>
53
          <div class="comment-date">${dateString}</div>
54
        </div>
55
        <div class="comment-body">${body}</div>`
56
57
      commentsSection.appendChild(thisComment)
58
    })
59
  })   

You may need to change the relevant CSS selectors to fit in with your own page. But if everything lines up, you should find yourself with your sample comment appearing on your page

To conclude

At this stage:

  • We can fetch comments from our database within our app
  • We can programmatically display them on our webpage!

Feels like a lot of work for two bullet points, right? That’s OK - this will be a great way to test things as we move forward. In the next post, I’ll go over setting up commenting and moderation. Now we’ve done this work, actually implementing commenting isn’t too difficult, but moderation is going to be a fun little journey.


  1. Full disclosure: I know next to nothing about running a good GraphQL query. I’ve picked most of this up by trial and error, correcting this code over and over again until it runs without causing any issues.