Thanks to visit codestin.com
Credit goes to docs.cloudbase.net

Skip to main content

How to Write Cloud Functions

Function Parameter Details

Every cloud function invocation receives two important objects: event and context.

event Object

The event object contains event data that triggers the cloud function, and its content varies depending on the trigger method:

  • Mini Program Call: Contains parameters passed from the mini program
  • HTTP Request Call: Contains HTTP request information (such as request headers, request body, etc.)
  • Scheduled Trigger: Contains information related to scheduled triggers

context Object

The context object provides invocation context information, helping you understand the function's runtime environment and invocation method:

  • Request ID: Unique identifier for the current invocation
  • Invocation Source: Service or client information that triggered the function
  • Execution Environment: Runtime information of the function
  • User Identity: Identity information of the caller (if available)

Basic Code Example

Here's a simple Node.js cloud function example showing how to handle input parameters and return results:

// index.js - Cloud function entry file
exports.main = async (event, context) => {
// 1. Parse cloud function input parameters
const { a, b } = event;

// 2. Execute business logic
const sum = a + b;

// 3. Return result
return {
sum,
timestamp: Date.now(),
requestId: context.requestId,
};
};

Asynchronous Processing Best Practices

Since instance management is handled automatically by the platform, it's recommended that cloud functions adopt the async/await pattern and avoid using Promise chaining:

exports.main = async (event, context) => {
// ❌ Not recommended: Promise chaining
getList().then((res) => {
// do something...
});

// ✅ Recommended: Use async/await
const res = await getList();
// do something...
};

Installing Third-Party Dependencies

When cloud functions need to use third-party npm packages, you need to install the corresponding dependency packages first. The CloudBase online editor provides convenient dependency management functionality.

Opening the Terminal

In the CloudBase online editor, you can open the terminal in the following ways:

  • Keyboard Shortcut: Use Ctrl + J (Windows/Linux) or command + J (macOS)
  • Menu Operation: Click the "Terminal" button at the top of the editor and select "New Terminal"

Installing Dependencies

Use the npm add command in the terminal to install the required dependency packages.

For example, to install the CloudBase Node.js SDK:

npm add @cloudbase/node-sdk

Installing other commonly used dependency packages:

# Timezone handling library
npm add moment-timezone

# HTTP request library
npm add axios

# Utility library
npm add lodash

Using Dependencies

After installation, you can reference these dependencies in your code:

In the cloud function Node.js environment, you cannot directly write code using the ES Module specification. The main reason is that the default entry file (index.js) supported by cloud functions must follow the CommonJS specification. If you need to use the ES Module specification, please refer to Using ES Module Specification

const cloudbase = require('@cloudbase/node-sdk');

exports.main = async (event, context) => {
// Initialize CloudBase
const app = cloudbase.init({
env: 'your-envid', // Replace with your environment ID
});

const db = app.database();
const collection = db.collection('users');

// Query data
const { data } = await collection.get();

return {
success: true,
count: data.length,
};
};

Upload and Deployment

After completing code writing and dependency installation, choose the appropriate upload method based on your project situation:

  • With Third-Party Dependencies: Click the "Save and Install Dependencies" button
    • The system will automatically upload code files and package.json
    • Automatically execute npm install to install dependencies in the cloud environment
    • Ensure that the cloud function runtime can correctly load all dependency packages
  • Without Third-Party Dependencies: Click the "Save" button
    • Only upload code files
    • Suitable for cloud functions that don't use third-party dependencies
Dependency Management Tips
  • Avoid installing too many unnecessary dependencies to reduce function package size and startup time

Using Environment Variables

Cloud functions can access environment variables through process.env, which is a best practice for managing configuration information:

Getting Environment Variables

exports.main = async (event, context) => {
// Get environment variables
const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;
const nodeEnv = process.env.NODE_ENV || 'development';

// Use environment variables for configuration
const config = {
database: dbUrl,
apiKey: apiKey,
debug: nodeEnv === 'development',
};

return {
message: 'Environment variables retrieved successfully',
environment: nodeEnv,
};
};

Environment Variable Best Practices

exports.main = async (event, context) => {
// Check required environment variables
const requiredEnvVars = ['DATABASE_URL', 'API_KEY'];
const missingVars = requiredEnvVars.filter((varName) => !process.env[varName]);

if (missingVars.length > 0) {
throw new Error(`Missing required environment variables: ${missingVars.join(', ')}`);
}

// Safely use environment variables
const config = {
dbUrl: process.env.DATABASE_URL,
apiKey: process.env.API_KEY,
timeout: parseInt(process.env.TIMEOUT) || 5000,
};

return { success: true, config };
};
Note
  • Sensitive information (such as API keys, database connection strings) should be passed through environment variables and not hardcoded in the code
  • Environment variable values are always string types, perform type conversion when needed
  • It's recommended to set default values for environment variables to improve code robustness

Timezone Settings

The runtime environment of cloud functions maintains UTC time, which is 0 timezone time, with an 8-hour time difference from Beijing time.

You can use language-specific time processing libraries or packages (such as moment-timezone) to recognize UTC time and convert it to +8 zone Beijing time.

Timezone Handling Example

const moment = require('moment-timezone'); // Dependencies must be specified and installed in package.json

exports.main = async (event, context) => {
// javascript date
console.log(new Date()); // 2021-03-16T08:04:07.441Z (UTC+0)
console.log(moment().tz('Asia/Shanghai').format()); // 2021-03-16T16:04:07+08:00 (UTC+8)

// Get current Beijing time
const beijingTime = moment().tz('Asia/Shanghai');

return {
utcTime: new Date().toISOString(),
beijingTime: beijingTime.format(),
timestamp: beijingTime.valueOf(),
};
};

Timezone Handling Best Practices

const moment = require('moment-timezone');

exports.main = async (event, context) => {
// Unified timezone handling function
const getBeijingTime = (date = new Date()) => {
return moment(date).tz('Asia/Shanghai');
};

// Format time output
const formatTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
return getBeijingTime(date).format(format);
};

// Use in business logic
const currentTime = getBeijingTime();
const formattedTime = formatTime();

console.log('Current Beijing time:', formattedTime);

return {
success: true,
currentTime: formattedTime,
timestamp: currentTime.valueOf(),
};
};

Using ES Module Specification

In the cloud function Node.js environment, you cannot directly write code using the ES Module specification. The main reason is that the default entry file (index.js) supported by cloud functions must follow the CommonJS specification, and the file name must be "index.js". However, Node.js requires that module files conforming to the ES Module specification have the .mjs extension.

Using ES Module in cloud functions requires creating three core files, forming a complete call chain: index.jsentry.mjsutil.mjs

Project Structure

cloud-function/
├── index.js # Cloud function entry file (CommonJS)
├── entry.mjs # ES Module entry file
└── src
└── util.mjs # Business logic module, name can be customized

1. Create Cloud Function Entry File index.js

// index.js - Cloud function entry file
exports.main = async (event, context) => {
try {
// Dynamically import ES Module entry file
const { entry } = await import('./entry.mjs');
return await entry(event, context);
} catch (error) {
console.error('Cloud function execution failed:', error);
return {
success: false,
error: error.message,
requestId: context.request_id
};
}
};

2. Create ES Module Entry File entry.mjs

// entry.mjs - ES Module entry file
import { getUserList } from './src/util.mjs';

/**
* ES Module entry function
* @param {Object} event - Event object
* @param {Object} context - Context object
* @returns {Promise<Object>} Processing result
*/
export const entry = async (event, context) => {
return getUserList(event, context);
};

3. Create Business Logic Module util.mjs

// src/util.mjs - Business logic module
import cloudbase from '@cloudbase/node-sdk';

const app = cloudbase.init({
env: 'your-envid', // Replace with your environment ID
});

const models = app.models;

export const getUserList = async (event) => {
const res = await models.user.list({});

return {
success: true,
data: res,
};
};

💡 Note: ES Module files must use the .mjs extension so that Node.js can correctly recognize and process ES Module syntax.

Error Handling and Logging

Error Handling Best Practices

exports.main = async (event, context) => {
try {
// Parameter validation
if (!event.userId) {
throw new Error('Missing required parameter: userId');
}

// Business logic processing
const result = await processUserData(event.userId);

return {
success: true,
data: result,
};
} catch (error) {
// Log error
console.error('Function execution failed:', {
error: error.message,
stack: error.stack,
event,
requestId: context.requestId,
});

// Return friendly error message
return {
success: false,
error: error.message,
requestId: context.requestId,
};
}
};

Performance Optimization Recommendations

Execution Time Optimization

exports.main = async (event, context) => {
const startTime = Date.now();

try {
// Use parallel processing to improve performance
const promises = event.items.map((item) => processItem(item));
const results = await Promise.all(promises);

const duration = Date.now() - startTime;
console.log(`Function execution time: ${duration}ms`);

return {
success: true,
data: results,
duration,
};
} catch (error) {
console.error('Execution error:', error);
throw error;
}
};

Memory Usage Optimization

exports.main = async (event, context) => {
// Process large data in batches to avoid memory overflow
const batchSize = parseInt(process.env.BATCH_SIZE) || 100;
const results = [];

for (let i = 0; i < event.data.length; i += batchSize) {
const batch = event.data.slice(i, i + batchSize);
const batchResult = await processBatch(batch);
results.push(...batchResult);

// Clean up unnecessary variables promptly
batch.length = 0;

// Log processing progress
console.log(`Processed ${Math.min(i + batchSize, event.data.length)}/${event.data.length} records`);
}

return results;
};