Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse default parameters from function signature #80

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,19 @@ Example: passing thrown string errors to the client while masking javascript err

You can provide a function called `$logError` in the `$global` object to record any true javascript errors (with `.stack`) when they occur. The `$logError` function will be called with the error object as first argument and `fullref` as the second argument. For proper logging it is important to capture the error at source, as the dependencies might be optional - in which case the error never reaches the original request.

You can also specify a default value for an argument if it is either missing or an error/rejection using [default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) in the function signature:

```js.
var obj = {
a: () => 1,
b: () => Promise.reject('Problem'),
result: (a = 100, b = 21, missing = 2) => a * b * missing
};

clues(obj,'result').then(console.log); // console logs 42 (1 * 21 * 2)
```


### making arguments optional with the underscore prefix
If any argument to a function resolves as a rejected promise (i.e. errored) then the function will not run and will also be rejected. But sometimes we want to continue nevertheless (example: user input that is optional). Any argument to any function can be made optional by prefixing the argument name with an underscore. If the resolution of the optional argument returns a rejected promise (or the optional argument does not exist), then the value of this argument to the function will simply be `undefined`.

Expand Down
32 changes: 23 additions & 9 deletions clues.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,29 @@

function matchArgs(fn) {
if (!fn.__args__) {
let def,m;
var match = fn.prototype && fn.prototype.constructor.toString() || fn.toString();
match = match.replace(/^\s*async/,'');
match = reArgs.exec(match) || reEs6.exec(match) || reEs6Class.exec(match);
fn.__args__ = !match ? [] : match[1].replace(/\s/g,'')
.split(',')
.filter(function(d) {
.map(function(d) {
if (d === '$private')
fn.private = true;
if (d === '$prep')
fn.prep = true;
return d.length;
});

m = /(.*)\s*=\s*(.*)/.exec(d);

if (m) {
def = def || {};
def[m[1]] = m[2];
d = m[1];
}
return d;
})
.filter(d => d.length);
fn.__args__.def = def;
}
return fn.__args__;
}
Expand Down Expand Up @@ -116,7 +127,7 @@
}

function _rawClues(logic,fn,$global,caller,fullref) {
var args,ref;
var args,ref,match;

if (!$global) $global = {};

Expand Down Expand Up @@ -183,15 +194,17 @@
}
args = fn.slice(0,fn.length-1);
fn = fn[fn.length-1];
var fnArgs = matchArgs(fn);
var numExtraArgs = fnArgs.length-args.length;
match = matchArgs(fn);
var numExtraArgs = match.length-args.length;
if (numExtraArgs) {
args = args.concat(fnArgs.slice(numExtraArgs));
args = args.concat(match.slice(numExtraArgs));
}
}

if (typeof fn === 'function')
args = (args || matchArgs(fn));
if (typeof fn === 'function') {
match = matchArgs(fn);
args = args || match;
}

// If fn name is private or promise private is true, reject when called directly
if (fn && (!caller || caller == '__user__') && ((typeof(fn) === 'function' && (fn.private || fn.name == '$private' || fn.name == 'private')) || (fn.then && fn.private)))
Expand Down Expand Up @@ -235,6 +248,7 @@
}

let processError = e => {
if (match && match.def && match.def[arg] !== undefined) return match.def[arg];
if (optional) return (showError) ? e : undefined;
let rejection = reject(e);
if (!errorArgs) errorArgs = rejection;
Expand Down
17 changes: 17 additions & 0 deletions test/default-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const clues = require('../clues');
const t = require('tap');

const Logic = {
a: () => 5,
optA: (a = 42) => a,
optMissing: (b = 42) => b,
optError: (err = 42) => err,
err: clues.reject('ERROR')
};

t.test('default arguments in function',{autoend: true}, async t => {
const facts = Object.create(Logic);
t.same(await clues(facts,'optA'),5,'resolve without default if value exists');
t.same(await clues(facts,'optMissing'),42,'resolves to default if value missing');
t.same(await clues(facts,'optError'),42,'resolves to default if value missing');
});