Challenges

Create a Dashboard

Add the API

For our dashboard, we need an API to manage the data. Let's add that as the first task.

Create a file called pages/api/post.js and add this content:

import { createPost, updatePost, getPost, deletePost } from '../../lib/data'
import { getSession } from 'next-auth/client'

export default async function post(req, res) {
    const session = await getSession({ req })

    if (!session) {
        res.status(401).send('Unauthorized')
        return
    }

    if (req.method === 'GET') {
        const post = await getPost(req.query.slug, { ownerId: session.user.id })
        return res.send(post)
    }

    if (req.method === 'POST') {
        const payload = {
            ownerId: session.user.id,
            slug: req.body.slug,
            title: req.body.title,
            content: req.body.content
        }

        const post = await createPost(payload)
        return res.send(post)
    }

    if (req.method === 'PATCH') {
        const payload = {
            ownerId: session.user.id,
            slug: req.query.slug,
            title: req.body.title,
            content: req.body.content
        }

        const post = await updatePost(payload)
        return res.send(post)
    }

    if (req.method === 'DELETE') {
        await deletePost(req.query.slug, { ownerId: session.user.id })
        return res.send({})
    }

    res.status(404).send('Unsupported Method')
}

As you can see, we have introduced four APIs to manage a given blog post. Here are those:

  • POST /post : Create a blog post
  • GET /post?slug=<slug> : Get the blog post by slug
  • PATCH /post?slug=<slug> : Update the given blog post
  • DELETE /post?slug=<slug> : Delete the blog post by slug

Let's do a simple activity:

  • Apply the above changes & run the app with yarn dev
  • Open the app from a browser
  • Log in to the app
  • Open the browser console & run the following code
fetch('/api/post', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        slug: 'hello-from-the-api',
        title: 'Hello from the API',
        content: 'This is a simple blog post, added from the API'
    })
})
    .then(res => res.text())
    .then(output => console.log(output))
  • Now reload the page
Q: What was your experience?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: