Javascript Developer Guide
Deep detail about @dataswift/hat-js

Overview

This library contains all the API calls needed to communicate with the HAT
  • Authentication
  • Fetch Applications and Data Connectors
  • Fetch Data Debits
  • Read and write data to endpoints
  • File API

Supported Environments

The @dataswift/hat-js library works in all modern browsers. Some older browsers do not support all the features required. If you want to support these browsers you need to load polyfill for Promise.

Installation

Install the @dataswift/hat-js package via npm or pull from our CDN.
NPM installation
1
npm install @dataswift/hat-js
Copied!
CDN Link
1
<script src="https://cdn.dataswift.io/libs/hatjs/hat-0.3.0.min.js"></script>
Copied!

Usage

Importing

ES6
1
import { HatClient } from "@dataswift/hat-js";
Copied!
ES5 Modules
1
var HatClient = require("@dataswift/hat-js").HatClient;
Copied!

Initialisation

Configuration type:
1
interface HatClientConfig {
2
apiVersion?: string; // Api Version for the HAT. eg. v2.6
3
hatDomain?: string; // The HAT domain of the user. eg. testing.hubat.net
4
token?: string; // The Application token.
5
secure?: boolean; // If you want to run the HAT locally, you have to modify this field to 'false'.
6
onTokenChange?: Function;
7
}
Copied!
Example:
1
const config = {
2
token: "<access-token>",
3
apiVersion: 'v2.6',
4
secure: true,
5
onTokenChange: (newToken) => storeNewToken(newToken)
6
};
7
8
const hat = new HatClient(config);
Copied!

Authentication

Check if HAT exists

Parameters
Type
hatDomain
string
Example:
1
const hatDomain = "testing.hubat.net";
2
try {
3
const res = hat.auth().isDomainRegistered(hatDomain);
4
if (res) {
5
// HAT domain is registered
6
}
7
} catch (e) {
8
// HAT domain doesn't exist
9
}
Copied!

Sign out

Example:
1
hat.auth().signOut();
Copied!

Get HAT domain

Example:
1
const res = hat.auth().getHatDomain();
2
if (res) {
3
// Returns the HAT Domain
4
// eg. testing.hubat.net
5
}
Copied!

Get auth token

Example:
1
const res = hat.auth().getToken();
2
if (res) {
3
// Returns the auth token
4
}
Copied!

Check if token has expired

Example:
1
const token = '<auth-token>';
2
3
if (hat.auth().isTokenExpired(token)) {
4
// Token has expired
5
}
Copied!

Generate HAT login URL

Example:
1
const hatDomain = 'testing.hubat.net';
2
const appId = 'our-app-id';
3
const redirect = 'callback-url';
4
const fallback = 'fallback-url';
5
6
const url = hat.auth().generateHatLoginUrl(hatDomain, appId, redirect, fallback);
7
if (url) {
8
window.location.href = url;
9
}
Copied!

Applications

Get all the apps

The are 2 ways to fetch applications:
With default options:
Example:
1
try {
2
const result = await hat.applications().getAllDefault();
3
4
if (result.parsedBody) {
5
// result.parsedBody contains an array of Applications.
6
}
7
} catch (error) {
8
// The request failed...
9
}
Copied!
With custom options:
Example:
1
// In custom options you can specify the following parameters: "ordering", "orderBy", "take", "skip"
2
3
const options = {
4
ordering: "descending",
5
orderBy: "name"
6
};
7
8
try {
9
const result = await hat.applications().getAll(options);
10
11
if (result.parsedBody) {
12
// result.parsedBody contains an array of Applications.
13
}
14
} catch (error) {
15
// The request failed...
16
}
Copied!

Get an application with a specific ID

Example:
1
try {
2
const result = await hat.applications().getById("testhatapp");
3
4
if (result.parsedBody) {
5
// result.parsedBody contains the application.
6
}
7
} catch (error) {
8
// The request failed...
9
}
Copied!

Get an application status

Parameters
Type
application
Example:
1
const status = hat.applications().getAppStatus(application);
2
3
console.log(status);
4
// Will print one of 'goto' | 'running' | 'fetching' | 'failing' | 'untouched' | 'update';
Copied!

Generate a Data Plug setup URL

You can generate a URL in order to redirect the user to setup a Data Plug.
Parameters
Type
application
redirect
string
fallback
string
Example:
1
const redirectUrl = "https://myapp.dataswift.io/app/redirect";
2
const fallbackUrl = "https://myapp.dataswift.io/app/fallback";
3
const generatedUrl = hat.applications().getSetupUrl(application, redirectUrl, fallbackUrl);
4
5
console.log(generatedUrl);
6
// Will print: https://testing.hubat.net/#/hatlogin?name=facebook&fallback=https://myapp.dataswift.io/app/fallback&redirect=https://facebook.hubofallthings.com%3Fredirect=https://myapp.dataswift.io/app/redirect
7
8
window.location.href = generatedUrl; // Navigate the user to setup the Data Plug.
Copied!

HAT Data

Response type:
1
interface HatRecord<T> {
2
endpoint: string; // eg. locations
3
recordId: string; // A unique record ID of the record.
4
data: T; // The Data
5
}
Copied!

Write Data

Parameters
Type
namespace
string
endpoint
string
body
object
Response
  • HatRecord\
Example:
1
const namespace = "testhatapp";
2
const endpoint = "locations";
3
const newLocation = {
4
latitude: "51.01",
5
longitude: "52.12"
6
};
7
8
try {
9
const result = await hat.hatData().create(
10
namespace,
11
endpoint,
12
newLocation
13
);
14
15
if (result.parsedBody) {
16
// result.parsedBody contains a HatRecord with the new data.
17
}
18
} catch (error) {
19
// Failed to write data...
20
}
Copied!

Update Data

Parameters
Type
body
Array>
Response:
  • Array>
Example:
1
const location = {
2
endpoint: "testhatapp/locations",
3
recordId: "c14b8f73-157f-40f1-9c77-985d9dea50d2",
4
data: {
5
latitude: "51.01",
6
longitude: "52.12"
7
}
8
};
9
10
location.data.latitude = "49.01";
11
12
const records = [location]; // Array of records to update. In this case we have only one.
13
14
try {
15
const result = await hat.hatData().update(records);
16
17
if (result.parsedBody) {
18
// result.parsedBody contains an array of HatRecords<T> with the updated location data.
19
}
20
} catch (error) {
21
// Failed to update the records...
22
}
Copied!

Delete Data

Parameters
Type
recordIds
Array
Response:
  • A successful response message
Example:
1
const recordIds = ["c14b8f73-157f-40f1-9c77-985d9dea50d2", "d52b8f73-151f-40f1-9c77-932d9dea5daa"];
2
3
try {
4
const result = await hat.hatData().delete(recordIds);
5
6
if (result.parsedBody) {
7
// result.parsedBody contains a successful response message.
8
// In this case the result will be {message: "All records deleted"}.
9
}
10
} catch (error) {
11
// Failed to delete records...
12
}
Copied!

Read Data

The are 2 ways to fetch data:
With default options:
Parameters
Type
namespace
string
endpoint
string
Response
  • Array>
Example:
1
const namespace = "testhatapp";
2
const endpoint = "locations";
3
4
try{
5
const result = await hat.hatData().getAllDefault(namespace, endpoint);
6
7
if (result.parsedBody) {
8
// result.parsedBody contains an Array of HatRecord<Location>.
9
}
10
} catch (error) {
11
// Failed to fetch the data
12
}
Copied!
With custom options:
Example:
1
const options = {
2
ordering: "descending",
3
orderBy: "lastUpdated"
4
};
5
const namespace = "testhatapp";
6
const endpoint = "locations";
7
8
try{
9
const result = await hat.hatData().getAll(namespace, endpoint, options);
10
11
if (result.parsedBody) {
12
// result.parsedBody contains an Array of HatRecords<Location>, ordered by the last updated date.
13
}
14
} catch (error) {
15
// Failed to fetch the data
16
}
Copied!

Data Debits

Get all the Data Debits

The are 2 ways to fetch data debits:
With default options:
Response:
Example:
1
try {
2
const result = await hat.dataDebits().getAllDefault();
3
4
if (result.parsedBody) {
5
// result.parsedBody contains an array of Data Debits.
6
}
7
} catch (error) {
8
// Failed to fetch Data Debits.
9
}
Copied!
With custom options:
Parameters
Type
options
Object
Response:
Example:
1
// In custom options you can specify the following parameters: "ordering", "orderBy", "take", "skip"
2
const options = {
3
ordering: "descending",
4
orderBy: "name"
5
};
6
7
try {
8
const result = await hat.dataDebits().getAll(options);
9
10
if (result.parsedBody) {
11
// result.parsedBody contains an array of Data Debits.
12
}
13
} catch (error) {
14
// Failed to fetch Data Debits.
15
}
Copied!

Get a Data Debit with a specific ID

Parameters
Type
DataDebitId
string
Response: DataDebit: The Data Debit object.
Example:
1
try {
2
const result = await hat.dataDebits().getById("your-data-debit-id");
3
4
if (result.parsedBody) {
5
// result.parsedBody contains the data debit.
6
}
7
} catch (e) {
8
// Failed to get Data Debit by ID...
9
}
Copied!

Get Data Debit values

Parameters
Type
DataDebitId
string
Response:
  • DataDebitValues: The Data Debit values bundle.
Response type:
1
interface DataDebitValues<T> {
2
bundle: { [endpoint: string]: Array<HatRecord<T>> };
3
}
Copied!
Example:
1
try {
2
const result = await hat.dataDebits().getDataDebitValues("your-data-debit-id");
3
4
if (result.parsedBody) {
5
// result.parsedBody contains the bundle.
6
}
7
} catch (error) {
8
// Failed to get Data Debit values...
9
}
Copied!

File API

Upload a File

Parameters
Type
metadata
FileMetadataReq
file
ArrayBuffer | Buffer
fileType
string
Response:
  • FileMetadataRes: The File metadata.
FileMetadataReq type:
1
interface FileMetadataReq {
2
name: string;
3
source: string;
4
tags?: string[];
5
title?: string;
6
description?: string;
7
dateCreated?: number;
8
lastUpdated?: number;
9
}
Copied!
Response type:
1
interface FileMetadataRes {
2
fileId: string;
3
name: string;
4
source: string;
5
tags?: string[];
6
title?: string;
7
description?: string;
8
dateCreated: number;
9
lastUpdated: number;
10
status: FileStatus;
11
contentUrl?: string;
12
contentPublic: boolean;
13
permissions: FilePermissions;
14
}
15
16
interface FileStatus {
17
status: string;
18
size?: number;
19
}
20
21
interface FilePermissions {
22
userId: string;
23
contentReadable: boolean;
24
}
Copied!
Example:
1
try {
2
const meta = {
3
"name": "testFileName",
4
"source": "applicationName",
5
"tags": [
6
"iphone",
7
"photo",
8
]
9
};
10
const file = []; // ArrayBuffer or Buffer
11
12
const result = await hat.files().uploadFile(meta, file, "image/png");
13
14
if (result.parsedBody) {
15
// result.parsedBody contains the File metadata.
16
}
17
} catch (error) {
18
// Failed to upload a file...
19
}
Copied!
Example response:
1
{
2
"fileId": "applicationnametestfilename-5",
3
"name": "testFileName",
4
"source": "applicationName",
5
"dateCreated": "2020-03-04T13:13:37.041Z",
6
"lastUpdated": "2020-03-04T13:13:37.042Z",
7
"tags": [
8
"iphone",
9
"photo"
10
],
11
"status": {
12
"status": "New"
13
},
14
"contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3.eu-west-1.amazonaws.com/testing.hubat.net/applicationnametestfilename-5?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190404T131337Z&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption&X-Amz-Expires=299&X-Amz-Credential=AKIAICFRCZUZIP4PQ64A%2F20190404%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=6e7b112fca980dafe9935e8c849dfdb7e4e49abb658947909ec35c12370247b2",
15
"contentPublic": false,
16
"permissions": [
17
{
18
"userId": "de35e18d-147f-4664-8de7-409abf881754",
19
"contentReadable": true
20
}
21
]
22
}
Copied!

Mark a file as public

Parameters
Type
fileId
string
Response:
  • FileMetadataRes: The File metadata.
Example:
1
try {
2
const result = await hat.files().markFileAsPublic("file-id");
3
4
if (result.parsedBody) {
5
// result.parsedBody contains the File metadata.
6
}
7
} catch (error) {
8
// Failed to mark a file as public...
9
}
Copied!

Mark a file as private

Parameters
Type
fileId
string
Response:
  • FileMetadataRes: The File metadata.
Example:
1
try {
2
const result = await hat.files().markFileAsPrivate("file-id");
3
4
if (result.parsedBody) {
5
// result.parsedBody contains the File metadata.
6
}
7
} catch (error) {
8
// Failed to mark a file as private...
9
}
Copied!

Update File metadata

Parameters
Type
fileId
string
Response:
  • FileMetadataRes: The File metadata.
Example:
1
try {
2
const meta = {
3
"name": "differentFileName",
4
"source": "applicationName",
5
"tags": [
6
"iphone",
7
"photo",
8
"extra tag"
9
]
10
};
11
const result = await hat.files().updateFileParameters("file-id", meta);
12
13
if (result.parsedBody) {
14
// result.parsedBody contains the File metadata.
15
}
16
} catch (error) {
17
// Failed to update file's metadata...
18
}
Copied!

Search Files

Parameters
Type
metadata
FileMetadataReq
Response:
  • Array: An array of File metadata.
Example:
1
try {
2
const meta = {
3
"name": "",
4
"source": "applicationName",
5
"tags": [
6
"iphone",
7
"photo",
8
]
9
};
10
const result = await hat.files().searchFiles(meta);
11
12
if (result.parsedBody) {
13
// result.parsedBody contains an array of File metadata.
14
// The result contains all the files with the tags "iphone" and "photo" with the same source.
15
}
16
} catch (error) {
17
// Failed to search for Files...
18
}
Copied!

Delete File

Parameters
Type
fileId
string
Response:
  • FileMetadataRes: The File metadata.
Example:
1
try {
2
const result = await hat.files().deleteFile("file-id");
3
4
if (result.parsedBody) {
5
// result.parsedBody contains the File metadata.
6
}
7
} catch (error) {
8
// Failed to delete the File...
9
}
Copied!

Generate File content URL

Parameters
Type
fileId
string
Response:
  • string: The URL to the content.
Example:
1
const url = hat.files().getFileContentUrl("file-id");
2
3
console.log(url);
4
// will print:
5
// https://<hat-url>/api/v2.6/files/content/<file-id>>
6
7
// The file will be available in this URL.
8
// Note: if the file is private, will need to pass the authentication token as
9
// a header to access the file.
Copied!

Handling Errors

HAT JS error response:
1
{
2
cause: string, // The cause of the error.
3
message: string, // The message of the error.
4
status: number // When the cause is HAT_API_EXCEPTION you can handle the HTTP response code.
5
}
Copied!
Error Codes:
Cause
Message
Error definitions
HAT_CLIENT_VALIDATION
HAT_DOMAIN_IS_UNDEFINED
hatDomain parameter is required
HAT_CLIENT_VALIDATION
RECORD_IDS_MISSING
recordsIds array parameter is empty or null
HAT_CLIENT_VALIDATION
APPLICATION_NOT_SUPPORTED
application is not supported
HAT_CLIENT_VALIDATION
NOT_AUTHENTICATED
client is not authenticated
HAT_TOKEN_VALIDATION
HAT_TOKEN_IS_NOT_VALID_OR_EXPIRED
Authentication token has expired or is not valid
HAT_TOKEN_VALIDATION
HAT_TOKEN_IS_UNDEFINED
Authentication token is undefined
HAT_TOKEN_VALIDATION
HAT_TOKEN_FAILED_TO_DECODE
Authentication token has failed to decode
HAT_API_EXCEPTION
HTTP_RESPONSE_FAILED
HTTP response failed
HAT_FILE_API_EXCEPTION
FILE_IS_UNDEFINED
File parameter is undefined
HAT_FILE_API_EXCEPTION
FAILED_TO_FETCH_METADATA
Failed to fetch HAT File metadata
HAT_FILE_API_EXCEPTION
FILE_FAILED_TO_UPLOAD
Failed to upload the file to AWS

FAQ

Why do I get CORS errors?

  • Make sure that you set the localhost port to 3000, and you use a testing HAT. eg. testing.hubat.net
  • You are using a production HAT. Localhost is not allowed origin for the production HATs.
  • The secure property in the configuration is set to false. Only if you want to
    run the HAT locally, you have to set this field to false. Otherwise, for the test environment
    it must be true.

I'm getting a 403: Access Denied, how do I fix it?

  • Make sure you use the correct App ID and namespace. Note: The testing App ID
    has a -dev suffix even if it's not displayed correctly in the Developer Portal.
  • In order for an application to fetch the list of applications or a specific application, it needs an extra permission.
  • You are trying to write data to a different namespace.

Why do I get 400: Bad request?

  • Make sure you use the secure configuration correctly. Only if you want to
    run the HAT locally, you have to set this field to false.
  • The HAT doesn't allow to create duplicate data.

License

This work is licensed under the Mozilla Public License Version 2.0. Please read the LICENSE file for further details.
Last modified 1yr ago