Skip to content

Commit

Permalink
Merge pull request #1 from danopia/merge-upstream
Browse files Browse the repository at this point in the history
Merge upstream
  • Loading branch information
danopia authored Nov 6, 2020
2 parents 85ee509 + fa52f10 commit 01e2bfe
Show file tree
Hide file tree
Showing 9 changed files with 2,207 additions and 1,753 deletions.
85 changes: 59 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,32 +103,6 @@ search(JSON_DOCUMENT, "foo[?age > `30`]");
// OUTPUTS: [ { age: 35 }, { age: 40 } ]
```


### `registerFunction(functionName: string, customFunction: RuntimeFunction, signature: InputSignature[]): void`

Extend the list of built in JMESpath expressions with your own functions.

```javascript
import {search, registerFunction, TYPE_NUMBER} from '@metrichor/jmespath'


search({ foo: 60, bar: 10 }, 'divide(foo, bar)')
// THROWS ERROR: Error: Unknown function: divide()

registerFunction(
'divide', // FUNCTION NAME
(resolvedArgs) => { // CUSTOM FUNCTION
const [dividend, divisor] = resolvedArgs;
return dividend / divisor;
},
[{ types: [TYPE_NUMBER] }, { types: [TYPE_NUMBER] }] //SIGNATURE
);

search({ foo: 60,bar: 10 }, 'divide(foo, bar)');
// OUTPUTS: 6

```

### `compile(expression: string): ASTNode`

You can precompile all your expressions ready for use later on. the `compile`
Expand All @@ -145,6 +119,65 @@ TreeInterpreter.search(ast, {foo: {bar: 'BAZ'}})

```

---
## EXTENSIONS TO ORIGINAL SPEC

1. ### Register you own custom functions

#### `registerFunction(functionName: string, customFunction: RuntimeFunction, signature: InputSignature[]): void`

Extend the list of built in JMESpath expressions with your own functions.

```javascript
import {search, registerFunction, TYPE_NUMBER} from '@metrichor/jmespath'


search({ foo: 60, bar: 10 }, 'divide(foo, bar)')
// THROWS ERROR: Error: Unknown function: divide()

registerFunction(
'divide', // FUNCTION NAME
(resolvedArgs) => { // CUSTOM FUNCTION
const [dividend, divisor] = resolvedArgs;
return dividend / divisor;
},
[{ types: [TYPE_NUMBER] }, { types: [TYPE_NUMBER] }] //SIGNATURE
);

search({ foo: 60,bar: 10 }, 'divide(foo, bar)');
// OUTPUTS: 6

```

Optional arguments are supported by setting `{..., optional: true}` in argument signatures


```javascript
registerFunction(
'divide',
(resolvedArgs) => {
const [dividend, divisor] = resolvedArgs;
return dividend / divisor ?? 1; //OPTIONAL DIVISOR THAT DEFAULTS TO 1
},
[{ types: [TYPE_NUMBER] }, { types: [TYPE_NUMBER], optional: true }] //SIGNATURE
);
search({ foo: 60, bar: 10 }, 'divide(foo)');
// OUTPUTS: 60
```

2. ### Root value access with `$` symbol

```javascript
search({foo: {bar: 999}, baz: [1, 2, 3]}, '$.baz[*].[@, $.foo.bar]')
// OUTPUTS:
// [ [ 1, 999 ], [ 2, 999 ], [ 3, 999 ] ]
```


## More Resources

Expand Down
Loading

0 comments on commit 01e2bfe

Please sign in to comment.