natural-utility
v1.1.1-beta.1
Published
natural-utility is a simple helper tool to get easily your work as a module loader, route middleware, plugin middleware and flash message.
Downloads
14
Maintainers
Readme
natural-utility
natural-utility
is a simple helper tool to get easily your work as a module loader, route middleware, plugin middleware and flash message.
Table of Contents
Get Started
Language Translate
Framework Support
| Framework Support | globalModule | pluginMiddleware | flashMessage | | ------------- | ------------- | ------------- | ------------- | | Express | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | | Koa | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | | Hapi | :heavy_check_mark: | :x: | :x: | | Fastify | :heavy_check_mark: | :heavy_check_mark: | :x: | | Restify | :heavy_check_mark: | :x: | :x: | | Sails | :heavy_check_mark: | :x: | :x: | | Total | :heavy_check_mark: | :x: | :x: | | Adonis | :heavy_check_mark: | :x: | :x: | | Feathers | :heavy_check_mark: | :x: | :x: | | Keystone| :heavy_check_mark: | :x: | :x: | | Nest| :x: | :x: | :x: | | LoopBack| :x: | :x: | :x: | | Mean| :x: | :x: | :x: |
Features
- [x] Parallel Module Loader
- [x] Parallel Route Middleware
- [x] Parallel Plugin Middleware
- [x] Flash Message
- [x] Global Module Access
Installation
$ npm i natural-utility --save
| OR
$ yarn add natural-utility --save
Example Usage
// register all module
const natural = require("natural-utility");
natural.globalModule(
["express", "http", "path", "bodyParser", "logger", "cookieParser"],
["express", "http", "path", "body-parser", "morgan", "cookie-parser"]);
// init all module
const app = express();
const server = http.createServer(app);
// init all route
const indexRoute = require("./routes/index.route");
// register all plugin middleware
natural.pluginMiddleware(app, [
bodyParser.urlencoded({ extended: false }),
bodyParser.json(),
cookieParser(),
logger("dev"),
natural.flashExpress()
]);
// register template engine
app.set("views", path.join(__dirname, "/views"));
app.set("view engine", "ejs");
// register all route midlleware
natural.routeMiddleware(app, [indexRoute]);
// listening server
server.listen(3000, () => console.log("server is running"));
API Reference
naturalModule
globalModule ( inputs: [string...], modules: [string...] ) function method of
naturalModule
to register each given module without the need to rewriterequire
, then the module will be run as parallel, the module can also be accessed as a global in every file or route in many ways, which you haven't to re-register the same module as you want to use it, note: global module only supports writing format CommonJS as require.Before - example usage not using natural-utility
// register all module const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); // listening server server.listen(3000, () => console.log("server is running"));
After - example usage using natural-utility
// register all module const natural = require("natural-utility"); natural.globalModule(["express", "http"], ["express", "http"]); // init all module const app = express(); const server = http.createServer(app); // listening server server.listen(3000, () => console.log("server is running"));
naturalRoute
routeMiddleware ( app, routes: [string...] ) function method of
naturalRoute
to register each given route, then the route will be run as parallel, which it haven't to rewriteapp.use
middleware many of times to register every each route.Before - example usage not using natural-utility
// register all module const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); // init all route const indexRoute = require("./routes/home"); const usersRoute = require("./routes/users"); // register all route middleware app.use(indexRoute); app.use(usersRoute); // listening server server.listen(3000, () => console.log("server is running"));
After - example usage using natural-utility
// register all module const natural = require("natural-utility"); natural.globalModule(["express", "http"], ["express", "http"]); // init all module const app = express(); const server = http.createServer(app); // init all route const indexRoute = require("./routes/home"); const usersRoute = require("./routes/users"); // register all route middleware natural.routeMiddleware(app, [indexRoute, usersRoute]); // listening server server.listen(3000, () => console.log("server is running"));
naturalPlugin
pluginMiddleware ( app, plugins: [string...], options: {} ) method of the
naturalPlugin
function to register each given plugin, the plugin will be run as parallel, which it haven't to rewriteapp.use
middleware many of times to register every each plugin.Before - example usage not using natural-utility
// register all module const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); const bodyParser = require("body-parser"); const cookieParser = require("cookie-parser"); const logger = require("morgan"); // init all route const indexRoute = require("./routes/home"); const usersRoute = require("./routes/users"); // register all plugin middleware app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(logger("dev")); // register all route middleware app.use(indexRoute); app.use(usersRoute); // listening server server.listen(3000, () => console.log("server is running"));
After - example usage using natural-utility
// register all module const natural = require("natural-utility"); natural.globalModule( ["express", "http", "bodyParser", "cookieParser", "logger"], ["express", "http", "body-parser", "cookie-parser", "morgan"]); // init all module const app = express(); const server = http.createServer(app); // init all route const indexRoute = require("./routes/home"); const usersRoute = require("./routes/users"); // register all plugin middleware natural.pluginMiddleware(app, [ bodyParser.urlencoded({ extended: false }), bodyParser.json(), logger("dev"), ]); // register all route middleware natural.routeMiddleware(app, [indexRoute, usersRoute]); // listening server server.listen(3000, () => console.log("server is running"));
naturalFlash
flashMessage ( ) function method of
naturalFlash
to display an error message or any message that might be displayed later, every requested time is made, note:cookie-parser
is not required now and flashMessage is now renamed to flashExpress, more info check here.Before - example usage not using natural-utility
//app.js // register all module const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); const flash = require("connect-flash"); const session = require("express-session"); //init all route const indexRoute = require("./routes/home"); const usersRoute = require("./routes/users"); // register all plugin middleware app.use(flash()); app.use(session({ secret: "kucing", resave: false, saveUninitialized: false })); app.use((req, res, next) => { res.locals.messages = require("express-message")(req, res); }); // register all route middleware app.use(indexRoute); app.use(usersRoute); // listening server server.listen(3000, () => console.log("server is running"));
// routes/home.js // register all module const express = require("express"); const router = express.Router(); // setup route middleware router.get("/", (req, res, next) => { req.flash("username already exist"); res.render("home", {}); }); // export route middleware module.exports = router;
<!-- views/home.ejs --> <html> <title> Natural </title> <body> <!-- result message --> <h1> <%- messages() %> </h1> </body> </html>
After - example usage using natural-utility
// app.js // register all module const natural = require("natural-utility"); natural.globalModule( ["express", "http", "cookieParser"], ["express", "http", "cookie-parser"]); // init all module const app = express(); const server = http.createServer(app); // init all route const indexRoute = require("./routes/home"); const usersRoute = require("./routes/users"); // register all plugin middleware natural.pluginMiddleware(app, [ cookieParser(), natural.flashExpress() ]); // register all route middleware natural.routeMiddleware(app, [indexRoute]); // listening server server.listen(3000, () => console.log("server is running"));
// routes/home.js // register all module const express = express(); const router = express.Router(); // setup route middleware router.get("/", (req, res, next) => { // single message req.flash("username already exist"); res.render("home", {}); }); // export route middleware module.exports = router;
// routes/home.js // register all module const express = express(); const router = express.Router(); // setup route middleware router.get("/", (req, res, next) => { // multiple message let errors = ["username is required", "email is required", "password is required"]; for(let i of errors) { req.flash(i); } res.render("home", {}); }); // export route middleware module.exports = router;
<!-- views/home.ejs --> <html> <title> Natural </title> <body> <!-- sigle message --> <h1> <%- messages() %> </h1> </body> </html>
<!-- views/home.ejs --> <html> <title> Natural </title> <body> <!-- multiptle message --> <ul> <% if(messages()) { %> <% messages().forEach((msg) => { %> <li> <%= msg %> </li> <%})%> <%}%> </ul> </body> </html>
Working With Database
MongoDB
example usage using mongodb
// register all module const natural = require("natural-utility"); natural.globalModule(["mongodb"], ["mongodb"]); // init collection const database = db.db("testing"); // init data const myData = { name: "John Doe", age: 28 }; // insert data to database database.collection("test").insertOne(myData,function(err, res) { if(err) throw err; console.log("successfuly store data to database"); db.close(); }); });
MySQL
example usage using mysql
// register all module const natural = require("natural"); natural.globalModule(["mysql"], ["mysql"]); // setup database connection const con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "testing" }); // init connection con.connect(function(err) { // insert data to database const sql = "INSERT INTO test (name, age) VALUES ("john doe", 28)"; con.query(sql, function (err, result) { if (err) throw err; console.log("data successfuly to store to database"); }); });
PostgreeSQL
example usage using postgree sql
// register all module const natural = require("natural"); natural.globalModule(["pg"], ["pg"]); // setup database connection const client = new pg.Client({ user: 'root', host: 'localhost', database: 'testing', password: '123', port: 5432, }); // init connection client.connect(); // insert data to database const query = `INSERT INTO users (name, age) VALUES ('john doe', 28)`; client.query(query, (err, res) => { if (err) console.error(err); console.log('Data succesfuly to store to database'); client.end(); });
Mongoose
example usage using mongoose
// register all module const natural = require("natural-utility"); natural.globalModule(["mongoose"], ["mongoose"]); // setup database connection mongoose.connect("mongodb://localhost:3000/testing"); // setup schema const setSchema = new mongoose.Schema({ name: String, age: Number }); // register schema const userSchema = setSchema.model("test", setSchema); // insert data to database userSchema.created({ name: "john doe", age: 28 }, (err, res) => { if(err) return err; console.log("data successfuly store to database"); });
Working With Framework
How To Test
natural-utility uses supertest
to mock http requests, thus testing no longer relies on the http server.
$ npm install $ npm test $ npm run test
Contributors
- Vikri Kurniawan - English Translator
- Restu Wahyu Saputra - Indonesian Translator