Rest API Framework

API Endpoints and Controllers

Overview

Below are all files and directories in the REST API Framework related to this section

├── src/
│   ├── pages/
│   │   └── api/
│   │      └── [...params].js
│   ├── hooks/
│   │   ├── useQuery.js
│   │   └── useMutation.js
└── server/
    ├── models/
    │   └── User.js
    ├── controllers/
    │   ├── base.js
    │   └── users.js
    └── utils/
        └── request.js

Controllers

Controllers are request handlers, which take in a request and output a response. When REST API Framework is installed, there will be a Base controller, which will handle 4 CRUD operations by default:

  • read: handle a GET request
  • create: handle a POST request
  • update: handle a PUT or PATCH request
  • delete: handle a DELETE request

To create a controller for a specific Model, you can create a controller file, whose name will be also the API route, and extends the Base controller. The Base controller constructor has 2 arguments: modelName and options

  • modelName: filename of the related Model
  • options: options to turn on or off the CRUD operations

Below is an example of how to define a controller

// server/controllers/users.js

import { BaseController } from 'server/controllers/base

export default class Users extends BaseController {
  constructor() {
    super("User", {
        allowMethods: {
        delete: false,
        },
    })
  }

  async create(req, res) {
    const { data } = req.body

    if ("password" in data) {
      req.body.data.password = await hashPassword(data.password)
    }

    super.create(req, res)
  }

  async login(req, res) {
    // login handle
  }
}

In the example above, you can see that you also can override the default CRUD methods from Base controller with specific logic for a Model and handle the logic by yourself or call the super method to continue the flow with Base method.

You can define your custom methods (actions) also, and to map the route to this method, just add a new item to the apiMapping at [...params].js file like below:

// src/pages/api/[...params].js

// item signature

// routeName_requestMethod: "controller/method"

const apiMapping = {
  login_POST: "users/login"
}

Of course, all the codes here are just boilerplate and suggestions, you can customize them on your own. But if you don't know what to do, that's all the files you need to know about controllers and you should keep the other parts untouched.

API Request React Hooks

REST API Framework has 2 built-in React Hooks that allow you to communicate with the server API Endpoints: useQuery and useMutation

useQuery hook, wrapping the SWR and using Axios as the fetcher, allows you to send a GET request to the server and fetch data.

// Calling signature
const { data, mutate, isValidating } = useQuery(["apiEndpoint", "queries"])
  • data: response body
  • mutate: a function to rerun the query (refetch)
  • isValidating: a boolean to indicate that the request is in progress and not done (isLoading)

useMutation hook allows you to call other request types (POST, PUT, PATCH, DELETE), but unlike useQuery which sends the request on call, useMutation will return a mutation function that you can use to lazily send requests.

// Calling signature
const [mutate] = useMutation({ url: apiEndPoint, method })

const response = await mutate(requestBody)
Previous
MongoDB ODMs