Skip to content

Commit

Permalink
feat(jsonld): Add method to find node in document
Browse files Browse the repository at this point in the history
The DID public key information may be embedded in the DID document,
so add the "findNodeById()" function to find the node in the
document.

See also: https://w3c-ccg.github.io/did-spec/#public-keys
  • Loading branch information
ender503 committed Jun 20, 2019
1 parent a844c34 commit 8434b71
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/jsonld/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ yarn add @tangleid/jsonld

* [~frame(input, frame, [options])](#module_jsonld..frame)

* [~findNodeById(document, id)](#module_jsonld..findNodeById)

* [~generateRsaKeyPair([options])](#module_jsonld..generateRsaKeyPair)

* [~signRsaSignature(document, publicKey, privateKeyPem, [options])](#module_jsonld..signRsaSignature)
Expand Down Expand Up @@ -148,6 +150,18 @@ Performs JSON-LD flattening.
Performs JSON-LD framing.

**Returns**: <code>Promise.&lt;object&gt;</code> - Promise that resolves to the framed output.
<a name="module_jsonld..findNodeById"></a>

### *jsonld*~findNodeById(document, id)

| Param | Type | Description |
| --- | --- | --- |
| document | <code>object</code> | the JSON-LD document to find. |
| id | <code>string</code> | String that specifies the ID value. |

Returns the first node with the specified value of the ID attribute.

**Returns**: <code>Promise.&lt;(object\|null)&gt;</code> - Promise that resolves to the node.
<a name="module_jsonld..generateRsaKeyPair"></a>

### *jsonld*~generateRsaKeyPair([options])
Expand Down
26 changes: 26 additions & 0 deletions packages/jsonld/src/jsonld.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,29 @@ export const frame = async (input: object, frame: object, options: object = {}):
// @ts-ignore
return jsonld.frame(input, frame, options);
};

/**
* Returns the first node with the specified value of the ID attribute.
* @function findNodeById
* @param {object} document - the JSON-LD document to find.
* @param {string} id - String that specifies the ID value.
* @return {Promise<object|null>} Promise that resolves to the node.
*/
export const findNodeById = async (document: object, id: string): Promise<object | null> => {
const flattened: { [index: string]: any } = await flatten(document, {});

if (!flattened.hasOwnProperty('@graph')) {
throw new Error('@graph property does not exist in the flattened document');
}

const graph = flattened['@graph'] as Array<{ [index: string]: any }>;
const node = graph.find(element => {
return element['@id'] === id;
});

if (node === undefined) {
return null;
}

return node;
};

0 comments on commit 8434b71

Please sign in to comment.