2.0.5 • Published 4 years ago

@ianwremmel/tracks-controller v2.0.5

Weekly downloads
90
License
MIT
Repository
github
Last release
4 years ago

tracks-controller (@ianwremmel/tracks-controller)

license standard-readme compliant npm (scoped) npm

Dependabot badge semantic-release

CircleCI

Add convention to you express routes

Inspired by ActionController, this library provides the conventions that your express app's route config has been missing.

One of the key selling points of Ruby on Rails in Convention over Configuration. It holds strongs opinions and by doing so, if you follow the conventions, your app will do things automatically. On the other hand, Express docs and tutorials don't really hold any options at all on how to organize code; in fact, most tutorials seem to rely on anonymous functions bound directly to routes.

At some point, your app will get too big to just wire anonymous functions to routes. See usage for how Controller can help.

Table of Contents

Install

npm install @ianwremmel/tracks-controller

Usage

This library exports a configuration function that asynchronously produces an express router. Its root parameter points to the directory containing your controllers

import {configure as configureRouteControllers} from '@ianwremmel/tracks-controller';
import path from 'path';

// Take a look @ianwremmel/tracks-boot for a cleaner way to do async loading
(async function boot() {
    const app = express();
    app.use(
        '/',
        await configureRouteControllers({
            // extensions defaults to '.js', but you might want to incldue '.ts'
            // files, for example, if your dev setup does JIT compilation
            extensions: ['js'],
            root: path.join(__dirname, 'controllers'),
        })
    );

    app.listen(3000);
})();

Your controllers should inherit from ResourceController. They'll follow one of the following routing tables.

Routing is taken directly from the rails conventions. Unlike rails, Controller doesn't let you provide a route config; everything is routed based on file location.

HTTP VerbPathController#ActionUsed for
GET/photosphotos#indexdisplay a list of all photos
GET/photos/newphotos#newreturn an HTML form for creating a new photo
POST/photosphotos#createcreate a new photo
GET/photos/:idphotos#showdisplay a specific photo
GET/photos/:id/editphotos#editreturn an HTML form for editing a photo
PATCH/PUT/photos/:idphotos#updateupdate a specific photo
DELETE/photos/:idphotos#destroydelete a specific photo

However, we do provide one convenince that rails doesn't. If you set Controller.singleton to true, your controller will follow a different routing table that makes sense for things like the current user's profile page.

HTTP VerbPathController#ActionUsed for
GET/newprofile#newReturn an HTML form for creating a new profile
POST/profile#createCreate a new profile
GET/profile#showDisplay the current user's profile
GET/editprofile#showReturn an HTML form for editing the current user's profile
PATCH/PUT/profile#updateUpdate the current user's profile
DELETE/profile#destroyDelete the current user's profile

To create a controller and automatically route to it, simply add a file at the corresponding path location in your controllers directory and inherit from ResourceController. Then, implement the above-mentioned methods to begin serving pages.

Your controller must be the default export and must be named according to its path: remove the slashes, make everything PascalCase, and put "Controller" on the end.

/**
 * @file 'users/photos.js'
 */
import {ResourceController} from '@ianwremmel/tracks-controller';

export default UserPhotosController extends ResourceController() {
    async create(req, res) {
        // TODO something with the photo
        res.status.send(201).end
    }
}

ViewControllers

A previous version of this library attempted to provide automatic view rendering in controller form, but all of the bits needed to make it work reasonably had to be too intertwined in the main project for it to stand alone. It may return as its own library at some point. In the meantime, consider something like the following for defining a minimal view controller:

export class ViewController extends ResourceController {
    static async init(req: Request, res: Response) {
        const controller = new this(req, res);
        return new Proxy(controller, {
            get(target, prop, receiver) {
                const value = Reflect.get(target, prop, receiver);

                if (isRouteAction(prop)) {
                    const viewName = `${routify(
                        target.constructor.name
                    )}/${prop}`;

                    return async () => {
                        if (!value) {
                            throw new NotFound();
                        }

                        await value.call(target, req, res);

                        if (res.headersSent) {
                            return;
                        }

                        target.logger.info(`rendering ${viewName}`);
                        /*
                            this is where things break down keeping
                            ViewController in the library; no good way of
                            customizing locals presented itself at thetime and
                            they're critical for Views
                        */
                        const locals = {};

                        target.res.render(viewName, locals);
                    };
                }

                return value;
            },
        });
    }
}

Maintainer

Ian Remmel

Contribute

PRs Welcome

License

MIT © Ian Remmel 2019 until at least now

2.0.5

4 years ago

2.0.3

4 years ago

2.0.4

4 years ago

2.0.2

4 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.1.4

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago