Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cng-node-js-utils

Package Overview
Dependencies
Maintainers
1
Versions
66
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cng-node-js-utils

for nodejs utils in server

  • 3.0.4
  • latest
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

EASY-EXPRESS-API-SERVER-FOR-PRIVATE-CLOUD - lib utils for nodejs include post, get, ip, ldap, token, waiting, validators

1. install

npm i cng-node-js-utils@latest

2. index.js of this libs

const {
  expHandlers,
  validators,
  arrObj,
  dateUtil,
  excelUtils,
  expUtil,
  htmlUtil,
  ipInfo,
  jsEncrypt,
  ldapLogin,
  myDevice,
  pdfUtil,
  postHandler,
  qrCodeUtil,
  rsaService,
  Router,
  secretUtil,
  sendGmail,
  uniqueid,
  vnHandler,
  waiting,
  webService,
  createSubFolder,
  convertPath2ObjectName,
  createEntryIndex,
  captchaUtil
} = require("cng-node-js-utils")

console.log("This time:", arrObj.getTimestamp());

3. Set req.functionCode for validate Right of Api

// 
const { setFunctionFromPath } = require("cng-node-js-utils").expHandlers;
// if (req.isFullPath) then req.functionCode = req.pathName; 
// return req.functionCode = subpath;

4. Send Gmail by API very easy:

  const { sendGmail } =require("cng-node-js-utils");
  sendGmail((receiver, subject, content, senderGmail, passGmail, fromEmail, host = 'smtp.gmail.com', port = 465, secure = true)
  .then(ok=>console.log(ok))
  .catch(err=>console.log(err))

5. Use LDAP following:

// define your config to your ldap server
const ldapCfg = {
    ldapServerUrl: 'ldap://<host ip or host name>:389'
    , domainNameEmail: '@<your domain name>'
    , connectTimeout: `<timeout when ldap server not response>`
};
// init your connection
const ldapLogin = new LDAPLogin(ldapCfg.ldapServerUrl, ldapCfg.domainNameEmail, ldapCfg.connectTimeout);
// for verify LDAP
let user = await ldapLogin.login(user.username, passHash);
// if error no user return;

6. Use Router following:

  • 6.1 define one router:
// in this library,  FROM 0.0.5  for auto web API with req.error and req.finalJson in Router
const { postHandler, Router } =require("cng-node-js-utils");

// user custom class or functions:
const { serverHandler } = require("../../handlers/server")

const functionPaths = {
   // for POST method = CREATE = insert/import
    POST: {
        "/test": [
            postHandler.jsonProcess        
            , serverHandler.getUserDevice   
            // ... in the Router, auto include 2 function:
            // , checkErrorBeforeResource     // return res(435, {error}) for req.error
            // , sendFinnalJson               // return res(200, req.finalJson or {})
            // ... so you do not add more function for response if you want
        ],
        //...
    },
    // for GET method = select
    GET: {
        "/test": [
            postHandler.getToken              // return reg.token
            , serverHandler.verifyToken       // return req.user or req.error
            , serverHandler.getResource       // web response => return req.finalJson for user api and next()
            // ... in the Router, auto include 2 function:
            // , checkErrorBeforeResource     // return res(435, {error}) for req.error
            // , sendFinnalJson               // return res(200, req.finalJson or {})
            // ... so you do not add more function for response if you want
        ],
        //...
    },
    // UPDATE = update
    PUT: {
        "/test": [
            postHandler.getToken              // return reg.token
            , postHandler.jsonProcess    
            , serverHandler.verifyToken       // return req.user or req.error
            , serverHandler.getResource       // web response => return req.finalJson for user api and next()
            // ... in the Router, auto include 2 function:
            // , checkErrorBeforeResource     // return res(435, {error}) for req.error
            // , sendFinnalJson               // return res(200, req.finalJson or {})
            // ... so you do not add more function for response if you want
        ],
        //...
    },
    // DELETE = delete
    DELETE: {
        "/test": [
            postHandler.getToken              // return reg.token
            , postHandler.jsonProcess
            , serverHandler.verifyToken       // return req.user or req.error
            , serverHandler.getResource       // web response => return req.finalJson for user api and next()
            // ... in the Router, auto include 2 function:
            // , checkErrorBeforeResource     // return res(435, {error}) for req.error
            // , sendFinnalJson               // return res(200, req.finalJson or {})
            // ... so you do not add more function for response if you want
        ],
        //...
    },
}
// export router of Express the same old version
module.exports = (new Router(functionPaths)).getExpressRouter();
  • define index.js in ./routes as:
// define api path for many router .... as following
const apiRoutes = [
    // is one router as https://yourhost/yourBaseDir/api --> function in router
    {
        path: `/api`
        , route: require('<your router file above as you define in 6.1> ')
    }
    // ,
    // ... another router
]
module.exports = (app, ioSubDir) => {
    // Init routers for aps in express server
    for (let r of apiRoutes) {
        console.log("*> THE ROUTES of this server:", `${ioSubDir}${r.path}`);
        app.use(`${ioSubDir}${r.path}`, r.route);
    }
}

7. Express server for Easy config only one minute. SAMPLE SERVER: make server following in file ./test-server-express.js

// define config
const expressCfg = {
    // Port for server
    port: 8080
    // base
    , baseDirectory: "/socket"
    // If you want https define:
    // , https: {
    //     privateKey: "./cert/private.key",
    //     certificate: "./cert/certificate.crt"
    // }
    // default404Page:`<h1>Error Page 404 if you want</h1>`,
    // static html for root
    // , staticRoot: __dirname + '/client-c3-www/www'
    // static for baseDirectory
    // , staticHtml: __dirname + '/client-c3-www/socket-www/www'
    // if debug
    , isDebug: true
    // include cors for API web
    , domainIncludeCors:
        [
             'localhost'
        ]
};

// if you want to block ddos you have to install dddos:
const ddosUse = null; //= require('./ddos/ddos-config').express('ip', 'path'),

// define route follow # 6
const apiRoutes = require("./routes");

// if you want to run socketIo, you have to define socketIo 
const socketIoCfg = null ; //require('./server-socketio');

// include main libarary
const { ExpressServer } =require("cng-node-js-utils");
// define class
const expressServer = new ExpressServer(expressCfg, ddosUse, apiRoutes, socketIoCfg);
// start server
      expressServer.start();

8. run and test server SAMPLE very easy:

node ./test-server-express.js

Test server in: http://localhost:8080 and see web, and some API you define in routers. EASY

Keywords

FAQs

Package last updated on 23 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc