script-handler
Run a custom JS function inside vm
, providing a flexible way to validate complex
input. Simple to use and does only one thing, so no bells and whistles, which might be just what you need.
Install
npm i script-handler
Usage
script-handler
allows you to define a function within a vm
, which can then be
used to validate complex input.
A script can come from any source (security is outside the scope of this module) and is compiled only once, saving precious time.
The script
defines a global variable process
, which should be a function
.
process
can then be called with arbitrary data by using compiled.process()
(see example below).
A simple annotated example should suffice:
const ScriptHandler = require('script-handler')
// Our script defines a `process` variable which is the function
// that will be called later.
const script = `process = function (row) {
return row.type === 'credit' && row.code === 'ba'
}`
// We only have to compile the script once, saving clock cycles
const compiled = new ScriptHandler(script)
// In order for the script to set the `process` variable, we have to run it
// When the script has finished running, the global variable `process`
// should be a function (typeof process === 'function')
compiled.run().then(() => {
// Now our process handler is set
console.log('Script successfully ran')
// Some data to validate.
// vm.process() only supports one argument at the moment
const row = {
type: 'credit',
code: 'ba'
}
// Execute the process handler with the `row` data
// In this case, `valid` will be true
const valid = vm.process(row)
console.log(`Row valid: ${valid}`)
}).catch(err => {
console.log(err)
})
To Do
- Allow any arbitrary amount of arguments to be passed to
process
- Try to find a way to make calling
vm.process()
asynchronous - Update example to show how to make use of
options
andsandbox
Changelog
-
v0.0.1 (31-03-2017)
- First published
License
Copyright 2017 Michiel van der Velde.
This software is licensed under the MIT License.