core-x-express
v1.0.0
Published
A library as express helper.
Downloads
1
Maintainers
Readme
Core Express
A library as express helper.
Installation
npm install core-x-express
Configuration
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.