New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@workerbase/sdk

Package Overview
Dependencies
Maintainers
3
Versions
114
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@workerbase/sdk

## Installing

  • 0.1.16-beta.8
  • npm
  • Socket score

Version published
Weekly downloads
6
decreased by-64.71%
Maintainers
3
Weekly downloads
 
Created
Source

Workerbase SDK for JavaScript

Installing

Install with npm

npm install @workerbase/sdk

Typescript

Workerbase SDK fully supports typescript with .d.ts files and the types will be maintained in the next releases.

Usage

You can use a default import with typescript

import workerbase from '@workerbase/sdk';

However we recommend using the following syntax with CommonJS to get the typings for autocomplete.

const { Workerbase } = require('@workerbase/sdk');

Authentication setup

You can configure the Workerbase SDK authentication options wiht the auth mehtod:

workerbase.auth({
  url: 'https://myWorkerbaseDomain.workerbase.io',
  token: TOKEN,
});

If you don't use the auth method will use the following env variables as token and url

WB_ACCESS_TOKEN=token
WB_API_URL=url

However if you are using the Workerbase SDK directly in a Workerbase Function, you don't need to use the specify the authentication config as the SDK will directly use the environment variables within the Workerbase Function.

Example

const workerbase = require('@workerbase/sdk');

// Doing simple requests
const updateUserName = async (userId) => {
  const { firstName } = await workerbase.users.get(userId);
  await workerbase.users.update(userId, { firstName: firstName + "v2" });
};

// Working with database items
const createDbAndInsertItems = async () => {
  const database = await workerbase.databases.create({
    name: "test",
    columns: [
      { name: "field1", type: "String" },
      { name: "value", type: "Integer" },
    ],
  });
  await database.items.create({ field1: "abc" }, "item1");
  await database.items.update("item1", { payload: { value: "5" } });
  await database.items.create({ field1: "abcd" }, "item2");
  await database.items.delete("item2");
  await database.items.query({$or: [{field1: "abc"}, {value: {$gt: 4}}]}, {populate: true});
};
};

// Using list response builtin methods
const getAllUserDepartments = () =>
  workerbase.users.list().distinctBy("department");
const getAllUsersWithName = (userLastname) =>
  workerbase.users.list().filterBy({ lastName: userLastname });
const getAllUserDepartmentsWithName = (userLastName) =>
  workerbase.users
    .list()
    .filterBy({ lastName: userLastName })
    .distinctBy("department");

// Invoking a workerbase Function
const invokeFunction = async (functionId) => {
  try {
    return await workerbase.functions.invoke(functionId, { some: "data" });
  } catch (err) {
    console.log(err.logs);
  }
};

Methods

Databases

workerbase.databases.list([listConfig])

workerbase.databases.get(id)

workerbase.databases.create(value)

workerbase.databases.update(id,value)

workerbase.databases.delete(id)

Database Items

Database.items.list([listConfig])

Database.items.get(id)

Database.items.create(value[,externalId])

Database.items.createMany(values)

Database.items.update(id,value)

Database.items.delete(id)

Database.items.query(query, options) (Documentation)

Events

workerbase.events.list([listConfig])

workerbase.events.get(id)

workerbase.events.create(value)

workerbase.events.update(id,value)

workerbase.events.delete(id)

workerbase.events.trigger(id,payload)

Functions

workerbase.functions.list([listConfig])

workerbase.functions.get(id)

workerbase.functions.create(value)

workerbase.functions.update(id,value)

workerbase.functions.delete(id)

workerbase.functions.deploy(id)

workerbase.functions.invoke(id,payload)

Locations

workerbase.locations.list([listConfig])

workerbase.locations.get(id)

workerbase.locations.create(value)

workerbase.locations.update(id,value)

workerbase.locations.delete(id)

workerbase.locations.getPartsByLevel(levelId)

workerbase.locations.getLevels()

Media

workerbase.media.list([listConfig])

workerbase.media.get(id)

workerbase.media.delete(id)

Roles

workerbase.roles.list([listConfig])

workerbase.roles.get(id)

workerbase.roles.create(value)

workerbase.roles.update(id,value)

workerbase.roles.delete(id)

Skills

workerbase.skills.list([listConfig])

workerbase.skills.get(id)

workerbase.skills.create(value)

workerbase.skills.update(id,value)

workerbase.skills.delete(id)

Users

workerbase.users.list([listConfig])

workerbase.users.get(id)

workerbase.users.create(value)

workerbase.users.update(id,value)

workerbase.users.delete(id)

List documentation

ListConfig

interface ListConfig {
  // Starts at 1
  page?: number;

  // Default is 1000
  perpage?: number;

  // field to sort on (not supported by every field)
  sort?: string;

  order?: 'desc' | 'asc';

  // fields to select
  fields?: string;
}

List Response Methods

We added some builtin methods in Workerbase SDK to help you work with the data on the list responses. See the examples above, to see how to use them.

list().filterBy(condition)

Filter the list to keep only the values that match the condition object.

list().distinctBy(field)

Return the list of all distinct values of the specified field.

Database Items Query

Getting started

The Database.items.query() function allows complex queries to Workerbase databases.
The following example explains a simple first query:

The example is done with the database Employee.

Employee database

IDNameEmailBirthdayDepartmentOffice
StringStringStringDateReference
[Department]
Location
1Vannie Douldenvannie@company.com12.11.19881North America / New York
2Marijo Stedemarijo@company.com03.06.19942Europe / Munich
3Jade Plantejade@company.com27.02.19902Europe / Munich

All employees where the birthday is after the 01.01.1989 and the name ends on Stede should be queried.

const EmployeeDB = async workerbase.databases.get("Employee");
const result = await EmployeeDB.items.query({
  Birthday: {
    $gt: "01.01.1989"
  },
  Name: {
    $like: "%Stede"
  }
})

The result variable will contain the employee Marijo Stede.

[
  {
    "_id": "634fc1e9d64ce49dd554c2db",
    "meta": {
      "createdAt": "2022-10-19T09:22:49.782Z",
      "updatedAt": "2022-10-19T09:27:50.733Z"
    },
    "database": "634fbc5cd64ce49dd554bdb0",
    "payload": {
      "Name": "Marijo Stede",
      "Email": "marijo@company.com",
      "Birthday": "1994-06-03T00:00:00.000Z",
      "Department": "634fbc8dd64ce49dd554bde6",
      "Office": "634fc1825025ac5347b21ffc"
    },
    "deleted": false,
    "externalId": "2"
  }
]

Advanced features of the Database.items.query() function are described in the sections Query Operators, Pagination, Sorting, Population, Nested Property Queries

Before looking into advanced features we recomment to review the Typings Definition of the query function.

Typings Definition

type QueryFunction = (query: Query, options: ListOptions): Promise<DatabaseItem[]>

type Query = Record<QueryOperator, string | number | boolean | Query>;

enum QueryOperator {
  EQ = '$eq',
  NE = '$ne',
  GT = '$gt',
  GTE = '$gte',
  LT = '$lt',
  LTE = '$lte',
  IN = '$in',
  NIN = '$nin',
  EXISTS = '$exists',
  AND = '$and',
  OR = '$or',
  LIKE = '$like',
  NOT_LIKE = '$notLike',
}

interface ListOptions {
  page?: number; // Starts at 1
  perpage?: number;
  sort?: string;
  order?: 'desc' | 'asc';
  populate?: boolean;
}

interface DatabaseItem {
  _id: string;
  externalId?: string;
  payload: ItemPayload;
}

type ItemPayload = Record<string, any>;

Query Operators

The following query operators are supported.

enum QueryOperator {
  // "equals"
  EQ = '$eq',

  // "not equals"
  NE = '$ne',

  // "greater than"
  GT = '$gt',

  // "greater than or equals"
  GTE = '$gte',

  // "less than"
  LT = '$lt',

  // "less than or equals"
  LTE = '$lte',

  // "in"
  // Expects a value to be in an array of values.
  // Example: Get all employees whose name is in an array with values
  // "Vannie Doulden" and "Jade Plante".
  // Query: { Name: { $in: [ "Vannie Doulden", "Jade Plante" ] } }
  IN = '$in',

  // "not in"
  // Expects a value not in an array of values.
  NIN = '$nin',

  // "exists"
  // Checks whether a value is defined.
  // Example: Get all employees where Department is not defined.
  // Query: { Department: { $exists: false } }
  EXISTS = '$exists',

  // "and"
  // Expects multiple conditions to be true.
  // Example: Get all employees whose name is
  // "Jade Plante" and where Department is "Product Management".
  // Query:
  // { $and: [
  //   { Name: "Jade Plante" },
  //   { Department: "Product Management" }
  // ]}
  AND = '$and',

  // "or"
  // Expects one of the conditions to be true
  // Example: Get all employees where Department is
  // either "Engineering" or "Product Management".
  // Query
  // { $or: [
  //    { Department: "Engineering" },
  //    { Department: "Product Management" }
  // ]}
  OR = '$or',

  // "like"
  // Expects a column of type string to match a pattern.
  // Patterns can include the wildcards "%" and "_":
  //  => "%" stands for zero or more arbitrary characters.
  //  => "_" stands for one arbitrary characters.
  // Example: Get all employees where the Name starts with "Jade".
  // Query: { Name: { $like: "Jade%" } }
  LIKE = '$like',

  // "not like"
  // Expects a column of type string not to match a pattern.
  NOT_LIKE = '$notLike',
}

Pagination

The result of the query function can be paginated with the page and perpage properties of the options parameter.

type QueryFunction = (query: Query, options: ListOptions): Promise<DatabaseItem[]>

interface ListOptions {
  page?: number; // Starts at 1
  perpage?: number;
  sort?: string;
  order?: 'desc' | 'asc';
  populate?: boolean;
}

Example: If the database Employee contains 100 items, the last 10 items (91-100) can be requested with the following query.

const EmployeeDB = async workerbase.databases.get("Employee");
const result = await EmployeeDB.items.query({}, { page: 10, perpage: 10 });

Sorting

Items in the result can be sorted with the sort and order properties of the options parameter.

Example: In order to sort items from the Employee database by their age starting with the oldest one, the following query has to be run.

const EmployeeDB = async workerbase.databases.get("Employee");
const result = await EmployeeDB.items.query({}, { sort: 'Birthday', order: 'desc' });

Population

Databases Items in Workerbase can have references to other Database Items and to User, Role and Location items in the platform. Those references can be directly included into the result by adding { populate: true } to the options parameter.

Example: The Department column of the Employee database is of type Reference and points to the database Department. Furthermore the Employee database has a column Office which is of type Location and points to locations in the Workerbase platform.

Employee database

IDNameEmailBirthdayDepartmentOffice
StringStringStringDateReference
[Department]
Location
1Vannie Douldenvannie@company.com12.11.19881North America / New York
2Marijo Stedemarijo@company.com03.06.19942Europe / Munich
3Jade Plantejade@company.com27.02.19902Europe / Munich

Department database

IDNameHeadcount
StringStringNumber
1Product Management10
2Engineering25

The employee Vannie Doulden is queried with the { populate: true } option, which includes the references Department and Location as objects into the result.

When the { populate: true } option is not set, the IDs of the references Department and Location are added instead of objects to the result.

const EmployeeDB = async workerbase.databases.get("Employee");
const result = await EmployeeDB.items.query({ Name: 'Vannie Doulden' }, { populate: true });

The result variable will contain the employee Vannie Doulden with populated references.

[
  {
    "_id": "634fc1b3d64ce49dd554c24c",
    "meta": {
      "createdAt": "2022-10-19T09:21:55.713Z",
      "updatedAt": "2022-10-19T09:22:24.916Z"
    },
    "database": "634fbc5cd64ce49dd554bdb0",
    "payload": {
      "Name": "Vannie Doulden",
      "Email": "vannie@company.com",
      "Birthday": "1988-11-12T00:00:00.000Z",
      "Department": {
        "_id": "634fbc85d64ce49dd554bdd1",
        "meta": {
          "createdAt": "2022-10-19T08:59:49.755Z",
          "updatedAt": "2022-10-19T09:00:04.742Z"
        },
        "database": "634fbc75d64ce49dd554bdc2",
        "payload": {
          "Name": "Product Management",
          "Headcount": 10
        },
        "deleted": false,
        "externalId": "1"
      },
      "Office": {
        "_id": "634fc1905025ac5347b22020",
        "externalId": "649f9110-4f8f-11ed-967c-0b922c03bae6",
        "name": "North America / New York"
      }
    },
    "deleted": false,
    "externalId": "1"
  }
]

Nested Property Queries

In order to filter on references of items, conditions on nested properties have to be added to the query parameter. Nested properties are specified by adding $ in the beginning and end of a path i.e. $Office.Name$.

Please keep in mind that nested property queries can only be used when { populate: true } is added to the options parameter.

Example: All employees whose Department has a Headcount less than 20 should be queried. The example is based on the data shown in the section Population.

const EmployeeDB = async workerbase.databases.get("Employee");
const result = await EmployeeDB.items.query({ "$Department.Headcount$": { $lt: 20 } }, { populate: true });

The result variable will contain the employee Vannie Doulden.

[
  {
    "_id": "634fc1b3d64ce49dd554c24c",
    "meta": {
      "createdAt": "2022-10-19T09:21:55.713Z",
      "updatedAt": "2022-10-19T09:22:24.916Z"
    },
    "database": "634fbc5cd64ce49dd554bdb0",
    "payload": {
      "Name": "Vannie Doulden",
      "Email": "vannie@company.com",
      "Birthday": "1988-11-12T00:00:00.000Z",
      "Department": {
        "_id": "634fbc85d64ce49dd554bdd1",
        "meta": {
          "createdAt": "2022-10-19T08:59:49.755Z",
          "updatedAt": "2022-10-19T09:00:04.742Z"
        },
        "database": "634fbc75d64ce49dd554bdc2",
        "payload": {
          "Name": "Product Management",
          "Headcount": 10
        },
        "deleted": false,
        "externalId": "1"
      },
      "Office": {
        "_id": "634fc1905025ac5347b22020",
        "externalId": "649f9110-4f8f-11ed-967c-0b922c03bae6",
        "name": "North America / New York"
      }
    },
    "deleted": false,
    "externalId": "1"
  }
]

FAQs

Package last updated on 04 May 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc