Calling CloudBase Resources
In cloud functions, you can conveniently call various CloudBase resources, including databases, cloud storage, and other cloud functions. Node.js cloud functions use @cloudbase/node-sdk, while other languages use HTTP API.
Node.js Cloud Functions
Node.js cloud functions use @cloudbase/node-sdk to call CloudBase resources. In the cloud function environment, no authentication parameters need to be configured, and you can call them directly.
Install SDK
npm install @cloudbase/node-sdk --save
Initialization
Initialize the SDK in cloud functions without configuring authentication parameters such as secretId and secretKey:
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV // Use the default environment ID of the current cloud function
})
Database Calling Example
- Query Data
- Add Data
- Update Data
- Delete Data
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV
})
exports.main = async (event, context) => {
const db = app.database()
// Query a single record
const user = await db.collection('users')
.doc('user-id-123')
.get()
// Query multiple records
const todos = await db.collection('todos')
.where({
completed: false
})
.orderBy('createdAt', 'desc')
.limit(10)
.get()
return {
user: user.data,
todos: todos.data
}
}
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV
})
exports.main = async (event, context) => {
const db = app.database()
const result = await db.collection('todos').add({
title: '学习云开发',
completed: false,
createdAt: new Date()
})
return {
id: result.id,
message: '新增成功'
}
}
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV
})
exports.main = async (event, context) => {
const db = app.database()
// Update a single record
await db.collection('todos')
.doc('todo-id-123')
.update({
completed: true,
updatedAt: new Date()
})
// Batch update
await db.collection('todos')
.where({
completed: false
})
.update({
priority: 'high'
})
return { message: '更新成功' }
}
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV
})
exports.main = async (event, context) => {
const db = app.database()
// Delete a single record
await db.collection('todos')
.doc('todo-id-123')
.remove()
// Batch delete
await db.collection('todos')
.where({
completed: true
})
.remove()
return { message: '删除成功' }
}
Other Language Cloud Functions
Cloud functions in other languages (Python, Java, Go, PHP, etc.) need to use the HTTP API to call CloudBase resources.
HTTP API provides an interface to access CloudBase platform functions through HTTP protocol. For detailed API documentation, please refer to HTTP API Documentation
Example: Python Cloud Function Calling MySQL Database
For obtaining access_token, please refer to Get AccessToken
- Query Data
- Conditional Query
- Sorting and Pagination
import requests
import os
def main_handler(event, context):
# Get environment variables
env_id = os.environ.get('TCB_ENV')
# Query movies in the film table directed by Christopher Nolan
url = f'https://{env_id}.api.tcloudbasegateway.com/v1/rdb/rest/film'
params = {
'director': 'eq.Christopher Nolan',
'select': 'title,director,release_year,duration'
}
headers = {
'Authorization': 'Bearer <access_token>',
'Content-Type': 'application/json'
}
response = requests.get(url, params=params, headers=headers)
if response.status_code == 200:
return {
'code': 0,
'data': response.json()
}
else:
return {
'code': -1,
'message': response.text
}
import requests
import os
def main_handler(event, context):
env_id = os.environ.get('TCB_ENV')
# Query movies released after 2000 with duration not exceeding 120 minutes
url = f'https://{env_id}.api.tcloudbasegateway.com/v1/rdb/rest/film'
params = {
'release_year': 'gte.2000',
'duration': 'lt.120',
'select': 'title,director,release_year,duration'
}
headers = {
'Authorization': 'Bearer <access_token>'
}
response = requests.get(url, params=params, headers=headers)
return response.json()
import requests
import os
def main_handler(event, context):
env_id = os.environ.get('TCB_ENV')
# Query the top 3 movies with the longest duration
url = f'https://{env_id}.api.tcloudbasegateway.com/v1/rdb/rest/film'
params = {
'order': 'duration.desc',
'limit': 3,
'select': 'title,director,duration,release_year'
}
headers = {
'Authorization': 'Bearer <access_token>',
'Prefer': 'count=exact' # Return total count
}
response = requests.get(url, params=params, headers=headers)
# Get total count from response headers
content_range = response.headers.get('content-range', '')
total = content_range.split('/')[-1] if content_range else 0
return {
'data': response.json(),
'total': total
}
💡 Tips:
- In the cloud function environment, you can obtain the environment ID through the environment variable
TCB_ENV, and the access token throughTCB_CONTEXT_KEYS- For languages such as Python, Java, and Go, it is recommended to use HTTP API to call CloudBase resources
- For detailed operators and query parameters, please refer to MySQL Database Query Documentation
- For complete HTTP API interfaces, please refer to HTTP API Documentation