0.1.26 • Published 4 months ago

open-hubagent v0.1.26

Weekly downloads
-
License
Apache-2.0
Repository
bitbucket
Last release
4 months ago

Open HubAgent

The Open HubAgent npm package is used for exchanging Knowledge Objects with EvidenceHub using the v2 Generic KO format.

Getting started

Installing the Open HubAgent in Your Node.js Project

To install the open-hubagent package in your Node.js project, you need to run the following command in the terminal. Make sure you're in the root directory of your Node.js project before running this command:

npm install open-hubagent

Request an API Key

Please email support@evidentli.com to request an API key.

Setting Up Environment Variables

For your npm project, you'll need to create a .env file to store your environment variables. This file should be located at the root of your project directory. Here's how you can create it:

  1. Navigate to the root directory of your project.
  2. Create a new file and name it .env.

Sample '.env' content

EVIDENCEHUB_API_URL=https://hub.evidentli.com/api #required
EVIDENCEHUB_API_KEY=<email request for api key> #required
HUBAGENT_PORT=3111 #optional. defaults to 6111.
HTTP_PROXY=http://localhost:6161 #optional. defaults to no proxy

Modify EVIDENCEHUB_API_KEY with a valid EvidenceHub Api key.

Quick start template

The following code snippets uses the Generic KO Format that is described in the section v2 Generic KO format sample.

A repository of templates can be found on this link: TBD

Using open-hubagent as a Rest Server

The following code will start a basic open-hubagent rest server with a custom route.

import app, { config, logger } from 'open-hubagent'

const server = app({
    logger
})

// add custom route at /custom
server.register(async (api, opts, done) => {
    api.get('/custom', async (request, reply) => {
        const checkHealth = await api.inject({
            method: 'GET',
            url: '/'
        })
        /* e.g. perform pre/post-processing on knowledge object (ko)
            const myobject = await api.inject({
                method: 'GET',
                url: '/api/v2/knowledge/cln17xg7h0003sk03b6twuu0p',
            })
            console.log(myobject)
            interop with other services
        */
        return { response: checkHealth.json() }
    })
    done()
})

const start = async () => {
    try {
        await server.listen({
            port: config.get('server.port'),
            host: '0.0.0.0'
        })
        const msg = `Server started listening on port ${config.get('server.port')}`
        logger.info(msg)
    } catch (error) {
        logger.error(error)
        process.exit(1)
    }
}
start()

The rest server is ready to receive REST requests as detailed in the section Available endpoints -V2 Generic KOs.

You can use the curl examples to send objects to your rest server and observe the response from EvidenceHub.

Calling open-hubagent methods directly

import { agent } from "open-hubagent";

const myFirstObject = {
    payload: {
        data: "test data for Generic KO.",
    },
    environment: {
        type: "application/vnd.acme.app.analytic",
    },
    description: {
        html: "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>",
    },
    metadata: {
        about:
            "Short text to be displayed in the abstract of KO Page. This is optional",
        owner: {
            name: "John Smith",
            email: "john.smith@example.com",
        },
        name: "Generic KO mandatory fields with description",
    },
};


async function main() {
    try {
        const result = await agent.sendKnowledgeToHub(myFirstObject);
        console.log(result)
    } catch (error) {
        if (error instanceof Error) {
            if ('code' in error && error.code === 'ECONNREFUSED') {
                console.error('Failed to connect to the server. Please check if the server is running and accessible.');
            } else {
                console.error(error.message);
            }
        }
    }
}

main();

v2 Generic KO format sample

{
    "payload": {
        "data": "test data for Generic KO."
    },
    "environment": {
        "type": "application/vnd.acme.app.analytic"
    },
    "description": {
        "html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>"
    },
    "metadata": {
        "about": "Short text to be displayed in the abstract of KO Page. This is optional",
        "owner": {
            "name": "John Smith",
            "email": "john.smith@example.com"
        },
        "name": "Generic KO mandatory fields with description"
    }
}

The agent methods available can be found in the section Available agent methods.

Available endpoints - V2 Generic KOs

POST <hostname:port>/api/v2/knowledge

This is the endpoint for adding a new knowledge object.

Example JSON body

{
    "payload": {
        "data": "test data for Generic KO"
    },
    "environment": {
        "type": "application/vnd.acme.app.analytic"
    },
    "description": {
        "html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>"
    },
    "metadata": {
        "owner": {
            "name": "John Smith",
            "email": "john.smith@example.com"
        },
        "name": "Generic KO mandatory fields with description",
        "about": "Short text to be displayed in the abstract of KO Page. This is optional"
    }
}

Example curl command

curl -X POST -H "Content-Type: application/json" -d '{
    "payload": {
        "data": "test data for Generic KO"
    },
    "environment": {
        "type": "application/vnd.acme.app.analytic"
    },
    "description": {
        "html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>"
    },
    "metadata": {
        "owner": {
            "name": "John Smith",
            "email": "john.smith@example.com"
        },
        "name": "Generic KO mandatory fields with description",
        "about": "Short text to be displayed in the abstract of KO Page. This is optional"
    }
}' http://localhost:3111/api/v2/knowledge

Example JSON Response

{
    "id": "clmzsbakr0003sko1gmf13z74",
    "ko": {
        "id": "clmzsbakq0002sko1vnevlt6i",
        "name": "Generic KO mandatory fields with description",
        "ownerId": "clmzsbaki0001sko1dasym0p7",
        "latestVersionId": "clmzsbakr0003sko1gmf13z74",
        "latestPublishedVersionId": "clmzsbakr0003sko1gmf13z74",
        "banned": false,
        "type": "application/vnd.acme.app.analytic"
    },
    "owner": {
        "id": "clmzsbaki0001sko1dasym0p7",
        "name": "John Smith",
        "email": "john.smith@example.com",
        "emailHash": "b17827239fa3b1d4eb667590c4c0e3d3",
        "role": "USER",
        "username": "johnsmith349",
        "isOrg": false
    }
}

GET <hostname:port>/api/v2/knowledge

This is the endpoint for checking if a knowledge object exists based on specified query parameters: name, type and email.

Example curl command

curl -X GET "http://localhost:3111/api/v2/knowledge?name=Generic%20KO%20mandatory%20fields%20with%20description&type=application%2Fvnd.acme.app.analytic&email=john.smith%40example.com"

Example response with status code 200

{
  "message": "Knowledge found."
}

Example response with status code 404

{
  "message": "Knowledge not found."
}

PUT <hostname:port>/api/v2/knowledge/:id

This is the endpoint for editing an existing knowledge object. The version id (:id) must target the latest id to succeed.

Example JSON body

{
    "payload": {
        "data": "test data for Generic KO. Changed Data."
    },
    "environment": {
        "type": "application/vnd.acme.app.analytic"
    },
    "description": {
        "html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>. Or Changed Description"
    },
    "metadata": {
        "owner": {
            "name": "John Smith",
            "email": "john.smith@example.com"
        },
        "name": "Generic KO mandatory fields with description",
        "about": "Short text to be displayed in the abstract of KO Page. This is optional"
    }
}

Example curl command

curl -X PUT \
     -H "Content-Type: application/json" -d '{
        "payload": {
            "data": "test data for Generic KO. Changed Data."
        },
        "environment": {
            "type": "application/vnd.acme.app.analytic"
        },
        "description": {
            "html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>. Or Changed Description"
        },
        "metadata": {
            "owner": {
                "name": "John Smith",
                "email": "john.smith@example.com"
            },
            "name": "Generic KO mandatory fields with description",
            "about": "Short text to be displayed in the abstract of KO Page. This is optional"
        }
    }' \
    http://localhost:3111/api/v2/knowledge/cln13uepr0003skt5fyi5vdmk

Example JSON Response

{
	"id": "cln14qm6l0007skt5pxzunjym",
	"koId": "cln13uepr0002skt5zql54v5k",
	"createdNewVersion": true
}

A new version is created when the payload or description changes. Changing public flag will not create a new version.

Changing public flag from true to false is not allowed when KO is under verification review. Example JSON Response when attempting to unpublish and the KO is under verification review.

{
  "message": "Knowledge could not be unpublished since it has already been accepted by a verifier."
}

Changing public flag from false to true is allowed when KO is under verification review.

POST <hostname:port>/api/v2/knowledge/:id/publish

This is the endpoint for publishing an existing knowledge object.

Example curl command

curl -X POST http://localhost:3111/api/v2/knowledge/cln14qm6l0007skt5pxzunjym/publish

Example JSON response

{
	"id": "cln14qm6l0007skt5pxzunjym",
	"publishedStatus": "PUBLISHED",
	"verifiedStatus": "PENDING"
}

Example JSON response if already published (HTTP 409)

{
  "message": "Knowledge is already published with a verified status of PENDING"
}

Example JSON response if unpublished version is already rejected by a verifier (HTTP 409)

{
  "message": "Knowledge could not be published since it has already been rejected by a verifier."
}

POST <hostname:port>/api/v2/knowledge/:id/unpublish

This is the endpoint for unpublishing an existing knowledge object.

Example curl command

curl -X POST http://localhost:3111/api/v2/knowledge/cln14qm6l0007skt5pxzunjym/unpublish

Example JSON response

{
	"id": "cln14qm6l0007skt5pxzunjym",
	"publishedStatus": "UNPUBLISHED",
	"verifiedStatus": "PENDING"
}

Example JSON response if already unpublished (HTTP 409)

{
  "message": "Knowledge is already unpublished"
}

Example JSON response if KO is being reviewed or accepted by a verifier

{
  "message": "Knowledge could not be unpublished since it has already been accepted by a verifier."
}

GET <hostname:port>/api/v2/knowledge/:id

This is the endpoint for fetching the knowledge object version by version id.

Example curl command

curl http://localhost:3111/api/v2/knowledge/cln14qm6l0007skt5pxzunjym

Example JSON response

{
	"payload": {
		"data": "test data for Generic KO. Changed Data."
	},
	"environment": {
		"type": "application/vnd.acme.app.analytic"
	},
	"description": {
		"html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>. Or Changed Description"
	},
	"metadata": {
		"name": "Generic KO mandatory fields with description",
		"about": "Short text to be displayed in the abstract of KO Page. This is optional",
		"owner": {
			"name": "John Smith",
			"email": "john.smith@example.com"
		},
		"public": false,
		"id": "http://localhost:3000/knowledge/cln14qm6l0007skt5pxzunjym/json",
		"source": "http://localhost:3000",
		"knowledgeObjectId": "cln13uepr0002skt5zql54v5k",
		"knowledgeObjectVersionId": "cln14qm6l0007skt5pxzunjym"
	}
}

GET <hostname:port>/api/v2/knowledge/:id/:attribute

This is the endpoint for fetching the 'payload', 'environment', 'description' or 'metadata' attribute of the knowledge object version by version id.

Example curl command

curl http://localhost:3111/api/v2/knowledge/cln14qm6l0007skt5pxzunjym/payload

Example JSON response

{
	"data": "test data for Generic KO. Changed Data."
}

GET <hostname:port>/api/v2/knowledge/search?q=:query&p=:page&type=:type

This is the search endpoint for querying knowledge object versions.

Query Parameters

ParamDescriptionExample
qThe query string. Searches against KO name, KOV description, KO owner and contributor names and usernames. If not specified, all KOVs will match.q=foobar
typeFilter by the knowledge object type. Multiple types may be specified, returning all KOVs with that typetype=application%2Fvnd.acme.app.analytic
pSpecify which page to return. Defaults to 1.p=2
searchAttributes.<attribute>Filter by search attribute. Each search attribute may be specified only once.searchAttributes.foo=bar&searchAttributes.baz=qux
prerequisites.<attribute>Filter by prerequisites in the same manner as search attributesprerequisites.foo=bar&prerequisites.baz=qux

Example with no query params

curl http://localhost:3111/api/v2/knowledge/search

Example JSON Response

{
	"total": {
		"value": 2,
		"relation": "eq"
	},
	"pages": 1,
	"page": 1,
	"results": [{
		"environment": {
			"type": "application/vnd.acme.app.analytic"
		},
		"description": {
			"html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>. Or Changed Description"
		},
		"metadata": {
			"owner": {
				"name": "John Smith",
				"email": "john.smith@example.com"
			},
			"name": "Generic KO mandatory fields with description",
			"about": "Short text to be displayed in the abstract of KO Page. This is optional",
			"public": false,
			"id": "http://localhost:3000/knowledge/cln14qm6l0007skt5pxzunjym/json",
			"knowledgeObjectId": "cln13uepr0002skt5zql54v5k",
			"knowledgeObjectVersionId": "cln14qm6l0007skt5pxzunjym",
			"source": "http://localhost:3000"
		}
	}, {
		"environment": {
			"type": "application/vnd.acme.app.analytic"
		},
		"description": {
			"html": "<h1>Generic KO mandatory fields with description</h1> <div>Hello World</div>"
		},
		"metadata": {
			"owner": {
				"name": "John Smith",
				"email": "john.smith@example.com"
			},
			"name": "Generic KO mandatory fields with description",
			"about": "Short text to be displayed in the abstract of KO Page. This is optional",
			"public": true,
			"id": "http://localhost:3000/knowledge/cln13uepr0003skt5fyi5vdmk/json",
			"knowledgeObjectId": "cln13uepr0002skt5zql54v5k",
			"knowledgeObjectVersionId": "cln13uepr0003skt5fyi5vdmk",
			"source": "http://localhost:3000"
		}
	}]
}

Available agent methods

Send objects to EvidenceHub

sendKnowledgeToHub(knowledge: JsonObject): Promise<object>;

sendKnowledgesToHub(knowledges: JsonObject[]): Promise<void>;

The methods mentioned above accept JSON objects in the Generic KO format and return the API response from EvidenceHub.

Update objects on EvidenceHub

updateKnowledgeOnHub(existingId: string, knowledge: JsonObject): Promise<unknown>;

The method mentioned above requires the existing version ID of an object to perform an update operation on EvidenceHub.

Publish/Unpublish objects on EvidenceHub

publishKnowledgeVersionById(knowledgeVersionId: string): Promise<object>;

unpublishKnowledgeVersionById(knowledgeVersionId: string): Promise<object>;

The methods mentioned above require the existing version ID of an object to either publish or unpublish it on EvidenceHub.

Retrieve objects from EvidenceHub

retrieveAttributeFromHub(knowledgeId: string, attribute: string): Promise<object>;

retrieveKnowledgeFromHub(knowledgeId: string, params?: URLSearchParams | undefined): Promise<JsonObject>;

retrieveKnowledgeFromHubWithSearchParams(params: URLSearchParams): Promise<JsonObject>;

The methods mentioned above require an existing version ID to retrieve an object. The attributes correspond to the Generic KO attributes: payload, environment, description, metadata. The search params method allows multiple fields to be returned in a single request. For example, ?fields=metadata&fields=environment would return a JSON object containing only the metadata and environment attributes.

Search objects on EvidenceHub

searchKnowledgeVersions(params: URLSearchParams): Promise<unknown>;

The method mentioned above utilizes parameters as described in the 'search' endpoint, detailed in the latter part of the section titled Available endpoints - V2 Generic KOs.

License

For more information on the license, see the license file.

0.1.23

8 months ago

0.1.25

4 months ago

0.1.26

4 months ago

0.1.22

1 year ago

0.1.21

1 year ago

0.1.20

1 year ago

0.1.19

1 year ago

0.1.18

2 years ago

0.1.17

2 years ago

0.1.16

2 years ago

0.1.15

2 years ago

0.1.14

2 years ago

0.1.13

2 years ago

0.1.12

2 years ago

0.1.11

2 years ago

0.1.10

2 years ago

0.1.9

2 years ago

0.1.8

2 years ago

0.1.7

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago