Javascript
@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
npm install @singlebase/singlebase-js
Or install with Yarn
yarn add @singlebase/singlebase-js
Or use as ES module/ESM
<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
// 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
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
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
type MutateCriteriaType = {
matches: object,
data: object|[object]
}
ResultType
The ResultType defines all the properties that will be returned to the client.
type ResultType = {
ok: bool,
data: object|[object]|null,
meta: object|null = {
pagination?: object
}
error: object|null
}
Setup
// 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
getDoc(_key:string) -> Promise<ResultType>
Params:
_key
(string) - The document _key
const collectionName = 'articles'
const _key = "xxxxxxxx"
const res = singlebase
.collection(collectionName)
.getDoc(_key)
fetch
To fetch all documents in a collection using query criteria.
fetch(criteria:QueryCriteriaType) -> Promise<ResultType>
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
.
fetchOne(criteria:string|QueryCriteriaType) -> Promise<ResultType>
const _key = "xxxxxxxxx"
const collectionName = 'articles'
const resp = await singlebase
.collection(collectionName)
.fetchOne(_key)
count
To count
count() -> Int
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
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.
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.
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
setDoc(_key:string, data:object) -> Promise<ResultType>
Params
_key
(string) - the document keydata
(object) - the data to update
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
deleteDoc(_key:string) -> Promise<ResultType>
Params
_key
(string) - the document key
const _key = "xxxxxxxxxx"
const collectionName = 'articles'
const res = await singlebase
.collection(collectionName)
.deleteDoc(_key)
archiveDoc
To archive one document using its _key
archiveDoc(_key:string) -> Promise<ResultType>
Params
_key
(string) - the document key
const _key = "xxxxxxxxxx"
const collectionName = 'articles'
const res = await singlebase
.collection(collectionName)
.archiveDoc(_key)
update
To update documents in a collection using matches
update(data:object|[object]) -> Promise<ResultType>
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
updateMany(data:[DocumentType,...]) -> Promise<ResultType>
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.
update(data:object|[object]) -> Promise<ResultType>
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
delete() -> Promise<ResultType>
const matches = {...}
const collectionName = 'articles'
const res = await singlebase
.collection(collectionName)
.matches(matches)
.delete()
archive
To archive documents in a collection using matches
archive() -> Promise<ResultType>
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.
restore() -> Promise<ResultType>
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
auth.createUserWithPassword({ email, password, display_name, aud }) -> Promise<ResultType>
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
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.
const email = "x@y.com"
const otp = "OTP123"
const resp = await singlebase
.auth
.signInWithOTP({email, otp})
signOut
To signout using the id_token
auth.signout(id_token) -> Promise<ResultType>
const res = await singlebase
.auth
.signout(id_token)
changeEmail
auth.changeEmail(current_email:string, new_email:string, otp:string) -> Promise<ResultType>
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.
auth.updateProfile(payload:object) -> Promise<ResultType>
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
auth.updateAccount(payload:dict) -> Promise<ResultType>
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
auth.getSettings() -> Promise<ResultType>
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
auth.sendOTP(email:str, intent:str, aud:str=null) -> Promise<ResultType>
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
auth.getNonce() -> Promise<ResultType>
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.
file.upload(file:File, opts:{}) -> Promise<ResultType>
/**
* 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
file.update(objectKey:string, data:object) -> Promise<ResultType>
const objectKey = "xxxxxxxxxx"
const res = await singlebase
.file
.update(objectKey, {title: 'More awesome'})
delete
Delete an object by key
file.delete(objectKey:string) -> Promise<ResultType>
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
file.getDownloadURL(objectKey:string) -> Promise<string|null>
const objectKey = "xxxxxxxxxx"
const url = await singlebase
.file
.getDownloadURL(objectKey)