Skip to content

@singlebase/singlebase-js

The Singlebase JavaScript SDK is the primary way of interacting with your Singlebase project using Javascript/Typescript. It exposes a standard interface for each of the following services:

1. Install ​

Install with NPM

tsx
npm install @singlebase/singlebase-js

Or install with Yarn

tsx
yarn add @singlebase/singlebase-js

Or use as ES module/ESM

tsx
<script type="module">
  import createClient from '//unpkg.com/@singlebase/singlebase-js'
</script>

2. Create Client ​

Get your Public Access Key.

Login to Console > Settings > Access Keys and copy the Public Access Key

tsx
// import the client
import createClient from '@singlebase/singlebase-js'

// API URL and KEY
const API_URL = "https://cloud.singlebaseapis.com/api"
const API_KEY = "[[PROJECT_API_KEY]]"

// Config object
const SBC_CONFIG = {
  api_url: API_URL,
  api_key: API_KEY
}

// create the instance
const singlebase = createClient(SBC_CONFIG)

Now the client singlebase is created, it exposed the major services:

  • collection(collectionName:string)
  • auth
  • storage

Security Notice

To prevent spam or unwanted access or insert, by default collections must be created in the Console.

For storage, you must enable public


3. Usage ​

Having set up the client, it's time to start to use it to access and manipulate the data.

Datastore Collection ​

The collection service gives access to the datastore and all the collections.

QueryCriteriaType ​

The QueryCriteriaType defines all the properties that can be used when query data in a collection

tsx
type QueryCriteriaType = {
  matches: object,
  sort: object|null,
  limit: int,
  offset:int 
  //or 
  page: int,
  per_page: int
}

MutateCriteriaType ​

The MutateCriteriaType defines all the properties that can be used when updating data in a collection

tsx
type MutateCriteriaType = {
  matches: object,
  data: object|[object]
}

ResultType ​

The ResultType defines all the properties that will be returned to the client.

tsx
type ResultType = {
  ok: bool,
  data: object|[object]|null,
  meta: object|null = {
    pagination?: object
  }
  error: object|null
}

Setup ​

tsx

// import sdk
import createClient from '@singlebase/singlebase-js'

// API URL and KEY
const API_URL = "https://cloud.singlebaseapis.com/api"
const API_KEY = "[[PROJECT_API_KEY]]"

// Config object
const SBC_CONFIG = {
  api_url: API_URL,
  api_key: API_KEY
}

// create the instance
const singlebase = createClient(SBC_CONFIG)

Read Data ​


getDoc ​

To get a document by _key from a collection

tsx
getDoc(_key:string) -> Promise<ResultType>

Params:

  • _key (string) - The document _key
tsx
const collectionName = 'articles'
const _key = "xxxxxxxx"
const res = singlebase
  .collection(collectionName)
  .getDoc(_key)

fetch ​

To fetch all documents in a collection using query criteria.

tsx
fetch(criteria:QueryCriteriaType) -> Promise<ResultType>
tsx
const criteria = {
  matches: {
    type: 'blog',
    has_image: true
  },
  page:1,
  limit: 20
}

const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(criteria)
    .fetch()

fetchOne ​

To fetch only one document in a collection using query criteria or document _key.

tsx
fetchOne(criteria:string|QueryCriteriaType) -> Promise<ResultType>
tsx
const _key = "xxxxxxxxx"
const collectionName = 'articles'
const resp = await singlebase
    .collection(collectionName)
    .fetchOne(_key)

count ​

To count

tsx
count() -> Int
tsx
const matches = {}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(matches)
    .count()

Write Data ​


insert ​

To insert one or multiple documents in a collection

tsx
insert(data:object|[object]) -> Promise<ResultType>

*Insert one document ​

To insert a single document, provide a plain old javascript object (POJO), with any arbitrary properties.

tsx
const data:object = {
  title: "Hello world",
  content: "Today is a beautiful day"
}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .insert(data)

*Insert many documents ​

To insert multiple documents, provide an Array of plain old javascript object (POJO), with any arbitrary properties.

tsx
const data:Array = [
  {
    title: "Hello World",
    content: "Today is a beautiful day"
  },
  {
    title: "Something else",
    content: "Lorem ipsum"
  }
]
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .insert(data)

setDoc ​

To update one document using its _key

tsx
setDoc(_key:string, data:object) -> Promise<ResultType>

Params

  • _key (string) - the document key
  • data (object) - the data to update
tsx
const _key = "xxxxxxxxxx"
const data = {
  "views:$incr": true,
  "tags": ['blog', 'life']
}
const collectionName = 'articles'
const res = await singlebase
  .collection(collectionName)
  .setDoc(_key, data)

deleteDoc ​

To delete one document using its _key

tsx
deleteDoc(_key:string) -> Promise<ResultType>

Params

  • _key (string) - the document key
tsx
const _key = "xxxxxxxxxx"
const collectionName = 'articles'
const res = await singlebase
  .collection(collectionName)
  .deleteDoc(_key)

archiveDoc ​

To archive one document using its _key

tsx
archiveDoc(_key:string) -> Promise<ResultType>

Params

  • _key (string) - the document key
tsx
const _key = "xxxxxxxxxx"
const collectionName = 'articles'
const res = await singlebase
  .collection(collectionName)
  .archiveDoc(_key)

update ​

To update documents in a collection using matches

tsx
update(data:object|[object]) -> Promise<ResultType>
tsx
const matches = {}
const data = {}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(matches)
    .update(data)

// alternatively
const res = await singlebase
    .collection(collectionName)
    .update({matches, data})

updateMany ​

To update mutiple documents, where each document contains it's _key

tsx
updateMany(data:[DocumentType,...]) -> Promise<ResultType>
tsx
const data:Array = [
  {
    _key: "xxxxx",
    prop: value,
    ...
  },
  {
    _key: "yyyyy",
    prop: value,
    ...
  }
]

const res = await singlebase
    .collection(collectionName)
    .updateMany(data)

upsert ​

To Update documents if exists based on the matches criteria, otherwise Insert.

tsx
update(data:object|[object]) -> Promise<ResultType>
tsx
const matches:Object = {...}
const insert = {...}
const update = {...}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(matches)
    .upsert({
      insert, 
      update
    })

delete ​

To delete documents in a collection using matches

tsx
delete() -> Promise<ResultType>
tsx
const matches = {...}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(matches)
    .delete()

archive ​

To archive documents in a collection using matches

tsx
archive() -> Promise<ResultType>
tsx
const matches = {...}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(matches)
    .delete()

restore ​

To restore deleted or archived documents in a collection using matches.

tsx
restore() -> Promise<ResultType>
tsx
const matches = {}
const collectionName = 'articles'
const res = await singlebase
    .collection(collectionName)
    .matches(matches)
    .delete()

Auth ​

Auth provides methods to signup, signin, signout and update user account.


createUserWithPassword ​

To signup with email/password combo. We can also provide the display_name of the user along with the aud

tsx
auth.createUserWithPassword({ email, password, display_name, aud }) -> Promise<ResultType>
tsx
const email = "me@email.com"
const password = "[SECUREPASSWORD12345]"
const display_name = "John Doe"

const res = await singlebase
  .auth
  .createUserWithPassword({
    email,
    password,
    display_name
  })

signInWithPassword ​

To signin with email and password

tsx

const email = "me@email.com"
const password = "[SECUREPASSWORD12345]"
const resp = await singlebase
  .auth
  .signInWithPassword({email, password})

signInWithOTP ​

To signin with email and OTP. You must first request the OTP with the intent=signin then provide both the email and OTP to signin.

tsx
const email = "x@y.com"
const otp = "OTP123"

const resp = await singlebase
  .auth
  .signInWithOTP({email, otp})

signOut ​

To signout using the id_token

tsx
auth.signout(id_token) -> Promise<ResultType>
tsx
const res = await singlebase
  .auth
  .signout(id_token)

changeEmail ​

tsx
auth.changeEmail(current_email:string, new_email:string, otp:string) -> Promise<ResultType>
tsx

const email = "me@email.com"

// 1. Request OTP
auth.sendOTP(email, 'change_email')

// 2. Change email
const new_email = "new@email.com"
const otp = "XY123"
auth.changeEmail(email, new_email, otp)

changePassword ​


updateProfile ​

To update the user profile: display_name, phone_number, photo_url

The id_token and refresh_token must be provided.

tsx
auth.updateProfile(payload:object) -> Promise<ResultType>
tsx
payload = {
  id_token,
  refresh_token,
  data: {
    display_name,
    phone_number,
    photo_url
  }
}

const res = await singlebase
  .auth
  .updateProfile(payload)

updateAccount ​

To update the user's account : email, password, username

You must first request the OTP with the intent=$intent then provide both the received OTP to completed the rest of the process.

intents: change_email, change_password, change_username

tsx
auth.updateAccount(payload:dict) -> Promise<ResultType>
tsx
const payload = {
  id_token, 
  intent,
  otp
  email,
  new_email, // the new email when changing email, with intent=change_email
  new_password // the new password when changing password, with intent=change_password
}

const res = await singlebase
  .auth
  .updateAccount(payload)

getSettings ​

To get the auth settings

tsx
auth.getSettings() -> Promise<ResultType>
tsx
const res = await singlebase
  .getSettings()

sendOTP ​

To send a One Time Password to the user's email address with an intent of the following action.

OTP is always combined with subsequent action such as signin, changeEmail etc

tsx
auth.sendOTP(email:str, intent:str, aud:str=null) -> Promise<ResultType>
tsx

const email = "xxxxx@xxxxx.com"
const intent = "signin"

const res = await singlebase
  .auth
  .sendOTP(email, intent)

OAuthConnect ​


getNonce ​

To get a random unique 75 chars nonce value.

Value can be submitted to send OTP

tsx
auth.getNonce() -> Promise<ResultType>
tsx
const nonce:string = await singlebase
  .auth
  .getNonce()

Files Storage ​

File Storage manages files uploaded to your project


upload ​

To upload a new file from the browser.

tsx
file.upload(file:File, opts:{}) -> Promise<ResultType>
tsx
/**
 * HTML
 * <input id="file" type="file" />
 */

const file = document.getElementById("file").files[0];

const res = await singlebase
  .file
  .upload(file, {title: "My Awesome Picture"})

update ​

Update an object by key

tsx
file.update(objectKey:string, data:object) -> Promise<ResultType>
tsx
const objectKey = "xxxxxxxxxx"

const res = await singlebase
  .file
  .update(objectKey, {title: 'More awesome'})

delete ​

Delete an object by key

tsx
file.delete(objectKey:string) -> Promise<ResultType>
tsx
const objectKey = "xxxxxxxxxx"

const { ok } = await singlebase
  .file
  .delete(objectKey)

if (ok) {
  console.log("File delete")
}

getDownloadUrl ​

Get the download url of an object by _key

tsx
file.getDownloadURL(objectKey:string) -> Promise<string|null>
tsx
const objectKey = "xxxxxxxxxx"

const url = await singlebase
  .file
  .getDownloadURL(objectKey)