iTraceiT - JavaScript Library
Developer Reference Guide
1. Introduction
iTraceiT JavaScript Library is a TypeScript/JavaScript client library that provides structured access to diamond traceability data stored on the blockchain. It abstracts authentication, HTTP communication, and response handling so that consuming applications can focus on presenting traceability information to end users.
1.1 Key Capabilities- Authenticate against the iTraceiT API and manage access tokens
- Retrieve parcel information including weight, origin, factory, and reference details
- Fetch full traceability chain data for a given parcel
- Download traceability certificates as Base64-encoded strings
- List and preview documents associated with a parcel
- Fetch group collections of parcels with pagination support
- Resolve a QR code identifier to determine whether it points to a parcel or a group
- Language: TypeScript (compiled to ES module + CommonJS dual build)
- Transport: Fetch-based HTTP client; works in browsers and Node.js
2.1 Install the Package
Important: The library has not yet been published to the npm registry. You must first place the library source on your server (or local machine) and then reference it by file path in your project's package.json.
Step 1 — Deploy the library to your environment
Copy or clone the iTraceiT library to a known path on your server or local machine. For example:
# Example deployment path on a Linux server
/opt/projects/itraceit-jslib-v2
# Example path on a local Windows machine
C:/projects/itraceit-jslib-v2
Step 2 — Add the file path reference to package.json
In the consuming project's package.json, add the library under dependencies using the file: protocol with the absolute path to the library folder:
{
"dependencies": {
"itraceit-jslib-v2": "file:/opt/projects/itraceit-jslib-v2",
"...other dependencies"
}
}
Replace /opt/projects/itraceit-jslib-v2 with the actual path where you deployed the library on your system.
Step 3 — Run npm install
After updating package.json, run the standard install command from your project root. npm will resolve the local file path and link the library into node_modules.
npm install
Step 4 — Run npm run build
After installing dependencies, build the library so it is compiled and ready for use in your project:
npm run build
This compiles the TypeScript source into JavaScript output. You only need to run this once after the initial install, or again if the library source is updated.
2.2 Import the Client
import APIClient from 'itraceit-jslib-v2';
// CommonJS
const APIClient = require('itraceit-jslib-v2');
2.3 Configuration Object
Before creating a client instance you need two credentials:
|
Field |
Type |
Description |
|
hashKey |
string |
Your API authentication hash key |
|
domainId |
string |
Tenant / domain identifier assigned to your organization |
const config = {
hashKey: 'YOUR_HASH_KEY',
domainId: 'YOUR_DOMAIN_ID',
};
const apiClient = new APIClient(config);
Authentication must be performed before calling any data endpoint. The library stores the resulting access token internally and attaches it to every subsequent request automatically.
3.1 authenticate()
Sends credentials to the API and stores the returned access token.
const authResponse = await apiClient.authenticate();
if (authResponse.status) {
console.log('Authenticated successfully');
} else {
console.error('Authentication failed:', authResponse);
}
3.2 isAuthenticated()
Returns true if a valid access token is currently held by the client. Use this as a lightweight check before issuing API calls, without making a network request.
if (!apiClient.isAuthenticated()) {
await apiClient.authenticate();
}
3.3 Token Management
Two helper methods are available if you need fine-grained control over the token. setToken(token) allows you to inject an externally obtained token, while clearToken() removes the stored token to force re-authentication.
// Inject an existing token (e.g. from local storage)
apiClient.setToken('eyJhbGci...');
// Remove the token (forces re-auth on the next call)
apiClient.clearToken();
A QR code scanned by an end user can represent either an individual parcel or a group of parcels. You should always resolve the QR code first to determine the correct follow-up API call.
4.1 getQRDetails(id)
|
Parameter |
Details |
|
id |
The identifier scanned from the QR code (string) |
|
Returns |
ApiResponse<QRDetailsResponse> — contains a type field ('parcel' | 'group') and the resolved id |
const qrInfo = await apiClient.getQRDetails(scannedId);
if (qrInfo.status) {
const { type, id } = qrInfo.data;
if (type === 'parcel') {
// call getParcel(id)
} else if (type === 'group') {
// call getGroup(id, 0, 20)
}
}
5. Parcel APIs
5.1 getParcel(parcelId)
Returns the main details of a parcel: ID, reference, weight, number of stones, country of origin, and additional metadata.
const parcelInfo = await apiClient.getParcel(parcelId);
if (parcelInfo.status) {
const { id, reference, weight, country, factory } = parcelInfo.data;
// render parcel details in the UI
}
5.2 getTraceabilityInformation(parcelId)Returns the full origin and traceability chain for the parcel — mine, manufacturer, trading entities, certifications, and all intermediary custody steps recorded on the blockchain.
const traceability = await apiClient.getTraceabilityInfomation(parcelId);
if (traceability.status) {
const traceData = traceability.data;
// render the traceability timeline or origin map
}
Note: The method name in the current build contains a typo (getTraceabilityInfomation). Use this exact spelling when calling it.
5.3 getTraceabilityCertificate(parcelId)Downloads the traceability certificate for the parcel. The response data is a Base64-encoded string which can be decoded and rendered as a PDF, or used to generate a download link in a browser.
const cert = await apiClient.getTraceabilityCertificate(parcelId);
if (cert.status) {
const base64String = cert.data;
// Open as PDF in the browser
const pdfUrl = `data:application/pdf;base64,${base64String}`;
window.open(pdfUrl);
}
6. Document APIs
6.1 getDocumentDetails(parcelId)
Returns a list of all documents associated with the given parcel. Each document record includes its own unique document ID that is used as the input to getDocumentPreview.
const documents = await apiClient.getDocumentDetails(parcelId);
if (documents.status) {
documents.data.forEach(doc => {
console.log(doc.id, doc.name, doc.type);
});
}
Fetches the raw binary content of a document, returned as a Uint8Array. This can be used to render a preview, display an image, or trigger a download. Note that the input here is the document ID returned by getDocumentDetails, not the parcel ID.
const preview = await apiClient.getDocumentPreview(documentId);
if (preview.status) {
const bytes = preview.data; // Uint8Array
const blob = new Blob([bytes]);
const url = URL.createObjectURL(blob);
document.getElementById('preview').src = url;
}
7. Group APIs
7.1 getGroup(id, index, limit)
Fetches a paginated list of parcels belonging to a group, along with group-level metadata. This is called when getQRDetails identifies the scanned code as a group.
|
Parameter |
Type |
Description |
|
id |
string |
The group identifier returned by getQRDetails |
|
index |
number |
Zero-based page index (0 = first page) |
|
limit |
number |
Number of parcels to return per page (e.g. 20) |
const PAGE_SIZE = 20;
const group = await apiClient.getGroup(groupId, 0, PAGE_SIZE);
if (group.status) {
const { parcels, total, details } = group.data;
// render group parcels and pagination controls
}
8. Response Format
Every method returns a Promise that resolves to an ApiResponse<T> object. The shape is consistent across all calls:
interface ApiResponse<T> {
status: boolean; // true = success, false = failure
data: T; // typed payload (null / undefined on failure)
error?: string; // human-readable error message when status = false
}
8.1 Error Handling Pattern
Always check status before consuming data. This prevents runtime errors when the API returns a non-success response.
const result = await apiClient.getParcel(id);
if (!result.status) {
// Handle error — show a message, retry, redirect to login, etc.
console.error('API error:', result.error);
return;
}
// Safe to use result.data here
renderParcel(result.data);
9. Method Quick Reference
All methods below are members of the APIClient class and return Promise<ApiResponse<T>>.
|
Method |
Parameters |
Response Type |
Description |
|
authenticate() |
— |
AuthSecureResponse |
Obtain and store an access token |
|
isAuthenticated() |
— |
boolean |
Check if a token is currently held |
|
getQRDetails(id) |
id: string |
QRDetailsResponse |
Resolve a QR id to parcel or group |
|
getParcel(id) |
parcelId: string |
ParcelResponse |
Fetch main parcel metadata |
|
getTraceabilityInfomation(id) |
parcelId: string |
TraceabilityResponse |
Fetch the traceability chain |
|
getTraceabilityCertificate(id) |
parcelId: string |
string (Base64) |
Download certificate as Base64 |
|
getDocumentDetails(id) |
parcelId: string |
DocumentDetailsResponse |
List documents for a parcel |
|
getDocumentPreview(id) |
documentId: string |
RawData (Uint8Array) |
Download raw document bytes |
|
getGroup(id, index, limit) |
id, index, limit |
GroupResponse |
Paginated group parcel list |
|
setToken(token) |
token: string |
void |
Manually inject an access token |
|
clearToken() |
— |
void |
Remove the stored access token |
|
updateConfig(config) |
Partial<Config> |
void |
Update hashKey / domainId at runtime |
10. Best Practices
Create a single APIClient instance for the lifetime of your application. The client holds the authentication token internally; creating multiple instances will require re-authentication each time.
Call authenticate() once at startup. If a downstream call fails due to an expired token, catch the error and call authenticate() again before retrying.
Never assume a scanned QR code points to a parcel. Always call getQRDetails before invoking any parcel or group endpoint to avoid incorrect API calls and unexpected errors.
Once a parcel ID is confirmed, the parcel info, traceability, certificate, and document list endpoints are independent of each other. Use Promise.all() to fetch them concurrently and reduce total page-load latency.
Never hard-code hashKey or domainId in source code. Store them as environment variables or inject them via your deployment configuration.
const apiClient = new APIClient({
hashKey: process.env.ITRACEIT_HASH_KEY,
domainId: process.env.ITRACEIT_DOMAIN_ID,
});
The library ships with a test suite. To run it locally after cloning the repository:
npm run test
Tests are for development and debugging purposes. Do not include test code in production builds.