1.1.4 • Published 3 years ago

valence-connect v1.1.4

Weekly downloads
2
License
ISC
Repository
-
Last release
3 years ago

CNX Corporation

Available for Valence ^5.2

Use the valence-connect package when developing your Valence apps in Node.js. With valence-connect, your Node.js apps can participate in Valence role-based security, session management, logging and more. Writing Node.js apps for Valence using valence-connect also allows for maximum portability -- you can move your code between IBM i, Linux and Windows servers with little or no changes.

Documentation    Examples    Tests    Versions

Clean Install

mkdir acme
cd acme
npm init --yes
npm install valence-connect --save

After completing a clean installation start the new node server. You can find more information on starting the server below.

Starting the Node Server

Development

npm start

Debug

$ DEBUG=acme:* npm start

On Windows

> set DEBUG=acme:* & npm start

On Windows: PowerShell

PS > $env:DEBUG="acme:*" ; npm start

Production

When running in production mode the server will be clustered and compress files to improve performance.

npm run start:production

On Windows: PowerShell

PS > npm run start:production_ps

Clustering

By default the server will be clustered when running in production mode and create workers based on the available CPU's. You can override the number of workers produced by setting the WEB_CONCURRENCY environment variable. Set WEB_CONCURRENCY to "0" if you don't want clustering turned on.

$ WEB_CONCURRENCY=3 npm run start:production

On Windows

> set WEB_CONCURRENCY=3 & npm run start:production

On Windows: PowerShell

PS > $env:WEB_CONCURRENCY="3" ; npm run start:production_ps

Examples

After performing a clean install and answering yes to "Automatically create application skeleton?" You will have one example application that displays a list of customers from our example table DEMOCMAST. Be sure the new server is running before attempting to launch the example application.

Try the example by creating a new Valence app in Portal Admin with an application type of "Valence Application". The Path will be the full URL consisting of this server and the route to the example.

http://YOUR_SERVER:PORT/apps/customers/index.html

Example :

http://acme.com:7152/apps/customers/index.html

Structure after a clean install

acme
│
└───bin
│       www.js
│
└───node_modules
│       valence-connect
│       *other modules
│
└───public
│   │
│   └───apps
│   │   │
│   │   └───customers "example"
│   │
│   └───images
│   │       valence_logo.png
│   │
│   └───stylesheets
│           style.css
│
└───routes
│   │   index.js
│   │   valence.js
│   │
│   └───api
│           customers.js "example"
│
└───services
│       Readme.md
│       customers.js "example"
│
└───tests
│       Readme.md
│       services.js "example"
│
└───views
│       error.pug
│       index.pug
│       layout.pug
│
│   .gitignore
│   app.js
│   package.json
│   Readme.md
│   valence.json

valence.json

{
  "url": "http://acme.com:7052/service/connect?key=CD5678F68804D0123112TA0B8C93D1E58",
  "IBMi": true,
  "logging": false
}
PropertyTypeDescription
urlstringValence Connect Web Service URL "Located in Valence Portal Admin/Web Services"
IBMibooleanRunning Valence for IBM i. Pass false if connecting to Valence Universal on Windows, Linux or OS X. Defaults to true if not passed.
loggingbooleanWhen true will capture statistical information which can be viewed in Portal Admin-->Logs.

Valence Connect init

routes/valence.js

/**
 * Valence Router
 */
const express        = require('express'),
      cors           = require('cors'),
      corsWhiteList  = ['http://acme.com:7052'],
      corsOptions    = {
          origin : (origin, callback) => {
              if (typeof origin === 'undefined'
                  || corsWhiteList.indexOf(origin) !== -1) {
                  callback(null, true);
              } else {
                  callback(new Error('Not allowed by CORS'));
              }
          }
      },
      router         = express.Router(),
      valenceConnect = require('valence-connect'),
      customers      = require(global.__services + 'customers/customers');

// Initialize Valence Connect
//
valenceConnect.init();

// Allow Cross Origin
//
router.all('*', cors(corsOptions));

/**
 * Check if the request session is authenticated
 * @param {IncomingMessage} req http request
 * @param {ServerResponse} res http response
 * @param {callback} next continue
*/
let valenceCheck = (req, res, next) => {
    valenceConnect.isAuthenticated(req, res)
        .then(() => {
            next();
        });
};

// Always check before proceeding that the session is valid for all Valence requests
//
router.use(valenceCheck);

// Routes
//

// Example Valence Route "query customers"
//
router.all('/customers/queryAll', customers.queryAll.bind(customers));

module.exports = router;

Tests

After performing a clean install and answering yes to "Automatically create application skeleton?" you will have an example test for the customer service using node-tap.

To run the example services test issue the below command passing a valid session id. You can get a valid session id by logging into the Valence Portal and launching developer tools. Once developer tools is launched go to the console and run Valence.util.Helper.getSid(). That will return your current session id.

$ session=CURRENTSESSIONID npm test

On Windows

> set session=CURRENTSESSIONID & npm test

On Windows: PowerShell

PS > $env:session="CURRENTSESSIONID" ; npm test

Classes

Functions

ValenceConnect

Documentation: Security, session management, logging and utilities

Kind: global class

new ValenceConnect()

Constructor

Example

const valenceConnect = require('valence-connect');

valenceConnect.baseInit() ⇒ Promise.<void>

init session storage

Kind: instance method of ValenceConnect

valenceConnect.init(options) ⇒ InitPromise

Initialize valence connect for communication with Valence for IBM i or Valence Universal. By default, valenceConnect.init will look for a valence.json configuration file at the root of the project for the required properties. You may override those properties by passing in an options object.

Kind: instance method of ValenceConnect

ParamTypeDescription
optionsobjectConfiguration Options
options.urlstringValence Connect Web Service URL "Located in Valence Portal Admin/Web Services"
options.IBMibooleanRunning Valence for IBM i. Pass false if connecting to Valence Universal on Windows, Linux or OS X. Defaults to true if not passed.
options.loggingbooleanWhen true will capture statistical information which can be viewed in Portal Admin-->Logs.

Example

// Using valence.json
//
valenceConnect.init();

Example

// Passing options
//
valenceConnect.init({
    url     : 'http://acme.com:7052/service/connect?key=AZE678F68804D0123112TD0B8D93C1E38',
    IBMi    : true,
    logging : false,
});

valenceConnect.dbQuery(req, res, statement) ⇒ DbQueryPromise

Run an SQL SELECT statement and get the results.

Kind: instance method of ValenceConnect
Returns: DbQueryPromise - when fulfilled will contain an object with the results.

ParamTypeDescription
reqIncomingMessage | objecthttp request or object containing parameters to send off to process the query. Parameters: rootName, maxResults, startFrom.
resServerResponsehttp response
statementstringSQL statement to run. Only SELECT statements are allowed

Example

router.all('/customers', (req, res) => {
    let statement     = 'select cusno as NUMBER, cname as NAME,' +
        ' ccity as CITY, cstate as STATE from DEMOCMAST',
        queryResponse = (response) => {
            res.json(response);
        },
        queryError    = (err) => {
            res.json(err);
        };

    valenceConnect.dbQuery(req, res, statement)
        .then(queryResponse)
        .catch(queryError);
});

valenceConnect.decodeUTF16(inStr) ⇒ string

Decode UTF16 hex-encoded strings

Kind: instance method of ValenceConnect
Returns: string - decoded string

ParamTypeDescription
inStrstringstring to decode

Example

let decodedValue = valenceConnect.decodeUTF16(encodedValue);

valenceConnect.getParams(req, param) ⇒ Object | string | number | date | array | boolean | *

Get a single request parameter or all request parameters from both the body and query string.

Kind: instance method of ValenceConnect

ParamTypeDescription
reqIncomingMessagehttp request
paramstringparameter id

Example

// All Parameters
// The variable params would be an object containing all the query string
//   and body parameters combined.
//
router.all('/processInventory', (req, res) => {
    let params = valenceConnect.getParams(req);

    if (params.inventoryId) {
      // process inventory
      //
    }
});

Example

// Single Parameter
// The inventoryId variable would be a number since the front-end passed a numeric
//   value.
//
router.all('/processInventory', (req, res) => {
    let inventoryId = valenceConnect.getParams(req, 'inventoryId');

    if (inventoryId) {
      // process inventory
      //
    }
});

valenceConnect.getSessionInformation(sid) ⇒ SessionInformationPromise

Get the session information from the passed in session id

Kind: instance method of ValenceConnect
Returns: SessionInformationPromise - when fulfilled will contain the session information. Environment Id, Mode, Session Variables, etc.

ParamTypeDescription
sidstringsession id

Example

router.all('/transferOrder', (req, res) => {
    let sessionId       = valenceConnect.getParams(req, 'sid'),
        sessionError    = (err) => {
            res.json(err);
        },
        sessionResponse = (info) => {
            if (info.envId === 1) {
                // process default
                //
            } else {
                //process other environment
                //
            }
        };

    valenceConnect.getSessionInformation(sessionId)
        .then(sessionResponse)
        .catch(sessionError);
});

valenceConnect.getSettings(sid, names, cacheBuster) ⇒ SettingsPromise

Get Valence Settings

Kind: instance method of ValenceConnect
Returns: SettingsPromise - when fulfilled will be a name/value array of Valence settings

ParamTypeDescription
sidstringsession id
namesarrayoptional array of setting names to get
cacheBusterbooleanIf true force pull of latest settings from Valence.

Example

router.all('/settings', (req, res) => {
    let sessionId        = valenceConnect.getParams(req, 'sid'),
        settingsError    = (err) => {
            res.json(err);
        },
        settingsResponse = (settings) => {
            res.json({
                settings : settings
            });
        };

    valenceConnect.getSettings(sessionId)
        .then(settingsResponse)
        .catch(settingsError);
});

valenceConnect.getUserInformation(sid, cacheBuster) ⇒ UserInformationPromise

Get the current user information from the passed in session id

Kind: instance method of ValenceConnect
Returns: UserInformationPromise - when fulfilled will contain the user information. Id, First, Last Name, Email, etc.

ParamTypeDescription
sidstringsession id
cacheBusterbooleanIf true force pull of latest users information from Valence.

Example

router.all('/userInformation', (req, res) => {
    let sessionId    = valenceConnect.getParams(req, 'sid'),
        userError    = (err) => {
            res.json(err);
        },
        userResponse = (info) => {
            res.json({
                user : info
            });
        };

    valenceConnect.getUserInformation(sessionId)
        .then(userResponse)
        .catch(userError);
});

valenceConnect.isAuthenticated(req, res) ⇒ IsAuthenticatedPromise

Is the session authenticated based off the current session id on the request object.

Kind: instance method of ValenceConnect

ParamTypeDescription
reqIncomingMessagehttp request
resServerResponsehttp response

Example

valenceConnect.isAuthenticated(req, res)
    .then(() => {
        // authenticated so continue...
        //
        next();
    });

valenceConnect.isEmpty(value) ⇒ boolean

Check to see if a value is empty

Kind: instance method of ValenceConnect

ParamTypeDescription
value* | stringvalue to test if empty

Example

if (valenceConnect.isEmpty(value)) {
    //value is empty
    //
} else {
    //value is not empty
    //
}

getSessionStorage(key) ⇒ Promise.<*>

get session storage

Kind: global function

ParamType
keystring

setSessionStorage(key, info) ⇒ Promise.<void>

set the session storage

Kind: global function

ParamType
keystring
infostring

Back To Top

Community

Forums

Versions

Prior to 1.1.1

  • beta

1.1.1 - 2018-05-18

  • General Availability

1.1.2 - 2018-09-12

  • When calling getParams with a specific parameter value return null if not found instead of an empty object.

1.1.3 - 2018-12-27

  • Update the required package url-parse minimum version to 1.4.3.

1.1.4 - 2020-12-21

  • Update package dependencies to the latest ver
  • Update core to handle dependency changes
1.1.4

3 years ago

1.1.3

5 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.73

6 years ago

1.0.72

6 years ago

1.0.71

6 years ago

1.0.70

6 years ago

1.0.69

6 years ago

1.0.68

6 years ago

1.0.67

6 years ago

1.0.66

6 years ago

1.0.65

6 years ago

1.0.64

6 years ago

1.0.63

6 years ago

1.0.62

6 years ago

1.0.61

6 years ago

1.0.60

6 years ago

1.0.59

6 years ago

1.0.58

6 years ago

1.0.57

6 years ago

1.0.56

6 years ago

1.0.55

6 years ago

1.0.54

6 years ago

1.0.53

6 years ago

1.0.52

6 years ago

1.0.51

6 years ago

1.0.50

6 years ago

1.0.49

6 years ago

1.0.48

6 years ago

1.0.47

6 years ago

1.0.46

6 years ago

1.0.45

6 years ago

1.0.44

6 years ago

1.0.43

6 years ago

1.0.42

6 years ago

1.0.41

6 years ago

1.0.40

6 years ago

1.0.39

6 years ago

1.0.38

6 years ago

1.0.37

6 years ago

1.0.36

6 years ago

1.0.35

6 years ago

1.0.34

6 years ago

1.0.33

6 years ago

1.0.32

6 years ago

1.0.31

6 years ago

1.0.30

6 years ago

1.0.29

6 years ago

1.0.28

6 years ago

1.0.27

6 years ago

1.0.26

6 years ago

1.0.25

6 years ago

1.0.24

6 years ago

1.0.23

6 years ago

1.0.22

6 years ago

1.0.21

6 years ago

1.0.20

6 years ago

1.0.19

6 years ago

1.0.18

6 years ago

1.0.17

6 years ago

1.0.16

6 years ago

1.0.15

6 years ago

1.0.14

6 years ago

1.0.13

6 years ago

1.0.12

6 years ago

1.0.11

6 years ago

1.0.10

6 years ago

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.0.38

6 years ago

0.0.37

6 years ago

0.0.36

6 years ago

0.0.35

6 years ago

0.0.34

6 years ago

0.0.33

6 years ago

0.0.32

6 years ago

0.0.31

6 years ago

0.0.30

6 years ago

0.0.29

6 years ago

0.0.28

6 years ago

0.0.27

6 years ago

0.0.26

6 years ago

0.0.25

6 years ago

0.0.24

6 years ago

0.0.23

6 years ago

0.0.22

6 years ago

0.0.21

6 years ago

0.0.20

6 years ago

0.0.19

6 years ago

0.0.18

6 years ago

0.0.17

6 years ago

0.0.16

6 years ago

0.0.15

6 years ago

0.0.14

6 years ago

0.0.13

6 years ago

0.0.12

6 years ago

0.0.11

6 years ago

0.0.10

6 years ago

0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago