[d24f17c] | 1 | import { isInteger } from 'ramda-adjunct';
|
---|
| 2 | import { isObjectElement, isArrayElement, cloneDeep } from '@swagger-api/apidom-core';
|
---|
| 3 | import parse from "./parse.mjs";
|
---|
| 4 | import EvaluationJsonPointerError from "./errors/EvaluationJsonPointerError.mjs"; // evaluates JSON Pointer against ApiDOM fragment
|
---|
| 5 | const evaluate = (pointer, element) => {
|
---|
| 6 | let tokens;
|
---|
| 7 | try {
|
---|
| 8 | tokens = parse(pointer);
|
---|
| 9 | } catch (error) {
|
---|
| 10 | throw new EvaluationJsonPointerError(`JSON Pointer evaluation failed while parsing the pointer "${pointer}".`, {
|
---|
| 11 | pointer,
|
---|
| 12 | element: cloneDeep(element),
|
---|
| 13 | cause: error
|
---|
| 14 | });
|
---|
| 15 | }
|
---|
| 16 | return tokens.reduce((acc, token, tokenPosition) => {
|
---|
| 17 | if (isObjectElement(acc)) {
|
---|
| 18 | // @ts-ignore
|
---|
| 19 | if (!acc.hasKey(token)) {
|
---|
| 20 | throw new EvaluationJsonPointerError(`JSON Pointer evaluation failed while evaluating token "${token}" against an ObjectElement`, {
|
---|
| 21 | pointer,
|
---|
| 22 | tokens,
|
---|
| 23 | failedToken: token,
|
---|
| 24 | failedTokenPosition: tokenPosition,
|
---|
| 25 | element: cloneDeep(acc)
|
---|
| 26 | });
|
---|
| 27 | }
|
---|
| 28 | // @ts-ignore
|
---|
| 29 | return acc.get(token);
|
---|
| 30 | }
|
---|
| 31 | if (isArrayElement(acc)) {
|
---|
| 32 | if (!(token in acc.content) || !isInteger(Number(token))) {
|
---|
| 33 | throw new EvaluationJsonPointerError(`JSON Pointer evaluation failed while evaluating token "${token}" against an ArrayElement`, {
|
---|
| 34 | pointer,
|
---|
| 35 | tokens,
|
---|
| 36 | failedToken: token,
|
---|
| 37 | failedTokenPosition: tokenPosition,
|
---|
| 38 | element: cloneDeep(acc)
|
---|
| 39 | });
|
---|
| 40 | }
|
---|
| 41 | // @ts-ignore
|
---|
| 42 | return acc.get(Number(token));
|
---|
| 43 | }
|
---|
| 44 | throw new EvaluationJsonPointerError(`JSON Pointer evaluation failed while evaluating token "${token}" against an unexpected Element`, {
|
---|
| 45 | pointer,
|
---|
| 46 | tokens,
|
---|
| 47 | failedToken: token,
|
---|
| 48 | failedTokenPosition: tokenPosition,
|
---|
| 49 | element: cloneDeep(acc)
|
---|
| 50 | });
|
---|
| 51 | }, element);
|
---|
| 52 | };
|
---|
| 53 | export default evaluate; |
---|