NAV Navbar
Node.js JavaScript (es5) JavaScript (es6)

Introduction

Welcome to the ClearRoad API!

ClearRoad is an online platform that aims to centralize data in the Road Usage Charging industry and standardize its format.

Many actors in the Road Usage Charging industry can simplify their IT integration needs by using the ClearRoad platform through its API.

This document aims to provide complete steps on how to quickly get set-up to start building great applications using the ClearRoad API.

All API interactions with ClearRoad are described in this document. The ClearRoad API is focused around the synchronization of data rather than a specification of API messages. To learn more about the ClearRoad API messages, please review the API documentation.

QuickStart

Step 1. Install the library as dependency

We are using npm to install the ClearRoad api library. Open a terminal window in your project and install the dependency using the command:

npm i @clearroad/api -S

If you want to include the files directly in your page, you can include via our CDN:

<script src="https://clearroadlab.azureedge.net/lib/ajv.js"></script>
<script src="https://clearroadlab.azureedge.net/lib/rsvp.js"></script>
<script src="https://clearroadlab.azureedge.net/lib/jio.js"></script>
<script src="https://clearroadlab.azureedge.net/api/clearroad.js"></script>

Step 2. Create a new ClearRoad instance

(function(ClearRoad) {
  const cr = new ClearRoad('apiUrl', 'accessToken');
})(ClearRoad);
import { ClearRoad } from '@clearroad/api';
const cr = new ClearRoad('apiUrl', 'accessToken');
const ClearRoad = require('@clearroad/api').ClearRoad;
const cr = new ClearRoad('apiUrl', 'accessToken');

To create an instance, you will need to have the apiUrl (the url of the ClearRoad API instance) and an accessToken. If you do not have an access token, you can request one on the developer platform.

Step 3. Choose a local storage

const cr = new ClearRoad('apiUrl', 'accessToken', {
  type: 'indexeddb'
});
const cr = new ClearRoad('apiUrl', 'accessToken', {
  type: 'indexeddb'
});
// if using .env
CLEARROAD_URL=<url>
CLEARROAD_ACCESS_TOKEN=<access token>
DROPBOX_ACCESS_TOKEN=<access token>

const dotenv = require('dotenv');
dotenv.config();
const cr = new ClearRoad(process.env.CLEARROAD_URL, process.env.CLEARROAD_ACCESS_TOKEN, {
  localStorage: {
    type: 'dropbox',
    accessToken: process.env.DROPBOX_ACCESS_TOKEN
  }
});

The ClearRoad API is based on a synchronization process, which will effectively synchronize data from the ClearRoad Platform to a "local" storage. This local storage can be on a local server, on the browser, or on a remote server.

By default, the API will use indexeddb as local storage. To use another storage please refer to the API reference.

Step 4. Retrieve messages

cr.sync()
  .then(function() {
    console.log('sync done');
    return cr.allDocs();
  })
  .then(function(results) {
    console.log(results);
  });
await cr.sync();
console.log('sync done');
const results = await cr.allDocs();
console.log(results);
await cr.sync();
console.log('sync done');
const results = await cr.allDocs();
console.log(results);

Now that you're all setup, you can start by synchronizing your local storage and then query the data.

Concepts

Pushing data to ClearRoad API

The storage must first be instantiated:

const cr = new ClearRoad('APIUrl', 'accessToken');

Data can then be pushed on the storage using the post method, and then data is synchronized with the ClearRoad platform using:

(function(ClearRoad) {
  cr.post(data)
    .push(function() {
      return cr.sync();
    })
    .push(function() {
      console.log('sync done');
    });
})(ClearRoad);
await cr.post(data);
await cr.sync();
console.log('sync done');
await cr.post(data);
await cr.sync();
console.log('sync done');

Pushing data to ClearRoad is done by posting it in a local storage and synchronizing that storage with the ClearRoad API.

Data format and validation

You can install ajv to test your JSON messages:

$ npm install -g ajv-cli
$ ajv validate -s node_modules/@clearroad/api/definitions/road-account-message.json -d data.json

All of the data can be pushed to the ClearRoad Platform using the post method. To validate the data format, we are using the ajv library.

The list of valid data format can be found under the node_modules/@clearroad/api/definitions directory.

Retrieving data from ClearRoad API

The storage must first be instantiated:

const cr = new ClearRoad('APIUrl', 'accessToken');

Then create a query on the portal_type that you want:

(function(ClearRoad) {
  cr.allDocs({
    query: 'grouping_reference: "report" AND portal_type:"Road Account Message"',
    select_list: ['source_reference', 'state', 'comment']
  }).push(result => {
    for (let i = 0; i < result.data.total_rows; i++) {
      var ref = result.data.rows[i].value.source_reference;
      var state = result.data.rows[i].value.state;
      var comment = result.data.rows[i].value.comment;
      ...
    }
  });
})(ClearRoad);
const result = await cr.allDocs({
  query: 'grouping_reference: "report" AND portal_type:"Road Account Message"',
  select_list: ['source_reference', 'state', 'comment']
});
result.data.rows.forEach(row => {
  const ref = row.value.source_reference;
  const state = row.value.state;
  const comment = row.value.comment;
  ...
});
const result = await cr.allDocs({
  query: 'grouping_reference: "report" AND portal_type:"Road Account Message"',
  select_list: ['source_reference', 'state', 'comment']
});
result.data.rows.forEach(row => {
  const ref = row.value.source_reference;
  const state = row.value.state;
  const comment = row.value.comment;
  ...
});

After pushing data to the API, you can retrieve it using the cr.allDocs function.

Examples

Check the state of all messages:

cr.allDocs({
  query: 'grouping_reference: "report"',
  select_list: ['source_reference', 'destination_reference', 'state', 'comment']
});

Retrieve the Road Account associated with a Road Account Message:

const reference = 'my-account-reference';
await cr.post({
  portal_type: 'Road Account Message',
  account_reference: reference,
  ...
});
// use reference in search as "reference"
cr.allDocs({
  query: 'portal_type: "Road Account" AND reference: "' + reference + '"',
  select_list: ['source_reference', 'registrations']
});

API Reference

ClearRoad

The ClearRoad class contains a subset of functions from the underlying jIO.js library, which uses RSVP.js to chain functions like Promises. Please refer to their documentation for more information.

constructor

new ClearRoad('apiUrl', 'accessToken');

constructor(url, accessToken, options)

Initialise a new ClearRoad object to interact with the ERP5 storage.

Param Type Description Required
url string ClearRoad API url. Yes
accessToken string Access token to authenticate on the ClearRoad API (if necessary). No
options IClearRoadOptions View IClearRoadOptions. (default: {}) No

post

cr.post({
  key1: "value",
  key2: JSON.stringify({
    "subkey": "subvalue"
  })
}).then(function(id) {
  // 'id' is the posted document 'source_reference'
})
// 'id' is the posted document 'source_reference'
const id = await cr.post({
  key1: "value",
  key2: JSON.stringify({
    "subkey": "subvalue"
  })
});
// 'id' is the posted document 'source_reference'
const id = await cr.post({
  key1: "value",
  key2: JSON.stringify({
    "subkey": "subvalue"
  })
});

post(data)

Returns: string The id of the posted message.

Posts data in your local storage and return the reference of the new document. Then use the sync method to synchronize the data with the ClearRoad API.

Param Type Description Required
data postData The message to post. Each value paired with a key must be a string. Yes

state

cr.post({...})
  .then(function(reference) {
    // posting a message returns the reference of the message
    // use reference to get the state of the message
    return cr.state(reference);
  })
  .then(function(state) {
    // state = 'processed'
  });
// posting a message returns the reference of the message
const reference = await cr.post({
  ...
});
// use reference to get the state of the message
const state = await cr.state(reference);
// state = 'processed'
// posting a message returns the reference of the message
const reference = await cr.post({
  ...
});
// use reference to get the state of the message
const state = await cr.state(reference);
// state = 'processed'

state(id)

Returns: ValidationStates The [state](#api-reference-clearroad-enums-validationstates) of the message.

Check for the processing state of the message. Allow some time after synchronizing before checking for the state.

Param Type Description Required
id string The id of the message. Yes

sync

cr.sync();

sync(progress)

Returns: IQueue<void>

Synchronizes the local storage with the ClearRoad Platform (will make sure both storage contain the same data).

Param Type Description Required
progress syncProgressCallback Function to get notified of progress. There are 4 storages to sync. (default: () => { }) No

queryByState

cr.queryByState('rejected').then(function(results) {
  // rejected messages
});
const results = await cr.queryByState('rejected');
// rejected messages
console.log(results);
const results = await cr.queryByState('rejected');
// rejected messages
console.log(results);

queryByState(state, options)

Returns: IQueue<IJioQueryResults> Search results.

Retrieve the messages in a certain "processing" state. By default, when a message is not yet synchronized or processed, the state is not_processed.

Param Type Description Required
state ValidationStates State of the message. Yes
options Partial<IJioQueryOptions> Set { sort_on, limit } on the results. (default: {}) No

allDocs

Query the documents from ClearRoad Platform:

cr.allDocs({
  query: query_object,
  limit: [3, 42],
  sort_on: [['key1', 'ascending'], ['key2', 'descending']],
  select_list: ['key1', 'key2', 'key3'],
  include_docs: false
}).then(function(result) {
  // read rows in result.rows
})
const result = await cr.allDocs({
  query: query_object,
  limit: [3, 42],
  sort_on: [['key1', 'ascending'], ['key2', 'descending']],
  select_list: ['key1', 'key2', 'key3'],
  include_docs: false
});
// read rows in result.rows
const result = await cr.allDocs({
  query: query_object,
  limit: [3, 42],
  sort_on: [['key1', 'ascending'], ['key2', 'descending']],
  select_list: ['key1', 'key2', 'key3'],
  include_docs: false
});
// read rows in result.rows

Which returns object in the following format:

// with select_list: ['select_list_key']
{
  "total_rows": 39,
  "rows": [{
    "id": "text_id",
    "value": {
      "select_list_key": "select_list_value"
    }
  }, ...]
}

// with include_docs = true
{
  "total_rows": 39,
  "rows": [{
    "id": "text_id",
    "doc": {
      "key": "value"
    }
  }, ...]
}

allDocs(options)

Returns: IQueue<IJioQueryResults> Search results.

Query for documents in the local storage. Make sure .sync() is called before.

Param Type Description Required
options IJioQueryOptions Query options. If none set, return all documents. No

getReportFromRequest

cr.getReport('reference').then(function(report) {
  // read report
})
const report = await cr.getReport('reference');
const report = await cr.getReport('reference');

getReportFromRequest(sourceReference)

Returns: IQueue<any> The report as JSON.

Get a report using the Report Request reference.

Param Type Description Required
sourceReference string The reference of the Report Request. Yes

getReport

cr.getReportFromRequest('reference').then(function(report) {
  // read report
})
const report = await cr.getReportFromRequest('reference');
const report = await cr.getReportFromRequest('reference');

getReport(reference)

Returns: IQueue<any> The report as JSON.

Retrieve the report with the given report reference. If you only have the reference of the report request, please use getReportFromRequest instead.

Param Type Description Required
reference string The reference of the Report. Yes

Enums

LocalStorageTypes

Note: this list does not contain the additional Node.js storages developped by ClearRoad available here.

Key Value Description
indexeddb 'indexeddb' Native Browser IndexedDB storage.
dropbox 'dropbox' Storage data in a dropbox account. Need accessToken.
gdrive 'gdrive' Storage data in a google drive account. Need accessToken.

PortalTypes

Each message is represented by a "portal_type" (or message category)

Key Value Description
BillingPeriodMessage 'Billing Period Message'
File 'File'
OdometerReading 'Odometer Reading'
OdometerReadingMessage 'Odometer Reading Message'
RoadAccount 'Road Account'
RoadAccountMessage 'Road Account Message'
RoadEvent 'Road Event'
RoadEventMessage 'Road Event Message'
RoadMessage 'Road Message'
RoadReportRequest 'Road Report Request'
RoadTransaction 'Road Transaction'

ValidationStates

When a message is processed by the ClearRoad platform, it will create a new message with a validation state.

Key Value Description
Processed 'processed' Message has been processed by the ClearRoad platform.
Rejected 'rejected' Message has been rejected by the ClearRoad platform. A comment will be added explaining the reason.
Submitted 'submitted' Message has been submitted to the ClearRoad platform but still processing.
Unprocessed 'not_processed' When the message has not been sent to the ClearRoad platform yet, the state is "not_processed".

GroupingReferences

Key Value Description
Data 'data' Message created in the local storage.
Report 'report' Message created on the ClearRoad platform.

Interfaces

IClearRoadOptions

Property Type Description Optional
localStorage IClearRoadOptionsLocalStorage Options for the local storage. View IClearRoadOptionsLocalStorage. Yes
minDate Date|number|string Messages updated before this date will not be synchronized. If not set, all messages will be synchronized. Improves speed of synchronisation for big sets. Yes
syncPortalTypes PortalTypes[] View PortalTypes. Defines which types of messages to synchronize. If not set, all messages will be synchronized. Improves speed of synchronisation for big sets. Yes
maxSyncObjects number Maximum number of objects that will be sycnrhonized from the ClearRoad platform to the local storage. Default is 1234567890. Yes
useQueryStorage boolean Force using a query storage around the localStorage. Needed if the storage can not query data directly. See information on the storage. Yes
debug boolean Log to console replication steps between local and remote storage. Yes

IClearRoadOptionsLocalStorage

Property Type Description Optional
type LocalStorageTypes|string Type of the storage. View LocalStorageTypes. No
accessToken string Access token to authenticate on the ClearRoad API (if necessary). Yes
database string Name of the database when the objects will be stored. Yes

IJioQueryOptions

Property Type Description Optional
query string Search with a query. Refer to the jIO documentation in the jIO Query Engine section for details. No
limit [number, number] Limit the results. Leave empty for no limit. Yes
sort_on JioQuerySortProperty[] List of fields to sort on, each specifying the order with ascending/descending. Example: [['date', 'ascending'], ['id', 'descending]] Yes
select_list string[] When provided, the response has a value containing the values of these keys for each document. Yes
include_docs boolean When true, the response has a doc containing the full metadata for each document. Yes

IJioQueryResults

Property Type Description Optional
data IJioQueryResultsData The result data. No

IJioQueryResultsData

Property Type Description Optional
rows IJioQueryResultRow[] List of result row. No
total_rows number The total number of results. No

IJioQueryResultRow

Property Type Description Optional
id string Document id No
doc any Original document value. Yes
value any Filtered properties of the document. Yes

IQueue

Property Type Description Optional
push IQueue<TResult1|TResult2> Similar to Promise but can be cancelled. No

v2.7.0Show

This content is hidden by default. Click on "Show" above or in the menu to view it.

\n

v3.0.1Show

This content is hidden by default. Click on "Show" above or in the menu to view it.

\n

v3.0.2Show

This content is hidden by default. Click on "Show" above or in the menu to view it.