Skip to content

nearup-io/nodb-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

70 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nodb JS/TS Sdk

Nodb NPM is a wrapper for nodb API. It allows you to do CRUD operations over your Postgres database via API directly. Nodb keeps track of vector embeddings using pgvector so that you can do retrieval-augmented generation (RAG) using vector search. Nodb offers real-time updates using websockets by connecting to the Nodb API and subscribing to changes.

Table of Contents

  1. Installation
  2. Getting Started
  3. Key Concepts
  4. Usage
    1. Creating Your First Application and Environment
    2. Working with Tokens
    3. Writing Entities
    4. Inquiring Data
    5. WebSocket Support
  5. Testing
  6. API Reference

Installation

Nodb supports both ESM and CommonJS modules, allowing you to integrate it seamlessly into your projects using either module system and you can use it with npm, yarn, bun, etc.

First install the NPM package (e.g. with npm, yarn, pnpm, bun):

npm install nodb-js-sdk

Getting Started

To begin using NodbSDK, import the Nodb class:

import Nodb from "nodb-js-sdk";
//OR
const Nodb = require("nodb-js-sdk");

If you're using import you should add "type": "module" to package.json. You need to create an instance of Nodb now:

const nodb = new Nodb({
  baseUrl: "http://localhost:3000",
});

Key Concepts

NodbSDK works with the following hierarchical structure:

  • Application: The top-level container
  • Environments: Belong to an application
  • Entities: Belong to an environment

One application can contain multiple environments, and each environment can contain multiple entities.

Usage

Creating Your First Application and Environment

To create your first application with an environment:

const application = await nodb.createApplication({
  appName: "your-application-name",
  envName: "your-environment-name",
});

If you don't specify an envName a default environment is created for you called dev.

Working with Tokens

After creating an application, you'll receive tokens for both the application and the environment:

// Token for your application (broader permission scope)
const appToken = application.applicationTokens[0].key;

// Token for your environment (limited scope of permissions for the environment)
const envToken = application.environmentTokens[0].key;

Setting Tokens

You can set a token globally for all subsequent operations:

nodb.setToken(appToken);

Alternatively, you can provide tokens individually for each method call. If both a global token and a method-specific token are provided, the method-specific token takes precedence.

Writing Entities

Let's write our first entities. Prepare some data that you'll import:

// seed.ts
type Todo = {
  task: string;
  priority?: "high" | "low";
  completed: boolean;
}

const todos:Todo[] = [
  {
    task: "Finish report",
    priority: "high",
    completed: false,
  },
  {
    task: "Buy groceries",
    completed: false,
  },
  {
    task: "Call mom",
    completed: false,
  },
];

Writing entities is done using writeEntities method for example using todos entity:

const ids = await nodb.writeEntities({
  appName: "your-application-name",
  envName: "your-environment-name",
  entityName: "your-entity-name",
  payload: todos
});

Or with then/catch:

nodb.writeEntities({
  appName: "your-application-name",
  envName: "your-environment-name",
  entityName: "your-entity-name",
  payload: todos
}).then(console.log); // get the ids

Inquiring Data

Let's make a sample inquiry using .inquire method, useful for RAG applications:

const { answer } = await nodb.inquire({
  appName: "your-application-name",
  envName: "your-environment-name",
  inquiry: "Which todo has highest priority?",
});
//Or
nodb.inquire({
  appName: "your-application-name",
  envName: "your-environment-name",
  inquiry: "Which todo has highest priority?",
}).then(console.log);

The response returned from inquire method has the following definition:

{
  answer: "Finishing report has highest priority.";
}

WebSocket Support

Our SDK provides WebSocket support for monitoring write, update, and delete events on your Nodb API. You can easily connect to the WebSocket with the connectToSocket method:

Example usage:

nodb.connectToSocket({
  appName: "your-app-name",
  envName: "your-env-name", // Optional: Listen to all events for an application if omitted.
  socketBaseUrl: "ws://localhost:3000", // Optional: If not provided, we automatically convert the base URL for you.
  token: "yourToken" // Optional: If omitted, we use the previously provided token. An error will be thrown if no token is provided and none has been set before.
})

Upon a successful connection, a message will appear in the console, indicating that you are now connected to the WebSocket. You will start receiving real-time updates about your application or environment.

To close the WebSocket connection, simply call:

nodb.disconnectFromSocket()

With these methods, you can seamlessly integrate WebSocket functionality into your application for real-time updates.

Testing

We are using jest to run e2e tests. You can run them with

npm run test

For testing we have a .env.test file where the only env variable that is specified is:

NODB_BASE_URL=

API Reference

The Nodb class provides methods for interacting with a NoDB (NoSQL Database) backend via HTTP and WebSocket connections. It extends the NodbWebSocket class to support WebSocket functionality.

Constructor

constructor({ token, baseUrl }: NodbConstructor)
  • Parameters:
    • token (optional, string): Authentication token for API requests.
    • baseUrl (string): Base URL for the API endpoints.

Methods

setToken

setToken(token: string): void

writeEntities

async writeEntities(props: BaseAPIProps & PostEntityRequestBody): Promise<string[]>

writeEntity

async writeEntity(props: BaseAPIProps & { payload: EntityBody }): Promise<string>

updateEntities

async updateEntities(props: BaseAPIProps & PatchRequestBody): Promise<string[]>

updateEntity

async updateEntity(props: BaseAPIProps & { payload: EntityBodyWithId }): Promise<string>

replaceEntities

async replaceEntities(props: BaseAPIProps & PatchRequestBody): Promise<string[]>

replaceEntity

async replaceEntity(props: BaseAPIProps & { payload: EntityBodyWithId }): Promise<string>

deleteEntities

async deleteEntities(props: BaseAPIProps): Promise<number>

deleteEntity

async deleteEntity(props: BaseAPIProps & EntityId): Promise<boolean>

getEntity

async getEntity(props: BaseAPIProps & EntityId): Promise<Entity>

getEntities

async getEntities(props: BaseAPIProps): Promise<EntityResponse>

inquire

async inquire(props: Inquiry & Pick<BaseAPIProps, "appName" | "envName" | "token">): Promise<{ answer: string }>

createApplication

async createApplication(props: PostApplicationBody): Promise<PostApplicationResponse>

createEnvironmentInApp

async createEnvironmentInApp(props: PostEnvironmentBody): Promise<PostEnvironmentResponse>

deleteEnvironmentFromApp

async deleteEnvironmentFromApp(props: { appName: string; envName: string; token?: string }): Promise<boolean>

deleteApplication

async deleteApplication(props: { appName: string; token?: string }): Promise<boolean>

createApplicationToken

async createApplicationToken(props: { appName: string; permission: TokenPermissions; token?: string }): Promise<PostApplicationTokenResponse>

createEnvironmentToken

async createEnvironmentToken(props: { appName: string; envName: string; permission: TokenPermissions; token?: string }): Promise<PostEnvironmentTokenResponse>

revokeApplicationToken

async revokeApplicationToken(props: { appName: string; tokenToBeRevoked: string; token?: string }): Promise<boolean>

revokeEnvironmentToken

async revokeEnvironmentToken(props: { appName: string; envName: string; tokenToBeRevoked: string; token?: string }): Promise<boolean>

connectToSocket

connectToSocket(props: { appName: string; envName?: string; token?: string; socketBaseUrl?: string }): void

disconnectFromSocket

disconnectFromSocket(): void