Skip to main content

How to invoke other capabilities of TCB CloudBase?

Just like the function code running in the TCB cloud function environment, you can use @cloudbase/node in the function-based cloud hosting environment to invoke other capabilities of TCB, such as database, storage, etc., and of course, also invoke cloud functions.

Since there are certain differences in the runtime environment between Function-based Cloud Hosting and Cloud Functions, slight variations exist in the usage of @cloudbase/node. During SDK initialization, the context parameter must be passed in, as shown below:

import { TcbEventFunction } from '@cloudbase/functions-typings'

export const main: TcbEventFunction<void, string> = function(event, context) {
// Note: Due to dependency on the context parameter, it must be placed inside the `main` function. Do not cache the tcbapp instance, as it has a limited validity period.
const tcbapp = tcb.init({
context: context,
env: 'abc-xyz', // Specifies the environment Id to be invoked. If `env` is not passed, the current environment will be used.
})

tcbapp.uploadFile({cloudPath: '', fileContent: Buffer.from('')})
// ...

return 'done'
}

After passing the context parameter, @cloudbase/node can invoke the relevant capabilities of TCB CloudBase.

Complete Sample Code

import { TcbEventFunction } from '@cloudbase/functions-typings'
import tcb from '@cloudbase/node-sdk'

async function sleep (time: number) {
return await new Promise(resolve => {
setTimeout(() => {
resolve(undefined)
}, time)
})
}

async function uploadFile (tcbapp: tcb.CloudBase) {
const result = await tcbapp.uploadFile({
cloudPath: ' hello world hello world .png',
fileContent: Buffer.from(' hello world hello world ')
})

return await tcbapp.getTempFileURL({ fileList: [result.fileID] })
}

async function runCmdWithCloudbaseNodeSDK (tcbapp: tcb.CloudBase) {
const result = await tcbapp
.database()
.collection('articles')
.where({
_id: 'not-exists-id'
})
.options({ multiple: true })
.update({
'a.b.c': 'a.b.c'
})

return result
}

export const main: TcbEventFunction<void, string> = function(event, context) {
console.log({ event, context })

const tcbapp = tcb.init({
context
})

// Invoke cloud function
try {
const result = await tcbapp.callFunction({
name: 'test',
data: { a: 1 }
})
console.log(result)
} catch (e) {
console.error(e, 'callFunction.error')
return e
}

Uploading Files
try {
const result = await uploadFile(tcbapp)
console.log(result, 'uploadFile.result')
} catch (e) {
console.error(e, 'uploadFile.error')
return e
}

// Access the database
try {
const result = await Promise.all([
runCmdWithCloudbaseNodeSDK(tcbapp)
])
console.log(result, 'run.result')
} catch (e) {
console.error(e, 'e')
return e
}

await sleep(3)

return 'done'
}