An express-ve way to start an express project

Overview

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.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.

You might also like...

Twitter recommends that the majority of developers start to think about migrating to v2 of the API

Passport-Twitter2.0 with PKCE Twitter recommends that the majority of developers start to think about migrating to v2 of the API. This package is a Pa

Dec 11, 2022

A quick start Create React App template with react-router-dom, material-ui, gh-pages and firebase

A quick start Create React App template with react-router-dom, material-ui, gh-pages and firebase. With google authentication, routing and deployment capabilities built in.

Feb 22, 2022

a quick start boilerplate for developing web3 apps and deploying smart contracts.

create-web3 A boilerplate for starting a web3 project. This boilerplate quickly creates a mono repo with 2 environments, a Next JS environment for fro

Dec 16, 2022

The website can be used to creat a new game and start adding players and there scores! 🙌

The website can be used to creat a new game and start adding players and there scores! 🙌

LeaderBoard Welcome! 👋 This Website Allows you to creat your game and add your players score. ScreenShot 1 ScreenShot 2 ScreenShot 3 ScreenShot 4 :--

Aug 30, 2022

Start building admin tools on Slack without going into complex slack syntax and flows.

Start building admin tools on Slack without going into complex slack syntax and flows.

Slackmin Slackmin helps in easy integration with slack to use slash commands, interactive components, format and send messages, design and use modals.

Jan 2, 2023

MUI Core is a collection of React UI libraries for shipping new features faster. Start with Material UI, our fully-loaded component library, or bring your own design system to our production-ready components.

MUI Core is a collection of React UI libraries for shipping new features faster. Start with Material UI, our fully-loaded component library, or bring your own design system to our production-ready components.

MUI Core MUI Core contains foundational React UI component libraries for shipping new features faster. Material UI is a comprehensive library of compo

Dec 30, 2022

The best place to start your Nuxt Theme.

Nuxt Theme Starter Create Nuxt theme with this GitHub template. Setup Make sure to install the dependencies: # yarn yarn install # npm npm install #

Dec 22, 2022

💻 A simple Create Next App template to start your projects with Next.js, TypeScript, ESLint, Prettier and other tools.

âš¡ Next Typescript Template âš¡ A simple Create Next App template to start your projects with Next.js, TypeScript, ESLint, Prettier and other tools. Quic

Nov 23, 2022

Extended version of create-t3-app to make it even faster to start (or maybe slower)

create-T3-app with extra tools/config out of the box create-t3-app is one of the fastest and easiest way to scaffold fullstack app. create-t3-extended

Jan 4, 2023
Owner
Merhawi Fissehaye
Merhawi Fissehaye
Quick way to start a new TypeScript/Next.js/Firebase web app 😼

create-crash-app Template repo to quickly set up an opinionated, strict config, typesafe Next.js project. Get started with create-crash-app by running

Diego Dorantes-Ferreira 5 Oct 28, 2022
A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

CTSP- Create TS Project A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and conf

Jean Rodríguez 7 Sep 13, 2022
Template to start developing a REST API with Node.js (Express), TypeScript, DDD, etc. 🔰🦸

Typescript DDD Boilerplate Plantilla para una API con Typescript basada en arquitectura DDD. En qué consiste este proyecto Este proyecto es un punto d

Bryan Herrera ~ ርᚱ1ናተᛰ ᚻህᚥተპᚱ 3 Nov 26, 2022
Catalogist is the easy way to catalog and make your software and (micro)services visible to your organization in a lightweight and developer-friendly way.

catalogist ?? ?? ?? ?? ?? The easy way to catalog and make your software and (micro)services visible to your organization through an API You were a pe

Mikael Vesavuori 11 Dec 13, 2022
🎨 Beautify your github profile with this amazing tool, creating the readme your way in a simple and fast way 🚀 The best profile readme generator you will find ⚡

Demo Profile Readme Generator The best profile readme generator you will find! About | Technologies | Requirements | Starting | Contributing ?? About

Mauro de Souza 476 Jan 1, 2023
A template to quickly start a new Node.js project

?? A template, for your node project. Including typescript, eslint and prettier.

Lorenzo Carneli 6 Aug 25, 2022
Makes downloading Scratch projects easy. Simply enter two project IDs and click start.

Makes downloading Scratch projects easy. Simply enter two project IDs and click start. No need to pick the right format or include the assets, all of this is done automatically and in the browser.

null 6 May 27, 2022
Avoid setting up a project from scratch. Start using VRTTV 🎉

VRTTV Boilerplate Avoid setting up a project from scratch. Start using VRTTV ?? View Demo · Report Bug · Request Feature ?? What’s this? Are you tired

Diego Do Santos 32 Nov 24, 2022
Nestia template project installed by "npx nestia start"

Nestia Template Outline A template repository for backend projects using nestia. You can create a new project from this boilerplate by running below c

Jeongho Nam 4 Dec 26, 2022
A simple browser extension, intended to get you "Back To Work" when you start slacking off to one of those really addictive sites.

Back to Work A simple browser extension, intended to get you Back To Work when you start slacking off to one of those really addictive sites. What doe

Dheeraj Lalwani 29 Nov 19, 2022