valence-connect
v1.1.4
Published
Connect to Valence for requests coming from applications running in the Valence Portal
Downloads
65
Maintainers
Readme
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
}
| Property | Type | Description |
| --- | --- | --- |
| url | string | Valence Connect Web Service URL "Located in Valence Portal Admin/Web Services" |
| IBMi | boolean | Running Valence for IBM i. Pass false if connecting to Valence Universal on Windows, Linux or OS X. Defaults to true if not passed. |
| logging | boolean | When true
will capture statistical information which can be viewed in Portal Admin-->Logs. |
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
- ValenceConnect
- new ValenceConnect()
- .baseInit() ⇒ Promise.<void>
- .init([options]) ⇒ InitPromise
- .dbQuery(req, [res], statement) ⇒ DbQueryPromise
- .decodeUTF16(inStr) ⇒ string
- .getParams(req, [param]) ⇒ Object | string | number | date | array | boolean | *
- .getSessionInformation(sid) ⇒ SessionInformationPromise
- .getSettings(sid, [names], [cacheBuster]) ⇒ SettingsPromise
- .getUserInformation(sid, [cacheBuster]) ⇒ UserInformationPromise
- .isAuthenticated(req, res) ⇒ IsAuthenticatedPromise
- .isEmpty(value) ⇒ boolean
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
| Param | Type | Description |
| --- | --- | --- |
| [options] | object | Configuration Options |
| options.url | string | Valence Connect Web Service URL "Located in Valence Portal Admin/Web Services" |
| options.IBMi | boolean | Running Valence for IBM i. Pass false if connecting to Valence Universal on Windows, Linux or OS X. Defaults to true if not passed. |
| options.logging | boolean | When 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.
| Param | Type | Description |
| --- | --- | --- |
| req | IncomingMessage | object | http request or object containing parameters to send off to process the query. Parameters: rootName
, maxResults
, startFrom
. |
| [res] | ServerResponse | http response |
| statement | string | SQL 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
| Param | Type | Description | | --- | --- | --- | | inStr | string | string 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
| Param | Type | Description | | --- | --- | --- | | req | IncomingMessage | http request | | [param] | string | parameter 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.
| Param | Type | Description | | --- | --- | --- | | sid | string | session 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
| Param | Type | Description |
| --- | --- | --- |
| sid | string | session id |
| [names] | array | optional array of setting names to get |
| [cacheBuster] | boolean | If 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.
| Param | Type | Description |
| --- | --- | --- |
| sid | string | session id |
| [cacheBuster] | boolean | If 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
| Param | Type | Description | | --- | --- | --- | | req | IncomingMessage | http request | | res | ServerResponse | http 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
| Param | Type | Description | | --- | --- | --- | | value | * | string | value 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
| Param | Type | | --- | --- | | key | string |
setSessionStorage(key, info) ⇒ Promise.<void>
set the session storage
Kind: global function
| Param | Type | | --- | --- | | key | string | | info | string |
Community
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