Giter Site home page Giter Site logo

tracks-controller's Introduction

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 Verb Path Controller#Action Used for
GET /photos photos#index display a list of all photos
GET /photos/new photos#new return an HTML form for creating a new photo
POST /photos photos#create create a new photo
GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit photos#edit return an HTML form for editing a photo
PATCH/PUT /photos/:id photos#update update a specific photo
DELETE /photos/:id photos#destroy delete 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 Verb Path Controller#Action Used for
GET /new profile#new Return an HTML form for creating a new profile
POST / profile#create Create a new profile
GET / profile#show Display the current user's profile
GET /edit profile#show Return an HTML form for editing the current user's profile
PATCH/PUT / profile#update Update the current user's profile
DELETE / profile#destroy Delete 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

tracks-controller's People

Contributors

dependabot-preview[bot] avatar ianwremmel avatar dependabot-support avatar dependabot[bot] avatar

Watchers

James Cloos avatar  avatar  avatar

Forkers

lgtm-migrator

tracks-controller's Issues

Stop passing req, res to action methods

res and req are available both on this and as arguments which can be a confusing. Moreover, if the consumer forgets to import Request and Response from express, (req: Request, res: Response) will get typed as http.Request, http.Response leading to confusing type errors.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


CircleCI using 'master' not configured publish branch (undefined)

Unfortunately this error doesn't have any additional information. Feel free to kindly ask the author of the condition-circle plugin to add more helpful information.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.