How to write a cloud function
Detailed Explanation of Function Parameters
Each 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 Invocation: Contains parameters passed from the Mini Program side.
- HTTP Request Invocation: Contains HTTP request information (such as request headers, request body, etc.)
- Scheduled Trigger: Contains relevant information about the scheduled trigger
context Object
The context object provides invocation context information to help you understand the runtime environment and invocation method of the function:
- Request ID: The unique identifier for the current invocation
- Invocation Source: Information about the service or client that triggered the function
- Execution Environment: Runtime information of the function
- Mini Program Invocation: Contains parameters passed from the Mini Program side.
Basic Code Example
The following is a simple Node.js cloud function sample that demonstrates how to process 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 Practices
Since instance management is automatically handled by the platform, it is recommended to use async/await patterns for cloud functions instead of 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...
};
Environment Variable Usage
Cloud functions can obtain environment variables via process.env, which is a practice for managing configuration information:
Obtaining Environment Variables
exports.main = async (event, context) => {
// Obtain 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 obtained successfully'
environment: nodeEnv,
};
};
Environment Variable 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(', ')}`);
}
中.翻译流程包括术语表匹配,惯用语表匹配等步骤.用户提供了多个待翻译内容示例,如"// ✅ 推荐:使用 async/await"翻译成"// ✅ Recommended: Use async/await",以及"## 环境变量使用"翻译成"## Environment Variable Usage".这些示例展示了如何保留英文原文中的英文字符和数字序号.
现在用户要求翻译"## 环境变量使用",根据术语表,"腾讯云"应译为"Tencent Cloud",其他部分按云计算规范翻译.惯用语表中"获取"对应"obtain",所以此处"获取"应译为"obtain".普通词汇部分按陈述句翻译,因此"环境变量使用"译为"Environment Variable Usage".
最终输出应严格遵循术语表,保留原文中的英文字符和数字序号,仅输出译文.例如输入"## 环境变量使用",输出"## Environment Variable Usage".
</think><think>
嗯,用户要求定义一种中文翻译英文的方法,输入中文原文后遵循翻译流程,只输出英文译文放在
const config = {
dbUrl: process.env.DATABASE_URL,
apiKey: process.env.API_KEY,
timeout: parseInt(process.env.TIMEOUT) || 5000,
};
return { success: true, config };
};
- Sensitive information (such as API keys, database connection strings) should be passed via environment variables and not hardcoded in the code
- Environment variable values are always strings; perform type conversion when necessary
- It is recommended to set default values for environment variables to enhance code robustness
Time Zone Configuration
The runtime environment of cloud functions maintains UTC time, which is UTC+0, resulting in an 8-hour time difference from Beijing Time.
You can use time processing libraries or packages in your programming language (such as moment-timezone) to recognize UTC time and convert it to Beijing Time in the +8 time zone.
Timezone Handling Example
const moment = require('moment-timezone'); // Must specify and install dependencies 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)
// Obtain current Beijing time
const beijingTime = moment().tz('Asia/Shanghai');
return {
utcTime: new Date().toISOString(),
beijingTime: beijingTime.format(),
timestamp: beijingTime.valueOf(),
};
};
Timezone Handling Practice
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);
};
// Used in business logic
const currentTime = getBeijingTime();
const formattedTime = formatTime();
console.log('Current Beijing Time:', formattedTime);
return {
success: true,
currentTime: formattedTime,
timestamp: currentTime.valueOf(),
};
};
Using the ES Module Specification
In the cloud function Node.js environment, it is not possible to directly adopt the ES Module specification for writing code. The primary reason is that the default entry file supported by cloud functions (index.js) must adhere to the CommonJS specification, and the file name must be 'index.js'. However, Node.js requires that module files conforming to the ES Module specification use the .mjs file extension.
Using ES Module in cloud functions requires creating three core files to form a complete invocation chain: index.js → entry.mjs → util.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. Creating the Cloud Function Entry File index.js
// index.js - Cloud Function Entry File
exports.main = async (event, context) => {
try {
// Dynamically import the 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. Creating the 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. Creating the Business Logic Module util.mjs
// src/util.mjs - Business Logic Module
import cloudbase from '@cloudbase/node-sdk';
const app = cloudbase.init({
env: 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
.mjsfile extension so that Node.js can correctly recognize and process ES Module syntax.
Error Handling and Logging
Error Handling 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 logs
console.error('Function execution failed:', {
error: error.message,
stack: error.stack,
event,
requestId: context.requestId,
});
// Return a user-friendly error message
return {
success: false,
error: error.message,
requestId: context.requestId,
};
}
};
Performance Optimization Suggestions
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 unused variables promptly
batch.length = 0;
// Record processing progress
console.log(`Processed ${Math.min(i + batchSize, event.data.length)}/${event.data.length} data items`);
}
return results;
};