sbx-lib-ts
v0.0.62
Published
sbx cloud library
Readme
sbx-lib-ts
A lightweight TypeScript client for SBX Cloud APIs. It provides:
- A typed HTTP service (SBXService) to access SBX Cloud endpoints.
- A rich query builder (FindQuery) and typed response models.
- Helpers for authentication, password management, files/folders, email, and cloud scripts.
This document explains how to install the package, configure environment variables, and use SBXService effectively.
Installation
You can install with npm or yarn.
- npm:
- npm install sbx-lib-ts
- yarn:
- yarn add sbx-lib-ts
Requirements:
- Node.js >= 14.17
- TypeScript (recommended)
Environment variables
SBXService uses these environment variables when you use the factory helpers (SBXServiceFactory.withEnv / withToken) or when not providing custom parameters:
- SBX_APP_KEY: Your SBX application key. Example: 00000000-0000-0000-0000-000000000000
- SBX_TOKEN: Bearer token for the user/session.
- SBX_DOMAIN: Numeric domain identifier (e.g., 0 for root).
- SBX_BASE_URL: Base URL to your SBX instance, without the trailing /api (the library appends /api automatically). Example: https://sbxcloud.com
You can load these via dotenv in your application entry point if needed:
- import 'dotenv/config'
Getting started
The package exports:
- SBXServiceFactory: convenient constructors for SBXService
- Model and helper types from ./data/model (e.g., FindQuery, SBXResponse, FieldType, etc.)
Basic usage with environment variables:
- import { SBXServiceFactory, FindQuery } from 'sbx-lib-ts'
- const sbx = SBXServiceFactory.withEnv()
- const query = new FindQuery('your_model')
- .newGroupWithAnd()
- .andWhereIsEqualTo('status', 'ACTIVE')
- const page1 = await sbx.find(query)
Custom configuration:
- const sbx = SBXServiceFactory.withCustom(
- 'YOUR_APP_KEY',
- 'YOUR_TOKEN',
- 0, // domain id
- 'https://sbxcloud.com' // base URL without /api
- )
SBXService overview
SBXService wraps axios with pre-configured headers and baseURL. It expects App-Key and Authorization token, and automatically includes your domain in calls that require it.
Key creation patterns:
- SBXServiceFactory.withEnv(): uses SBX_APP_KEY, SBX_TOKEN, SBX_DOMAIN, SBX_BASE_URL.
- SBXServiceFactory.withToken(token): uses env SBX_APP_KEY/SBX_DOMAIN and provided token.
- SBXServiceFactory.withAppKeyAndToken(appKey, token)
- SBXServiceFactory.withCustom(appKey, token, domain, baseUrl)
Authentication
Login (reads from SBX /user/v1/login):
- const { data } = await sbx.getInstance().get(...) // advanced manual usage
- const res = await sbx.login({ login: 'user', password: 'secret' })
- // Returns the SBX user object and token (SBXUserResponse). On failure: { success: false, error, message }
Validate session (reads from SBX /user/v1/validate):
- const res = await sbx.validateSession()
- // Optionally override domain and Authorization header (e.g., for testing tokens):
- await sbx.validateSession({ domain: 96, authorization: 'Bearer ' })
Change current password:
- await sbx.changeMyPassword('currentPass', 'newPass', userId)
Password reset flow:
- sendPasswordRequest(userEmail, subject, emailTemplate)
- requestChangePassword(userId, code, newPassword)
Validate email availability:
- checkMailAvailable({ email: '[email protected]' })
Data operations
Find records with query builder:
- const q = new FindQuery('contact')
- .newGroupWithAnd()
- .andWhereIsEqualTo('status', 'ACTIVE')
- .setPage(1)
- .setPageSize(50)
- const res = await sbx.find(q)
- // res.results contains typed rows when you specify
Create/Update/Delete:
- create({ row_model: 'contact', rows: [...] })
- update({ row_model: 'contact', rows: [...] })
- delete({ row_model: 'contact', keys: ['key1', 'key2'] })
Find helpers:
- findOne({ ...compiledFindQuery, domain })
- findAll({ ...compiledFindQuery, domain })
Cloud Scripts
Run a cloud script by key:
- const output = await sbx.run('cloudscript-key', { some: 'param' })
Config
Load and retrieve your app config:
- await sbx.loadConfig()
- const cfg = sbx.getConfig()
Files & Folders
- uploadFile({ file_name, file_content }, folderKey)
- file_content should be a data URL or base64 string. The library extracts base64, sets MIME and uploads multipart/form-data.
- downloadFile(key)
- addFolder(name, parentKey)
- deleteFolder(key)
- renameFolder(name, key)
- folderList(key)
- deleteFile(key)
- sendEmail({ to, subject, html, ... })
- sendEmailV2({ ... })
Low-level access
- getInstance(): returns the underlying axios instance for advanced scenarios.
Types
Useful exported types from data/model:
- FindQuery, SBXObject, SBXResponse, SBXFindResponse, SBXUpsert, FieldType, SBXUserResponse, Config, urls
You can import them directly:
- import { FindQuery, SBXResponse, SBXUserResponse } from 'sbx-lib-ts'
Error handling
Most methods return SBXResponse-like structures with success, items/item and error/message fields. Always check success before reading items. The login endpoint returns a user and token payload; in failure cases you will receive success: false with error/message.
Example:
- const res = await sbx.find(q)
- if (!res.success) {
- console.error('Query failed:', res.error || res.message)
- return
- }
- console.log(res.results)
Building and testing (library developers)
- npm run build or yarn build: compiles TypeScript to lib/
- npm test or yarn test: runs jest tests (if present)
- npm run format: formats with Prettier
License
ISC
Full API Reference (model.ts and service.ts)
This section lists all public functions, methods, and key types you can use from the library.
Module: src/data/model.ts
Exports overview:
- Types: SBXObject, SBXMeta, FieldType, ArrayValue, ExpressionValue, LogicalExpression, Operation, LogicalGroup, WhereQuery, Where, SBXRequest, SBXFindRequest, SBXUpsert, SBXDelete, SBXUpsertRequest, SBXDeleteRequest, SBXResponse, SBXUser, SBXUserResponse, SBXFindResponse, SBXProperty, SBXUpsertResponse, JSONValue, Config, ConfigResponse, EmailParams, Folder, FolderContent
- Class: FindQuery
- Constant: urls (all service endpoints)
FindQuery
- constructor(model: string)
- Create a new query for a model name; e.g., new FindQuery('contact').
- newGroupWithAnd()
- Start a new group combined by AND. Use before adding expressions for that group.
- newGroupWithOr()
- Start a new group combined by OR.
AND expressions
- andWhereIsEqualTo(field, value)
- andWhereIsNotNull(field)
- andWhereIsNull(field)
- andWhereIsGreaterThan(field, value)
- andWhereIsLessThan(field, value)
- andWhereIsGreaterOrEqualTo(field, value)
- andWhereIsLessOrEqualTo(field, value)
- andWhereIsNotEqualTo(field, value)
- andWhereItStartsWith(field, value)
- andWhereItEndsWith(field, value)
- andWhereItContains(field, value)
- andWhereIsIn(field, value: ArrayValue)
- andWhereIsNotIn(field, value: ArrayValue)
OR expressions
- orWhereIsEqualTo(field, value)
- orWhereIsNotNull(field)
- orWhereIsNull(field)
- orWhereIsGreaterThan(field, value)
- orWhereIsLessThan(field, value)
- orWhereIsGreaterOrEqualTo(field, value)
- orWhereIsLessOrEqualTo(field, value)
- orWhereIsNotEqualTo(field, value)
- orWhereItStartsWith(field, value)
- orWhereItEndsWith(field, value)
- orWhereItContains(field, value)
- orWhereIsIn(field, value: ArrayValue)
- orWhereIsNotIn(field, value: ArrayValue)
Other query builders
- whereWithKeys(keys: string[])
- Use a primary-key based where instead of logical groups.
- fetchModels(models: string[])
- Specify reference fields/models to fetch (forward relations).
- fetchReferencingModels(models: string[])
- Specify reverse relations to fetch.
- setAutowire(fields: string[])
- Define field names to automatically wire from related models when using findAll.
- setPage(page: number)
- setPageSize(limit: number)
- compile(): SBXFindRequest
- Build the request payload; typically used internally by SBXService.find / findAll.
Notes
- Default page is 1 and size is 100 if not set.
- Grouping: call newGroupWithAnd/Or before adding and/or expressions to that group.
- Text helpers (starts/ends/contains) translate to LIKE queries under the hood.
Module: src/data/service.ts
SBXService class
- constructor(appKey: string, token: string, domain: number, debug = false, baseUrl?: string)
- You normally use SBXServiceFactory helpers instead of calling constructor directly.
Data operations
- find<T = SBXObject>(req: SBXFindRequest): Promise<SBXFindResponse>
- findOne<T = SBXObject>(body: SBXFindRequest): Promise<SBXFindResponse>
- Executes a single page find; returns the raw response.
- findAll<T = SBXObject>(body: SBXFindRequest): Promise<SBXFindResponse>
- Paginates through all records, merges results, and performs autowire if configured.
- create(req: SBXUpsert): Promise
- update(req: SBXUpsert): Promise
- delete(req: SBXDelete): Promise
Cloud scripts
- run<Response = any>(key: string, params?: Record<string, JSONValue>, test = false): Promise
Configuration
- loadConfig(): Promise
- Loads app config (models and properties) into the service instance.
- getConfig(): Config | undefined
Authentication & user
- login(params: { login: string; password: string }): Promise<SBXResponse>
- validateSession(opts?: { domain?: number; authorization?: string }): Promise<SBXResponse>
- sendPasswordRequest(userEmail: string, subject: string, templateKey: string): Promise
- requestChangePassword(userId: string, userCode: string, newPassword: string): Promise
- changeMyPassword(currentPassword: string, newPassword: string, userId: string): Promise
- checkMailAvailable(params: { email: string }): Promise<SBXResponse<{ available: boolean }>>
Files & folders
- uploadFile<Response = any>(data: { file_name: string; file_content: string }, folderKey?: string): Promise<SBXResponse>
- Accepts base64 or data URL in file_content; determines MIME automatically and uploads multipart/form-data.
- downloadFile<Response = any>(key: string): Promise<AxiosResponse>
- addFolder<Response = any>(folderName: string, parentKey?: string): Promise<SBXResponse>
- deleteFolder<Response = any>(key: string): Promise<SBXResponse>
- folderList<Response = any>(key: string): Promise<SBXResponse>
- renameFolder<Response = any>(folderName: string, key: string): Promise<SBXResponse>
- deleteFile<Response = any>(key: string): Promise<SBXResponse>
- sendEmail<Response = any>(data: EmailParams): Promise<SBXResponse>
- sendEmailV2<Response = any>(data: EmailParams): Promise<SBXResponse>
Utilities
- getInstance(): AxiosInstance
- Access the underlying axios instance for custom calls.
- setMultidomainEnvs(domain: number, appKey: string, token: string): void
- Reconfigure the instance for a different domain, appKey and token (useful in multi-tenant apps).
SBXServiceFactory helpers
- withEnv(): SBXService
- Uses SBX_APP_KEY, SBX_TOKEN, SBX_DOMAIN (and SBX_BASE_URL if present).
- withToken(token: string): SBXService
- Uses env SBX_APP_KEY and SBX_DOMAIN.
- withAppKeyAndToken(appKey: string, token: string): SBXService
- withCustom(appKey: string, token: string, domain: number, baseUrl?: string): SBXService
- multidomain(baseUrl: string): SBXService
- Creates a service without initial credentials so you can call setMultidomainEnvs per-tenant.
Examples
Find all active contacts with autowire
- const q = new FindQuery('contact')
- .newGroupWithAnd()
- .andWhereIsEqualTo('status', 'ACTIVE')
- .setAutowire(['owner', 'account'])
- const sbx = SBXServiceFactory.withEnv()
- const res = await sbx.findAll(q.compile())
- if (res.success) console.log(res.results)
Upload a file to a folder
- const base64 = 'data:image/png;base64,iVBORw0KGgoAAA...'
- await sbx.uploadFile({ file_name: 'logo.png', file_content: base64 }, 'FOLDER_KEY')
Run a cloud script
- const out = await sbx.run('my-cloud-script', { userId: '...' })
Caveats
- Always check res.success before using data from SBXResponse.
- Base URL: pass baseUrl without /api; the library appends /api automatically.
- Pagination: findAll paginates until all pages are merged. Use find for a single page.
