Using the SDK
Requirements
The currently supported versions of Node.js are above 14.
To install Node.js, we recommend to use the Node Version
Manager nvm and follow the
installation instructions.
For example, we might execute:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm i 14
Getting Started
Installation
You can install the Datastore SDK in your project
with npm:
npm install -S @getanthill/datastore
Initialization
And then initialize it with:
import { Datastore } from '@getanthill/datastore';
const datastore = new Datastore({
baseUrl: 'http://localhost:3001',
token: 'token',
});
where baseURL is the URL on which your Datastore instance
is listening on and token is the API Access Token which
as defined in the
configuration.
Check the connectivity
To check that the baseUrl is correctly configured, you
can perform a request on the /heartbeat with:
import { Datastore } from '@getanthill/datastore';
const datastore = new Datastore({
baseUrl: 'http://localhost:3001',
token: 'token',
});
async function main() {
const { data: heartbeat } = await datastore.heartbeat();
console.log(heartbeat);
// { "state": "up" }
}
Usage
The SDK is a helper to request the Restful API of the Datastore but you can obviously still invoke the API without it.
Now that you can communicate with your instance of your Datastore, you can use the methods available in the SDK.
Playing with find()
Model definition
Let's say that we have the accounts model defined such as:
{
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "Email address",
"example": "john@doe.org",
"format": "email",
}
}
}
Finding all accounts
In order to find all accounts, you should use the find()
method:
async function main() {
const { data: accounts } = await datastore.find('accounts', {});
console.log(accounts);
/**
* [{
* "account_id": "619b5c6cd8ca5e001453ce8f",
* "created_at": "2020-10-01T00:00:00.000Z"
* "updated_at": "2020-10-02T00:00:00.000Z",
* "version": 1,
* "email": "alice@doe.org"
* }, {
* "account_id": "619b5c6cd8ca5e001453ce8a",
* "created_at": "2020-10-03T00:00:00.000Z"
* "updated_at": "2020-10-03T00:00:00.000Z",
* "version": 0,
* "email": "bernard@doe.org"
* }]
*/
}
where accounts on line 107 is the model name as registered
during the models initialization and {} the query to send
to the API (here, no constraint applied).
Finding Alice
Now, if you want to find only the accounts having the email
address alice@doe.org, just send the email into the
find() query object:
async function main() {
const { data: accounts } = await datastore.find('accounts', { email: 'alice@doe.org'});
console.log(accounts);
/**
* [{
* "account_id": "619b5c6cd8ca5e001453ce8f",
* "created_at": "2020-10-01T00:00:00.000Z"
* "updated_at": "2020-10-02T00:00:00.000Z",
* "version": 1,
* "email": "alice@doe.org"
* }]
*/
}