1.0.2 • Published 5 years ago

unimatrix-html-application-sdk v1.0.2

Weekly downloads
9
License
-
Repository
-
Last release
5 years ago

javascript-unimatrix-sdk

Javascript SDK for Unimatrix APIs

The Unimatrix SDK is used to make requests to and parse responses from internal APIs. It's broken down in to a number of different services, which live under specific modules.

Installation

npm install --save bedrocketjmd/javascript-unimatrix-sdk

For usage in Node apps, it can be included normally:

var unimatrix = require( 'javascript-unimatrix-sdk' );

For front-end usage, the SDK can be included with dist/unimatrix-sdk.js and accessed through window.unimatrix.

Injector

Accessing services requires injecting them with, appropriately enough, the .injector method. Invoking .injector without any arguments will return an injector instance with all available modules and services, which can then be invidivually retrieved with .get, like so:

var unimatrix = require( 'javascript-unimatrix-sdk' );
var operation = unimatrix.injector().get( 'Operation' );

When retrieving a service, you can optionally specify its module. This is generally unnecessary, since .get will default to retrieving services off of the Unimatrix module, which is where the main services are attached. If you need to interact with a non-Unimatrix service directly (a resource service, for example), you can put include the module name in the .get invocation, separating it from the service with a slash.

var artifact = unimatrix.injector().get( 'Resources/Artifact' );

Operation

Operation is the main means of making requests through the SDK. At its most basic, it can be as simple as:

var operation = unimatrix.injector().get( 'Operation' );

operation( 'https://url.com/path' ).
  then( response => {
    ...
  } )

It will make a request to the given path, parse the response, and return a resource object for each item in the response.

Operation can be configured with a base URL and set of default parameters that will be included with all requests.

operation.baseUrl = 'https://unimatrix.io';
operation.defaultParameters = { access_token: 'abcd1234' };

operation( '/realms/1234' );
// results in https://unimatrix.io/realms/1234?access_token=abcd1234

Operation Methods

Operation uses a number of chainable methods to customize requests and make the requests themselves.

Parameter methods

These are used for configuring a request's parameters or setting a request to batch mode.

.where( <parameters> )

Takes an object of query parameter keys and values and includes them on the request.

operation('https://unimatrix.io').
  where( { uuid: 'abcd1234' } );
// results in https://unimatrix.io?uuid=abcd1234

It will combine the given parameters with existing ones, which will override default parameters if the keys conflict.

.order( <sort by field>, <sort by direction> )

Adds sort parameters to the request. It takes a field and a direction (ascending or descending) and will sort responses accordingly.

.include( <fields to include> )

Takes an array, object, or just a series of relationships to be included in a response.

operation( 'https://unimatrix.io' )
  .include( 'components' );

operation( 'https://unimatrix.io' )
  .include( 'components', 'blueprints' );

operation( 'https://unimatrix.io' )
  .include( [ 'components', 'blueprints' ] );

operation( 'https://unimatrix.io' )
  .include( { videos: 'video_encoders' } )

// all valid

.limit( <record count> )

Takes an integer and limits the response to the given number of records. If this is used with a batched request, it will limit the total number of records returned to the given number.

.offset( <record count> )

Takes an integer and offsets the records returned by the given number. As an example, .offset( 5 ) would return records starting after the 5th from the available records that meet the other request criteria.

.find( <record id> )

Takes a record id and limits the response to a single record with a matching id.

.take()

Limits the response to a single record.

.batch( <record count> )

Takes an integer quantity of records to make requests in batches of. If no argument is supplied, .batch defaults to 100.

When reading records, successive requests will be made for the given quantity of records until either all records are returned or a provided limit was reached. When writing records, the records are broken up into batches of the given number and then written sequentiallly. If a request fails within a batched write, a remaining key will be present on the returned error that contains the unwritten records.

Request Methods

Once the request is configured, you can fire it off using one of the following methods. Each of them returns a promise that will resolve or reject depending on the status code of the response.

.query()

This will make a GET request as configured.

.destroy()

This will make a DELETE request as configured.

.write( <name>, <data> )

Takes the plural name of the type of record (like "artifacts") and a single object or an array of objects to be written, and makes a POST request as configured.

.then( <success handler>, <failure handler> )

The Promise.then you know and love. Currently, this functions as shorthand for .query().then().

Responses

Query

If a single record is returned, a successful Operation will result in a single resource object. If multiple records are returned, an array of resource objects will result. The array will additionally have count and unlimitedCount keys for the number of records returned and the total number of available records, respectively.

Write

A successful write will always return an array of resource objects.


Authorization

The Node SDK has an Authorization method for using a client ID and secret to request an access token. Instating it requires an authorization URL and an object containing a client ID and secret, like so:

var auth = injector().
  get( 'Authorization' )(
    'http://us-west-2.keymaker.acceptance.boxxspring.net',
    {
      id: process.env.CLIENT_ID,
      secret: process.env.CLIENT_SECRET
    }
  );

Authorization methods

.setUrl( <url> )

Replaces the existing authorization URL with a new one.

.setConfig( <configuration object> )

Replaces the existing client ID and secret with new ones. The configuration object is identical to the one used during instantiation and expects id and secret keys.

.getToken()

Makes a request to the configured URL with the supplied credentials and returns a Promise that will resolve with an accessToken and expiresIn, if successful.

auth.getToken().
  then( tokenResponse => {
    var token = tokenResponse.accessToken;
    var expiry = tokenResponse.expiresIn;
  } );

Resources

The SDK uses services attached to the Resources module to parse API resources and their relationships. In-SDK resources will correspond directly to the resources provided from an API and must be present to successfulily request a particular resource; if a response includes an unknown resource, an error will be thrown. Resources can be injected directly if you want to modify the base resource, but this shouldn't be necessary for normal use.

Resource Methods

Resource instances are returned after a successful request with Operation, and have a number of standard methods:

.duplicate()

Returns a copy of the resource without an id key.

.getKey()

Returns the resource's id.

.getAttribute( <attribute name> )

Returns the value of the given attribute name;

.getAttributesByAlias()

Returns an object containing all of an artifact's attributes.

In addition, a resource will have getter methods for its various associations. Each of these returns a promise that will resolve with the requested resource, if available. The exact method syntax depends on the relationship, and follows the following patterns:

references one/belongs to

For resources that reference or belong to a single other resource:

.get<resource name>()

Returns the associated resource.

Example: .getArtifact()

references many

Resources that reference multiple other resources will have two methods for each distinct resource they reference.

get<plural resource name>()

Returns an array of associated resources.

Example: .getArtifacts()

get<resource>By( <attribute name>, <attribute value> )

Returns an associated resource that has the specified value in the specified attribute. If no such resource exists, returns undefined.

Example: .getArtifactBy( 'name', 'My Artifact' )

Supported Resources

Examples

Reading a single record

var unimatrix = require( 'javascript-unimatrix-sdk' );
var operation = unimatrix.injector().get( 'Operation' );
var blueprintOperation = injector().get( 'BlueprintOperation' );
var auth = injector().
  get( 'Authorization' )(
    'http://us-west-2.keymaker.acceptance.boxxspring.net',
    {
      id: process.env.CLIENT_ID,
      secret: process.env.CLIENT_SECRET
    }
  );

var realmId = '7d4decd6c99c33bfe2c41829310122c5'; var artifactId = '4aee7ef0fbcfecb1dd8786e24449e69f';

operation.baseUrl = 'http://us-west-2.api.acceptance.unimatrix.io/';

auth.getToken(). then( credentials => { var token = credentials.accessToken;

return blueprintOperation( realmId, token ).
  then( _blueprints => {
    return operation( `/realms/${realmId}/artifacts/${artifactId}` ).
      where( { access_token: token } )
  } );

} ). then( artifact => { // the returned artifact will look something like this: // // resource { // createdAt:Fri Sep 07 2018 10:12:34 GMT-0700 (Pacific Daylight Time) {} // duplicate:function() { … } // getArtifactBy:function( fieldName , fieldValue ) { … } // getArtifactLocatorBy:function( fieldName , fieldValue ) { … } // getArtifactLocators:function() { … } // getArtifactRelationshipBy:function( fieldName , fieldValue ) { … } // getArtifactRelationships:function() { … } // getArtifacts:function() { … } // getAttribute:function( name ) { … } // getAttributesByAlias:function() { … } // getComponentBy:function( fieldName , fieldValue ) { … } // getComponents:function() { … } // getErrorBy:function( fieldName , fieldValue ) { … } // getKey:function() { … } // id:"538665b602b85ff2a49971f8de44af00" // name:"240p_2c273649f3c7dafa8988cf882c287d44.mp4 Picture" // pictureRenditionUrl:"http://alchemist-binaries-acceptance-us-west-2.s3.amazonaws.com/7e018aaf556679b0879b3bc2fcc328a1.jpg" // realmUuid:"7d4decd6c99c33bfe2c41829310122c5" // typeName:"picture_artifact" // updatedAt:Fri Sep 07 2018 10:12:34 GMT-0700 (Pacific Daylight Time) {} // uuid:"4aee7ef0fbcfecb1dd8786e24449e69f" // } } );

> __Reading multiple records__
```js
var unimatrix = require( 'javascript-unimatrix-sdk' );
var operation = unimatrix.injector().get( 'Operation' );
var blueprintOperation = injector().get( 'BlueprintOperation' );
var auth = injector().
  get( 'Authorization' )(
    'http://us-west-2.keymaker.acceptance.boxxspring.net',
    {
      id: process.env.CLIENT_ID,
      secret: process.env.CLIENT_SECRET
    }
  );

var realmId = '7d4decd6c99c33bfe2c41829310122c5';

operation.baseUrl = 'http://us-west-2.api.acceptance.unimatrix.io/';

auth.getToken().
  then( credentials => {
    var token = credentials.accessToken;

    return blueprintOperation( realmId, token ).
      then( _blueprints => {
        return operation( `/realms/${realmId}/artifacts` ).
          where( {
            access_token: token,
            type_name: 'video_artifact'
          } ).
          limit( 3 ).
          order( 'created_at', 'ascending' )
      } );
  } ).
  then( artifacts => {
    // Array {
    //   count: 3,
    //   length: 3,
    //   unlimitedCount: 42,
    //   0: resource {id: "b871e7235014c993f24d18678f3e59b5", uuid: "4b1af0e26668fa2bd8e1daef878a523a", typeName: "video_artifact", …},
    //   1: resource {id: "5b3efe6297c961c69fbc08cb4e8272a1", uuid: "bba0df0efd9d1c70cc725bf4912a2c63", typeName: "video_artifact", …},
    //   2: resource {id: "052b0cb07667d77d111232a0c333fb92", uuid: "d92012e6b71eab78ec0764efd71d1280", typeName: "video_artifact", …}
    // }
  } );

Writing a single record

var unimatrix = require( 'javascript-unimatrix-sdk' );
var operation = unimatrix.injector().get( 'Operation' );
var blueprintOperation = injector().get( 'BlueprintOperation' );
var auth = injector().
  get( 'Authorization' )(
    'http://us-west-2.keymaker.acceptance.boxxspring.net',
    {
      id: process.env.CLIENT_ID,
      secret: process.env.CLIENT_SECRET
    }
  );

var realmId = '7d4decd6c99c33bfe2c41829310122c5';

operation.baseUrl = 'http://us-west-2.api.acceptance.unimatrix.io/';

auth.getToken(). then( credentials => { var token = credentials.accessToken;

return blueprintOperation( realmId, token )
  .then( _blueprints => {
    return operation( `/realms/${realmId}/artifacts` ).
      where( {
        access_token: token,
      } ).
      write( {
        "type_name": "picture_artifact",
        "picture_uuid": "ad0f0aeed6dbc3dc4daef3e28e92e082",
        "name": "My Picture"
      } )
  } );

} ). then( artifact => { // // getArtifactRelationships:function() { … } // getArtifacts:function() { … } // getAttribute:function( name ) { … } // getAttributesByAlias:function() { … } // getComponentBy:function( fieldName , fieldValue ) { … } // getComponents:function() { … } // getErrorBy:function( fieldName , fieldValue ) { … } // getErrors:function() { … } // getKey:function() { … } // id:"3866d2f4a18830ae6ebb8f68b21d842f" // name:"My Picture" // pictureUuid:"ad0f0aeed6dbc3dc4daef3e28e92e082" // realmUuid:"7d4decd6c99c33bfe2c41829310122c5" // typeName:"picture_artifact" // updatedAt:Thu Sep 27 2018 14:48:12 GMT-0700 (Pacific Daylight Time) {} // uuid:"357bda6ba09dafbff8310b23e6ee0074" // } );

1.0.2

5 years ago

1.0.1

5 years ago