Learning Express Routers: Part 2: Planning Classes as Routes

Learning Express Routers

Express is a popular minimalist web framework for Node.js that provides functionality for creating individual Router objects for responding to particular routes using specified objects.


Planning Classes as Routes

Express middleware can be defined as function blocks that passes Request and Response objects and the next() function. As shown in the previous part, middlewares can also be stacked, passing control one to another.

It is also possible to define classes with their own internal functions that can handle data and use different, defined routes. This can be accomplished through the Router object.

Consider the following code that defines internal data (this.state) and functions that are setup as the result of dynamic routing.

const express = require('express')
const Router = express.Router();

class Post {
    
    constructor() {

        this.state = {
            id: 1
        };

        Router.get('/:id', this.getPost); 
        Router.post('/:id', this.setPost);

    }

    getPost = (req, res) => {
       res.json(
            {
                response: "get",
                id: this.state.id
            }
        );
    }

    setPost = (req, res) => {

        this.state.id = req.params.id;

        res.json(
            {
                response: "post",
                id: this.state.id
            }
        );
    }

}

new Post();

module.exports = Router;

Note: The required Router object MUST be exported in order for the above code to work. Express middleware must use the Router object as part of any use() usage.

Defined within a file that also creates it, via new Post(), it can be used as part of the following “main” code:

const express = require('express');
const Post = require("./post.js");
const app = express();
const port = 3000;

app.use("/posts", Post);
 
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Like with other middleware, the Post object can be used as part of the “/posts” route, defined internally in the Post object as a root route, “/”, that is exposed to the greater API as “/posts/:id”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.