Validating a command in Vorpal.js - javascript

When using the Vorpal.js code library, if I have created a command that looks like:
command-name [strategy]
and I have set the[strategy] command to accept only the values"insert", "update", and "upsert", how do I validate my code within the Vorpal.js framework? I'm guessing I would need to use some sort of validation function to parse the index and log an error message to the console if the index entry is not found. Or I could parse the index for each of the three strings instead. This would require marginally more code but I wonder, which is the most efficient way? Or perhaps people could suggest an implementation that is quicker still? Any suggestions of alternative methodologies would be great.
I am using the current build found at:
Vorpal.js code repository, Github

Vorpal doesn't have any custom validation method, so you can just manually validate it without too much trouble. Something like this would work:
const valids = ['insert', 'update', 'upsert'];
if (valids.indexOf(args.strategy) === -1) {
this.log('Please enter a valid strategy');
cb();
return;
}
Update
Adding a validation method is now on the roadmap for Vorpal.

Related

Avoid commander parser complaining when no arguments are present and just show helpInfo

I'm migrating a package from a much older version of commander (v2.20.3)
program.command(`install [pkg]`)
.alias(`i`)
.action(installPackageOrLocal)
.option(`-S, --save`, `Save to dependencies`)
.option(`-D, --save-dev`, `Save to devDependencies`)
.option(`--production`, `Will not install modules listed in devDependencies`)
.option(`--test`, `Exit with code 1 if package limits like maxPackagesNumber or maxSizeBites exceeded`);
I'd like for the default (when calling the CLI with no arguments at all) to continue being the display of the help and no erring out, but currently it errs with:
.../npm-reflect/node_modules/.pnpm/commander#8.3.0/node_modules/commander/lib/command.js:142
const [, name, args] = nameAndArgs.match(/([^ ]+) (.)/);
I was able to get the mostly desired behavior by adding:
program.command('help', {isDefault: true})
.action(() => {
program.help();
})
.command(`install [pkg]`)
// ...
...but this seems to be polluting things in the help by listing a new "help" command. How can I avoid the parser complaining when no arguments are present yet without adding a new command?
The default behaviour in latest Commander is to display the help if you have subcommands and do not specify a subcommand. Which sounds like what you want! Not sure how you are getting an error, you might want to open a Commander issue for help.
In general, if you want some custom behaviour for no arguments then it may be simple and easy to check yourself before calling parse(). e.g.
if (process.argv.length < 3)
program.help(); // exits
program.parse(process.argv);

Validation without objects using Joi

good evening.
I'm having trouble while trying to validate a variable using Joi. I've read this page link
Joi usually validates object through schemas, however, the page I mentioned show that Joi also supports a more "direct" approach to validation. In my case, I'm trying just to validate a variable.
I'm trying the following:
const {error, value} = Joi.number().validate("SAMPLE TEXT");
It's not precisely what I'm trying to do (I'd change "SAMPLE TEXT" for a variable), but It's a good example to show my problem.
What I'd expect from this code is that an error is thrown (because validation should fail), meaning that ** error should not be null or undefined **, however, when trying:
console.log(`Error: ${error}`};
I get:
Error: undefined
Can anyone help me?
[]
Check your package is installed perfectly. I did not find any issue in your code. I have run it properly.
const Joi = require('#hapi/joi'); check this line also

How do you use an npm package with require & module export as a plain JS library

I'm not sure I'm even asking the right question here, sorry, but I think the two general ones are:
In what way do you need to modify a node.js package using require etc to be used as a plain embedded script/library in HTML?
How do you call a class constructor (?) in JS as a function to validate a form field?
I'm trying to use this small JS library NoSwearingPlease (which is an npm package) in an environment with no node or build system – so I'm just trying to call it like you would jQuery or something with a script & src in the HTML, and then utilise it with a small inline script.
I can see a couple of things are required to get this working:
the JSON file needs to be called in a different way (not using require etc)
the checker variable needs to be rewritten, again without require
I attempted using jQuery getJSON but I just don't understand the class & scope bits of the library enough to use it I think:
var noswearlist = $.getJSON( "./noswearing-swears.json" );
function() {
console.log( "got swear list from inline script" );
})
.fail(function() {
console.log( "failed to get swear list" );
})
noswearlist.done(function() {
console.log( "done callback as child of noswearlist variable" );
var checker = new NoSwearing(noswearlist);
console.log(checker);
});
Please halp. Thanks!
No need to modify, when outside of node the class is just appended to window (global):
fetch("https://cdn.jsdelivr.net/gh/ThreeLetters/NoSwearingPlease#master/swears.json").then(response => {
return response.json();
}).then(data => {
var noSwearing = new NoSwearing(data);
console.log(noSwearing.check("squarehead"));
});
<script src="https://cdn.jsdelivr.net/gh/ThreeLetters/NoSwearingPlease#master/index.js"></script>
In the future, you can answer this type of question on your own by looking through the source code and looking up things you don't understand. That being said, here's what I was able to gather doing that myself.
For your first question, if you have no build tools you can't use require, you have to hope your NPM package supports adding the class to the window or has a UMD export (which in this case, it does). If so, you can download the source code or use a CDN like JSDelivr and add a <script> tag to link it.
<script src="https://cdn.jsdelivr.net/gh/ThreeLetters/NoSwearingPlease#master/index.js"></script>
I'm having a hard time deciphering your script (it has a few syntax errors as far as I can tell), so here's what you do if you have a variable ns containing the JSON and the string str that you need to check:
var checker = new NoSwearing(ns);
checker.check(str);
As an aside, you should really use build tools to optimize your bundle size and make using packages a lot easier. And consider dropping jQuery for document.querySelector, fetch/XMLHttpRequest, and other modern JavaScript APIs.

Minify Javascript programmatically in-memory

I am building a nifty little "asset-pipeline" for a express.js application, but i have a problem with the compression-step for javascript files
scripts = (fs.readFileSync(file) for file in filelist)
result = scripts.join("\n\n") # concat
upto now, things are working as expected (the logic itself is written in coffeescript). The next step after merging the JS-files would be to minify them. But here is my problem: i want to do this "hot" when i start my express-app in production mode, from within a piece of connect-middleware i wrote.
I need a solution that can minify a given blob of javascript stuff, without writing the result to disk (!), in other words: a function that does the minification and returns the result directly as a result value. (No, no webservices either.) It should be usable like this:
minified_result = awesomeMinifyFunction( result )
The raw processing performance isn't that important for me, neither is the level of compression, i need just something that works this way without hassle.
Does anyone know a suitable solution? Thanks in advance!
I'd suggest you look at one of the JavaScript based minifiers, like UglifyJS2.
npm install uglify-js
It can be used within a Node.JS application programatically:
var UglifyJS = require("uglify-js");
// you could pass multiple files (rather than reading them as strings)
var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ]);
console.log(result.code);
Or you could
var result = scripts.join("\n\n"); # concat
result = UglifyJS.minify(result, {fromString: true});
console.log(result.code);
You can write your own function that removes all comments/spaces/blank lines etc.
You can use a regular expression that makes use of rJSmin like:
function awesomeMinifyFunction(result)
{
pattern = (
r'([^\047"/\000-\040]+)|((?:(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?'
r'\n|\r)[^\047\\\r\n]*)*\047)|(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|'
r'\r)[^"\\\r\n]*)*"))[^\047"/\000-\040]*)|(?<=[(,=:\[!&|?{};\r\n])(?'
r':[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*'
r'(?:(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:/\*'
r'[^*]*\*+(?:[^/*][^*]*\*+)*/))*)*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?:('
r'?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/\\\['
r'\r\n]*)*/)[^\047"/\000-\040]*)|(?<=[\000-#%-,./:-#\[-^`{-~-]return'
r')(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/'
r'))*(?:(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:'
r'/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?'
r':(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/'
r'\\\[\r\n]*)*/)[^\047"/\000-\040]*)|(?<=[^\000-!#%&(*,./:-#\[\\^`{|'
r'~])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)'
r'*/))*(?:((?:(?://[^\r\n]*)?[\r\n]))(?:[\000-\011\013\014\016-\040]'
r'|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*)+(?=[^\000-\040"#%-\047)*,./'
r':-#\\-^`|-~])|(?<=[^\000-#%-,./:-#\[-^`{-~-])((?:[\000-\011\013\01'
r'4\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=[^\000-#%-,./:'
r'-#\[-^`{-~-])|(?<=\+)((?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*'
r'\*+(?:[^/*][^*]*\*+)*/)))+(?=\+)|(?<=-)((?:[\000-\011\013\014\016-'
r'\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=-)|(?:[\000-\011\013'
r'\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))+|(?:(?:(?://[^'
r'\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^'
r'/*][^*]*\*+)*/))*)+'
)
return result.match(pattern);
}
I'd recommend taking a look at Asset Rack, which already implements what you're building.

How to display inputs in Jamsine SpecRunner?

I started using Jasmine to test javascript code and its working fine. But I would like to display inputs to the test suite in specrunner.html.
I tried HtmlReporter() and TrivialReporter() but no luck.
SPEC CODE:
checkAddition("TEST_SUITE","Test INPUTS1",getResult(2,3),5);
checkAddition("TEST_SUITE","Test INPUTS2",getResult(3,8),11);
function checkAddition(suite_name,testcase,result,equalto){
describe(suite_name, function() {
it(testcase, function() {
expect(result).toEqual(equalto);
});
});
}
JavaScript CODE:
function getResult(input1,input2){
return input1+input2;
}
OUTPUT :
EXPECTED OUTPUT :
I need to display inputs that looks like expected output (I edited code in browser using firebug to share expected output).
Please help me. Help would be appreciated :)
The built reporters won't do this. You either need to need to hack the innards of those built in reporters to do this (you're on your own with this route), or create your own reports from scratch (see here for some examples).
But I find this to be a strange request. Perhaps there is a cleaner way to achieve your goal, whatever that may be. Maybe a test suite isn't what you want if you want this info.

Categories