npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ianwremmel/tracks-controller

v2.0.5

Published

<!-- (optional) Put banner here -->

Downloads

3

Readme

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