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

core-x-express

v1.0.0

Published

A library as express helper.

Downloads

1

Readme

Core Express

A library as express helper.

Installation

npm install core-x-express

Configuration

  1. Controller/Service
  2. Model
  3. Middleware
  4. Route

Mongodb Configuration

MongoDB for this library is required. You can see the installation manual here.

Ease of modeling requires mongodb configuration. The configuration only requires a full URL address when a model is made. The collection itself doesn't need any requirements so far.

Express

This library only requires ExpressJS to run. You should manually add the middleware to the router and configure the router on the app's router.

const express = require('express');
const app = express();

// This is the instance of Core Express router not the express itself
const router = require('./router'); 

// Configure the router to get the express router instance

app.use('/', indexRouter.getInstance());

Service

Service is a controller function or promise which only uses the request paramater given by the ExpressJS.

Example:

const service = function(req){
    return 'Hello World'; // Displays hello world
}

// router/index.js:
// ...
const {service} = require('../services');
router.get('/', service);

There are 3 types of service return can be applied. Every each of the following will be resolved automatically by the Core Express Routing Algorithm.

  • Direct Return
const service = function(req){
    return 'Hello World'; // Displays hello world
}
  • Promise Return
const service = function(req){
    return new Promise((resolve, reject)=>{ 
        fs.readFile('Demo.txt', 'utf8', (err, data)=>{
            if(err)
                return reject('Some Error Occurred on Reading files');
            resolve(data);
        })
    })
}
  • Non-functional service type
const service = 'Hello World';

They can be combined as follows:


router.get('/direct', (req)=>{
    return 'Hello World';
})
router.get('/promised', (req)=>{
    return new Promise((resolve, reject)=>{
        fs.readFile('Demo.txt', 'utf8', (err, data)=>{
            if(err)
                return reject('Some Error Occurred on Reading files');
            resolve(data);
        })
    });
})
router.get('/non-functional', 'Hello World');

Model

Creating a model is simple. Just simply add configuration for each model. It is basically laravel-like model. There are casts (for retrieving data) and rules (for validating incoming data);

The instance creation (with the options)

const coreExp = require('core-x-express');
const createModel = coreExp.createModel;

const config = {

    // Collection Name or instance of mongojs collection
    collection: 'posts',

    // This is required when you want to insert any data using the model's insert method.
    fillable: ['title', 'content', 'tags', 'images'],

    // To hide any field from response, you can simply add fields to hidden array
    hidden: ['_id'], // Will not show _id field

    // This is based on go-convert algorithm
    casts: {
        title: 'uppercase',
        tags: 'split'
    },

    // Rules are validation rules based on node-input-validator library
    rules: {
        title: 'required|string|maxLength:1000',
        content: 'required|string'
    },

    // Additional Methods or overriding methods
    methods: {
        remove(){
            return 'It is Removed!';
        }
    }
};

const mongoURL = 'localhost:27017/myapp';

const postModel = createModel(
    config, // Model Configuration
    mongoURL // Mongo Database URL
);

Model usage

  • Get All without hidden fields
const postModel = createModel(
    config, // Model Configuration
    mongoURL // Mongo Database URL
);

// Use as service:
const service = (req)=> {
    return postModel.all(); // This is asynchronous
}
  • Find only one (using _id)
const postModel = createModel(
    config, // Model Configuration
    mongoURL // Mongo Database URL
);

// Use as service:
const service = (req)=> {
    return postModel.find(req.params.id); // This is asynchronous
}
  • Find only one using filters
const userModel = createModel(
    config, // Model Configuration
    mongoURL // Mongo Database URL
);

// Use as service:
const service = (req)=> {
    return userModel.find({
        username: req.body.username,
        password: req.body.password
    }); // This is asynchronous
}
  • Insert from post route:
const postModel = createModel(config, mongoURL);

// Use as service:
const service = (req)=> {
    return postModel.insert(req.fields, {
        withValidation: true, // Use predefined rules
        withCasts: false // Use predefined casts
    });
}
  • Adding extended types (for node-input-validator rules and go-convert casts)
const postModel = createModel(config, mongoURL);

// niv = node-input-validator
postModel.use('niv',{
    'in': ({value, args})=>args.includes(value)
})

// gc = go-convert
postModel.use('gc', {
    'split': (input, ...args)=>input.split(args[0] || ' ')
})

// ...

Middleware

Middleware has 4 arguments: request, response, next, and guards Simply use guards and assign it to each route. Guards are included as arrays.

Usage

// Create The middleware
const authenticate = function(req, res, next, guards){
    // Assume that guards are ['admin'];
    let {username, password} = req.body;
    let m = userModel.find({username, password}).then(r=>{
        if(r && guards.includes(r.role))
            next();
    }).catch(e=>{
        res.send('Invalid Credentials');
    });
}

// Use on router (can be used as string, object, or array of combined):
router.get('/posts/add', postModel.insert).middleware('auth:admin'); // string
router.get('/posts/edit', postModel.update).middleware({auth: ['admin']}); // object
router.get('/posts/edit', postModel.update).middleware(['auth:admin']); // array

// Register middleware functions on router:
router.use(
    {auth: authenticate}
);

Route

The basic routing of ExpressJS needs middleware and the routing function. For that, We provided a middleware algorithm which you can simply use laravel-like guards and add it to each route.

Creating the instance:

// Create the instance
const path = require('path');
const Router = require('core-x-express').Router({
        uploadDir: path.join(__dirname, '../uploads') // This is required for uploading files
});

// GET
Router.get('/posts', postModel.all)
// POST
Router.post('/posts/add', postModel.insert)

// Using middlewares:
Router.post('/posts/add', postModel.insert).middleware('auth:admin');

// Prefixing Groups:
Router.prefix('/posts', function(newRouter){
    // Use this newRouter same as Router
    newRouter.get('/', postModel.all);
    newRouter.post('/add', postModel.insert).middleware('auth:admin');
});

// Add middleware functions if there is:
Router.use({
    auth: authenticate,
    ...middlewares
});

Contact or Contribute

Contact us on github if you want to donate us or contribute to this project.