sbx-lib-ts
v0.0.60
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
