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

plugdo-mvc

v2.0.9

Published

A module that implements mvc software architecture on top of express module

Downloads

13

Readme

plugdo-mvc

A module that implements mvc web software architecture on top of express module. It help you focus in the implementation of the business logic, instead of writing express routing each time you need a new section. It also avoid the callback hell because you are forced to implement your request methods like get, post, put and delete using class and async functions ES6. You don't even have access to the res and next functions provided by express module, but you can get access to the res and next functions writing your own middlewares.

Compatibility: Node.js version 6+ and Express version 4+

Install with npm:

npm install plugdo-mvc --save

IMPORTANT Directory Structure

In order to found the components, a directory structure must be created as follow:

- public
- source
- views (*Required if you installed a view engine like ejs)

Directories definitions:

public: you will add the html, css, js and font files.
source: the JavaScript files will be added here.
views: Any view engine file will be added here.

PLUGDO MVC

Page

Create a new page is easy, just add a new file in the directory source, plugdo MVC will load the new file after initialization, the loading is not automatic. You must restart the nodejs execution.

First, start the plugdo-mvc server. (use nodemon for development is recommended)

const path = require("path");
const PlugdoMvc = require("plugdo-mvc");

let options = {
    dirname: __dirname
};

global.mvc = new PlugdoMvc(opts); // The instance must be added to the global context.
mvc.start(3000);

Create a page, adding a file in the directory source. The page must return a json model. An example is:

const Page = require("plugdo-mvc/Page");

class UserPage extends Page {
    constructor() {
        /*
        ** Parameters
        ** - path: Always start with the /.
        ** - view_file: The file will be found in the views directory.
        ** - middleware (It is optional. It could be a express middleware function).
        */
        super("/users", "users.html");
        this.methods = {
            get: this.get,
            post: this.post
        }
    }

    async get(req) {
        return {
            title: "Users"
        }
    }

    async post(req) {
        return {
            title: "Users"
        }
    }
}

mvc.page(new UserPage()); // the mvc will be found because It was added to the global context

The expected URL will be: http://domain.com/users

You provide the path and the view file as parameters in the super function.

View Engines

Implement a view engine is simple. Let's check the following example including the plugdo-view-engine module.

const path = require("path");
const { pve } = require("plugdo-view-engine");
const md = require('marked-engine-highlightjs');
const PlugdoMvc = require("plugdo-mvc");

let options = {
    dirname: __dirname
};

global.mvc = new PlugdoMvc(opts);

// Register the view engine
/*
** Parameters
** - file_extension: The extension of the file.
** - view engine: The view engine render.
*/

// EJS View Engine
// You must install the ejs view engine:
// npm install ejs --save
mvc.set('view engine', 'ejs');

// Markdown View Engine
mvc.engine('md', md.renderFile);

// Plugdo View Engine
mvc.engine('html', pve.render);
pve.setPath(path.resolve(__dirname) + "/components");

// All the files with extension .html will be render using the plugdo-view-engine.

mvc.page404 = "/404.html";
mvc.start(path.resolve(__dirname));

Services

Create a new service is easy, just add a new file in the directory source, plugdo MVC will load the new file after initialization, the loading is not automatic. You must restart the nodejs execution.

class UserService {
    get() {
        return [
            { id: 1, amount: 20 },
            { id: 2, amount: 70 },
            { id: 3, amount: 10 },
        ]
    }
}

mvc.service("userService", new UserService());

You can use this service in your page or api as follow:

const Page = require("plugdo-mvc/Page");

class UserPage extends Page {
    constructor() {
        ... // Code hidden
    }

    async get(req) {
        let service = mvc.service("userService");
        return service.get();
    }

    .... // Code hidden
}

mvc.page(new UserPage()); // the mvc will be found because It was added to the global context

API

Create a new api is easy, just add a new file in the directory source, plugdo MVC will load the new file after initialization, the loading is not automatic. You must restart the nodejs execution.

const Api = require("plugdo-mvc/Api");

class UserAPI extends Api {
    constructor() {

        /*
        ** Parameters
        ** - path: Always start with the /.
        ** - middleware (It is optional. It could be a express middleware function).
        */
        super("/api/users");
        this.methods = {
            get: this.get,
            post: this.post,
            put: this.put,
            delete: this.delete
        }
    }

    async get(req) {
        let service = mvc.service("userService");
        return service.get();
    }

    async post(req) {
        return {
            success: true
        };
    }

    async put(req) {
        return {
            success: true
        };
    }

    async delete(req) {
        return {
            success: true
        };
    }
}

mvc.api(new UserAPI());

The expected URL will be: http://domain.com/api/users

Global Middleware

You can defined a global middleware to manage any authorization logic. The global middleware is provided as parameter when you create the PlugdoMvc instance. This global middleware will be executed before any other middleware registered, even before the express return the files from the public directory. You can apply authorization logic to the public files.

const path = require("path");
const PlugdoMvc = require("plugdo-mvc");

let options = {
    dirname: __dirname,
    middleware: (req, res, next) => {
        // You can add any logic here.. maybe authorization access control?
        next();
    }
};

global.mvc = new PlugdoMvc(opts);

mvc.start(path.resolve(__dirname));

Extra Features

Redirect

Redirect to another page is simple. Just return the property "redirectTo" in the model.

const Page = require("plugdo-mvc/Page");

class LoginPage extends Page {
    constructor() {
        super("/login", "login.html");
        this.methods = {
            get: this.get
        }
    }

    async get(req) {
        let service = mvc.service("loginService");
        let result = await service.login(req.query);

        if(result.success) {
            return {
                redirectTo: "/dashboard"
            }
        }
        else {
            return {
                success: false,
                error: "Username or password are incorrect",
                errorCode: 703
            }
        }
    }
}

mvc.page(new LoginPage()); // the mvc will be found because It was added to the global context

Api and Page Second Argument

All the request methods receive the first argument req but also you receive a second argument with few properties availables.

Page Second Argument

....

async get(req, opts) {
    /* 
    ** Properties availables in the opts argument
    ** - append (https://expressjs.com/es/api.html#res.append)
    ** - cookie (https://expressjs.com/es/api.html#res.cookie)
    ** - clearCookie (https://expressjs.com/es/api.html#res.clearCookie)
    ** - attachment (https://expressjs.com/es/api.html#res.attachment)
    ** - download (https://expressjs.com/es/api.html#res.download)
    ** - get (https://expressjs.com/es/api.html#res.get)
    ** - type (https://expressjs.com/es/api.html#res.type)
    **
    ** All the properties are documented in express js documentation.
    */

    return {
        success: true
    }
}

....

Api Second Argument

....

async get(req, opts) {
    /* 
    ** Properties availables in the opts argument
    ** - append (https://expressjs.com/es/api.html#res.append)
    ** - cookie (https://expressjs.com/es/api.html#res.cookie)
    ** - clearCookie (https://expressjs.com/es/api.html#res.clearCookie)
    ** - get (https://expressjs.com/es/api.html#res.get)
    **
    ** All the properties are documented in express js documentation.
    */

    return {
        success: true
    }
}

....

Global MVC Object

The global mvc object provides some useful properties.

mvc.server; // This is the express instance
mvc._port; // This is the port
mvc._paths; // This property save all the paths of the Pages and Apis
mvc._dirname; // This is the __dirname
mvc._filePath; // This is the path.resolve(mvc._dirname)

Quick Notes

The req parameter injected in the page and api method is the express object, if you need more details about the properties available, just go to expressjs.com documentation.