Code Monkey home page Code Monkey logo

ngsijs's Introduction

ngsijs

License Documentation Status Build Status Coverage Status

Ngsijs is the JavaScript library used by WireCloud for adding FIWARE NGSI capabilities to widgets and operators. However, this library has also been designed to be used in other environments as normal web pages and clients/servers running on Node.js.

This library has been developed following the FIWARE NGSI v1 and NGSI v2 specifications and has been tested to work against version 0.26.0+ of the Orion Context Broker.

Reference documentation of the API is available at http://conwetlab.github.io/ngsijs/stable/NGSI.html.

Using ngsijs from normal web pages

Note: Support for Cross-Origin Resource Sharing (CORS) has been added on orion 1.10.0. This support must be enabled to access the context broker from a web page in a different domain than the context broker.

CORS support can also be enabled by accessing to the context broker server using some proxies, like cors-anywhere or the FIWARE's pep proxy.

You can access any context broker server (without requiring CORS support and regardless of the context broker version) if the context broker is accessible throught the same domain as the web page. How to create such configuration is out of the scope of this documentation.

Just include a <script> element linking to the NGSI.min.js file:

<script type="text/javascript" src="url_to_NGSI.js"></script>

Once added the <script> element, you will be able to use all the features provided by the ngsijs library (except receiving notifications):

var connection = new NGSI.Connection("http://orion.example.com:1026");
connection.v2.listEntities().then((response) => {
    response.results.forEach((entity) => {
        console.log(entity.id);
    });
});

This example will display the id of the first 20 entities. See the documentation of the listEntities method for more info.

To be able to receive notifications inside a web browser the library requires the use of a ngsi-proxy server. You can use your own instance or the ngsi-proxy instance available at https://ngsiproxy.lab.fiware.org.

var connection = new NGSI.Connection("http://orion.example.com:1026", {
    ngsi_proxy_url: "https://ngsiproxy.lab.fiware.org"
});

Using ngsijs from Node.js

$ npm install ngsijs

After installing the ngsijs node module, you will be able to use the API as usual:

var NGSI = require('ngsijs');
var connection = new NGSI.Connection("http://orion.example.com:1026");
connection.v2.listEntities().then((response) => {
    response.results.forEach((entity) => {
        console.log(entity.id);
    });
});

Note: Node.js doesn't require the usage of a ngsi-proxy as you can create an HTTP endpoint easily (e.g. using express). Anyway, you can use it if you want, you only have to take into account that is better to directly provide the HTTP endpoint to reduce the overhead.

Using ngsijs from WireCloud widgets/operators

WireCloud already provides some components (widgets, operators and mashups) allowing NGSI connectivity. E.g.:

Anyway, WireCloud uses ngsijs as the binding for connecting to context brokers. If you need to create a new specific component you can take a look into the "3.2.1. Using Orion Context Broker" tutorial available at the FIWARE Academy.

ngsijs's People

Contributors

aarranz avatar cblanco avatar dependabot[bot] avatar fdelavega avatar fgalan avatar fisuda avatar rockneurotiko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngsijs's Issues

Support for geo-queries in v2.listEntities([options])

According to documentation at http://conwetlab.github.io/ngsijs/stable/NGSI.Connection.html#.%22v2.listEntities%22__anchor, the supported options are:

    attrs (String): Comma-separated list of attribute names whose data are to be included in the response. The attributes are retrieved in the order specified by this parameter. If this parameter is not included, the attributes are retrieved in arbitrary order.
    correlator (String): Transaction id
    count (Boolean; default: false): Request total count
    id (String): A comma-separated list of entity ids to retrieve. Incompatible with the idPattern option.
    idPattern (String): A correctly formated regular expression. Retrieve entities whose ID matches the regular expression. Incompatible with the id option
    limit (Number; default: 20): This option allow you to specify the maximum number of entities you want to receive from the server
    offset (Number; default: 0): Allows you to skip a given number of elements at the beginning
    metadata (String): A comma-separated list of metadata names to include in the response
    mq (String): A query expression for attribute metadata, composed of a list of statements separated by semicolons (;)
    orderBy (String): Criteria for ordering results
    q (String): A query expression, composed of a list of statements separated by semicolons (;)
    service (String): Service/tenant to use in this operation
    servicepath (String): Service path to use in this operation
    type (String): A comma-separated list of entity types to retrieve. Incompatible with the typePattern option.
    typePattern (String): A correctly formated regular expression. Retrieve entities whose type matches the regular expression. Incompatible with the type option.
    unique (Boolean): Represent entities as an array of non-repeated attribute values.
    values (Boolean): Represent entities as an array of attribute values

However, what about geometry, georel and coords? They aren't in the list and are needed to get advantages of one of the most important features of Orion Context Broker: geo queries.

Is this a gap in the current implementation of the library? Or a gap in the documentation?

Thanks!

Error when trying to retrieve the entity attributes

Dear Developers,

when implementing connection class https://conwetlab.github.io/ngsijs/stable/NGSI.Connection.html faced with some difficulties, namely by implementing following methods in NGSIv2:

getEntityAttribute

Properties "attribute" and "id" are not marked as required, while they are. By sending the following curl:

curl -s -H "Content-Type: application/json" -X POST -d '{"bodyParams": {"options": {"attribute": "brightness", "id": "LED002", "type": "LED"}}}' http://localhost:3000/accessfunctionality/orion/getEntityAttribute

Get an error:

{"status":"error","message":"Cannot create property 'search' on string 'http://xxxxxxxx/v2/entities/LED002/attrs/brightness'"}

NGSI.Connection:

 getEntityAttribute(connection, params){
    return new Promise(function(resolve, reject){
      console.log('NGSI function call: getEntityAttribute');

      connection.v2.getEntityAttribute(params.options).then(
        (response) => {
			resolve(response);
        }, (error) => {
			reject(error);
        }
      );
    });
  }

The same difficulties I faced with some other methods:
replaceEntityAttributeValue
replaceEntityAttribute
deleteEntityAttribute
getEntityAttribute

Some testing:

 getEntityAttribute(connection, params){
    return new Promise(function(resolve, reject){
      console.log('NGSI function call: getEntityAttribute');

	  console.log(params);
      connection.v2.getEntityAttribute(params.options).then(
        (response) => {
			console.log("correct");
			resolve(response);
        }, (error) => {
			console.log("error");
			reject(error);
        }
      );
    });
  }

Result:

-> controller: AccessFunctionality NGSI connection NGSI function call: getEntityAttribute { options: { attribute: 'brightness', id: 'LED002', type: 'LED' } } POST /accessfunctionality/orion/getEntityAttribute 200 115.451 ms - 138 Executing (default): INSERT INTO "Performances" ("id","component","name","service","executionTime","status","errorMessage","createdAt") VALUES (DEFAULT,'Enabler','orion','getEntityAttribute',4.087831,'Error','Cannot create property ''search'' on string ''http://xxxxxxxx/v2/entities/LED002/attrs/brightness''','2017-11-07 16:37:06.750 +00:00') RETURNING *; Executing (default): INSERT INTO "Performances" ("id","component","service","executionTime","status","createdAt") VALUES (DEFAULT,'Enablers Framework','/accessfunctionality/orion/getEntityAttribute',118.999163,'Success','2017-11-07 16:37:06.755 +00:00') RETURNING *;

I will really appreciate, if you could help me. Thank you in advance!

TOKEN retrieval

I'm strongly opting for including a function for retrieving tokens from the public ORION implementation, since the tokens are only valid for one hour.

batchQuery Error

Dear Developers,

I've already wrote you about a problem with "getEntityAttribute". Thank you very much for fixing this. However now I faced new difficulty with following method:

"batchQuery"

The problem is something is wrong with connection and request processing, the curl:

curl -s -H "Content-Type: application/json" -X POST -d '{"bodyParams": {"options": {}}}' http://localhost:3000/accessfunctionality/orion/batchQuery

Error:

{"status":"error","message":"Unexpected error code: 400"}

NGSI.Connection:

batchQuery(connection, params){
return new Promise(function(resolve, reject){
console.log('NGSI function call: batchQuery');

   connection.v2.batchQuery(params.options).then(
     (response) => {
       resolve(response);
     }, (error) => {
       reject(error);
     }
   );
 });

}

Tried some testing:

batchQuery(connection, params){ return new Promise(function(resolve, reject){ console.log('NGSI function call: batchQuery'); console.log(params); connection.v2.batchQuery(params.options).then( (response) => { console.log("correct"); resolve(response); }, (error) => { console.log("error error error error"); reject(error); } ); }); }

Result:

controller: AccessFunctionality NGSI connection NGSI function call: batchQuery { options: {} } error error error error POST /accessfunctionality/orion/batchQuery 200 155.687 ms - 57 Executing (default): INSERT INTO "Performances" ("id","component","name","service","executionTime","status","errorMessage","createdAt") VALUES (DEFAULT,'Enabler','orion','batchQuery',76.60613,'Error','Unexpected error code: 400','2017-11-13 15:54:20.210 +00:00') RETURNING *; Executing (default): INSERT INTO "Performances" ("id","component","service","executionTime","status","createdAt") VALUES (DEFAULT,'Enablers Framework','/accessfunctionality/orion/batchQuery',158.707139,'Success','2017-11-13 15:54:20.214 +00:00') RETURNING *;

When testing without parameters:

` batchQuery(connection, params){
return new Promise(function(resolve, reject){
console.log('NGSI function call: batchQuery');

  connection.v2.batchQuery().then(
    (response) => {
      resolve(response);
    }, (error) => {
      reject(error);
    }
  );
});

}`

Throws an error (as also stated in documentation: "query is empty" - this part is working well according docs):

{"status":"error","message":"missing query parameter"}

I will be grateful, if you could help me, and point what is wrong. Thank you in advance!

N.B.

"batchUpdate" works well, I already tested it, but has an additional parameter "changes". And entities to be updated can be delivered inside this parameter.

Error when trying to list entities

       <script type="text/javascript">
		$(document).ready(function() {
			console.log('Ready disparado');
			window.connection = new NGSI.Connection("http://ip_address:1026");

			console.log(connection);
			connection.v2.listEntities().then((result) => {
			    response.results.forEach((entity) => {
			        console.log(entity.id);
			    });
			});
		});
	</script>
Uncaught TypeError: this.makeRequest is not a function
    at NGSIConnection.makeJSONRequest2 (NGSI.js:206)
    at V2.listEntities (NGSI.js:2604)
    at HTMLDocument.<anonymous> (index.html:15)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)

Add NGSIv2 support

Add NGSIv2 support (RC-2016.10):

  • Entities:

    • List entities
    • Create entities
    • Get entity
    • Get entity attributes
    • Update or append entity attributes
    • Update entity attributes
    • Replace entity attributes
    • Delete entity
    • Get entity attribute
    • Update entity attribute
    • Delete entity attribute
    • Get single attribute value
    • Update attribute value
  • Types:

    • List types
    • Get type
  • Subscriptions:

    • List subscriptions
    • Create subscriptions
    • Get subscription
    • Update subscription
    • Delete subscription
  • Batch Operations:

    • Update
    • Query

Question: ngsijs or ngsi-parser + ocb-sender

hello, i am new to fiware and wanted to ask which library i should use to communicate with the context broker.
According to the documentation fiware refers to the ngsi-parser and ocb-sender (https://ngsi-js-library.readthedocs.io/en/latest/).
but these libraries were last updated 3-4 years ago.
this library (ngsijs) I see is still relatively up to date.

so my question: should i use ngsijs or the other one?

thanks in advance!

I want to use this library for backend, nodejs.

status code is not provided when InvalidResponseError is obtained

status code is not provided when InvalidResponseError is obtained

ngsijs/dist/NGSI.js

Lines 1687 to 1691 in 59ce53e

NGSI.InvalidResponseError = function InvalidResponseError(message, correlator) {
this.name = 'InvalidResponse';
this.message = message || '';
this.correlator = correlator;
};

InvalidResponseError could happens for example when PEP responses 401

Not sure if is really a bug or maybe just something that could be improved.
Others errors like InvalidRequestError are providing status code:

ngsijs/dist/NGSI.js

Lines 1624 to 1629 in 59ce53e

NGSI.InvalidRequestError = function InvalidRequestError(code, message, details) {
this.name = 'InvalidRequest';
this.code = code;
this.message = message || '';
this.details = details || '';
};

Deprecate contextValue and support value when using the updateAttributes, addAttributes and query methods

Currently, the ngsijs library uses a contextValue attribute for providing new values when using the updateAttributes and the addAttributes methods. The name of this attribute comes from the name of the XML element used in the initial payloads. On the current JSON payload, this attributes is called value, so seems more natural to use this name instead of contextValue. Anyway, we have to continue supporting the use of the contextValue attribute for allowing a soft migration.

Add Travis CI

Use Travis to pass karma tests instead of using jenkins.

Empty contextValue is wrongly translated

in ngsi_build_update_context_request:
if (contextValue.trim() === '') { attributeElement.valuecontextValue = 'emptycontent'; }
should be

if (contextValue.trim() === '') { contextValue = 'emptycontent'; }

No tests failing?

Pass unit tests on node

Currently, tests are only executed on firefox/chrome (using Karma and Travis CI). Those test should be also executed using node.

node-js client does not work with Orion context broker

When using the node-js client with Orion, I get the following:

time=2016-05-11T11:36:53.780UTC | lvl=WARNING | corr=a8d4baac-176c-11e6-9e73-029d61bc569f | trans=1462965567-845-00000000086 | srv= | subsrv= | from=127.0.0.1 | function=badInputReset | comp=Orion | msg=AlarmManager.caising alarm BadInput 127.0.0.1: no valid 'Accept-format' found

This is caused by the fact the Accept format is set to applicaiton/xml, which is not supported by Orion

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.