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

express-ve

v0.0.35

Published

An express-ve way to start an [express](https://expressjs.com/) project.

Downloads

8

Readme

Express-ve express starter

An express-ve way to start an express project.

Checkout a demo project here or Learn how to use express-ve here

Are you starting an express project? Are you adding some routing to it? Do you plan to add some mongodb data using mongoosejs? Then you can start your project with express-ve and have default mappings accelerate your development.

Installing

npm install express-ve

or

yarn add express-ve

How do you create and start the app?

const {createContainer} = require('express-ve')
const path = require('path') // optional

createContainer().then((container) => {
    // Listen as usual
    app.server.listen(8000 /* PORT */).on('listening', () => {
        console.log(`App live and listening on port 8000`)
    })
})

It's very simple and straightforward and yet createContainer creates a seamless routing, repo and organized config. Let's how! How do I add a routing?

Routing

express-ve routing makes use of conventions on the folder structure and maps them to route paths. The mapping is inspired by nuxtjs routing.

First define a folder named routes at the root of your project.

/**
 * routes are registered according to the following convention
 * Path                            Route
 *
 * routes/users/_id.js             GET /users/{id}
 * routes/users/_id/post.js        POST /users/{id}
 * routes/users/_id__post.js       POST /categories/:id/archive
 * routes/users/index.js           GET /users/
 * routes/index.js                 GET /
 * routes/put.js                   PUT /
 */

A single route has the following structure

// routes/users/_name.js
module.exports = (container) => {
    return {
        route: async (req, res) => {
            return res.json({
                message: `Welcome to express-ve ${req.params.name}`,
            })
        },

        middlewares: [] // oh really? you support middlewares too? Show me below.
    }
}

Route middlewares

Middlewares can be defined in one of two ways per route or globally.

Per Route

Just as shown in the last code snippet above, you return from a route file an object with keys 'route' and middleware. The middleware is an array of all middlewares that will apply to this specific route.

const multer = require('multer')
const upload = multer({storage})
// const storage ... define your storage here

middlewares: [async (req, res, next) => {
    await mkdirp(`${__dirname}/../../uploads/${req.bot._id}`)
    next()
}, upload.single('picture')]

The code snippet above has two middlewares and each will run one after the other the first one making sure a directory exists, the other one taking the files from the request and uploading it using multer.

Globally

You can also define middlewares globally by following the same folder structure conventions like that of routes. When you define a route at the same level of nesting as a specific route, the route and all others nested under it will be protected by the middleware

For example defining a middleware at the path middlewares/v1.js will protect all the paths v1/, v1/users/:id, v1/:id etc. Defining it under the path middlewares/users/index.js it will protect routes users/, users/:id, POST: users/:id, users/:id/upload etc.

How do I define a global middleware

First create a folder named middlewares at the root of your project and create your middleware file inside it. A single middleware file can look something like this:

// Here is a google authenticator middleware example
const {OAuth2Client} = require("google-auth-library");
module.exports = (container, route) => {
    return async (req, res, next) => {
        // You can add exception to a global middleware like below
        if (route.startsWith('/v1/auth') || route.startsWith('/v1/telegram/handler/'))
            return next()

        try {
            const token = req.headers.authorization
            if (!token) return res.status(401).json({message: 'No token provided'})
            const client = new OAuth2Client(container.config.CLIENT_ID) // Oh configs too? How do they work? Tell me more.
            const ticket = await client.verifyIdToken({
                idToken: token,
                audience: container.config.CLIENT_ID
            })

            const payload = ticket.getPayload()
            const googleId = payload['sub']

            let user = await container.repo.user.findUserByGoogleId(googleId)
            if (user) {
                req.user = user
                return next()
            }

            return res.status(401).json({message: 'User is not authenticated'})
        } catch (ex) {
            return res.status(401).json(ex.message ? {message: ex.message} : ex)
        }
    }
}

Configurations

Define your configurations inside a config folder at the root of your project, and they will be accessible as container.config.google.CLIENT_ID. You can separate your configurations by environments by defining each of the configs in different folders dev, staging and production for example. The configs can then be accessed as container.config.dev.google.CLIENT_ID or container.config.staging.google.CLIENT_ID

Models

You can define your models inside a folder named db at the root of your project. A single model looks like this:

module.exports = (mongoose) => {
    const UserSchema = new mongoose.Schema({
        name: String,
        picture: String,
        email: {
            type: String,
            unique: true
        },
        googleId: String,
    }, { timestamps: true })

    mongoose.model('User', UserSchema)
}

Repositories

Repos provide a few default database operations all, create, createMany, delete, get and update. They all accept req.body in the router and return relevant results. all returns all entries from the database by using the name of the repo as the model.

container.repo.command.all() will return all commands from the database as long as the Command schema is defined. It accepts params from the request body, it can also filter out results using query parameters. It also supports pagination out of the box. All you have to do is add page and limit parameters to the request. The README will be updated with more details on this.