
回复
在鸿蒙生态系统中,端云一体化开发已成为构建现代化应用的核心能力。本文记录了我使用ArkTS语言实现端云一体化功能的学习历程,涵盖云认证、云存储、云数据库和云函数四大核心模块。
随着鸿蒙生态的快速发展,应用对云端能力的需求日益增长。传统开发方式需要自行搭建后端服务,而鸿蒙的端云一体化方案提供了一站式解决方案:
核心架构
[HarmonyOS设备] ←→ [AGConnect SDK] ←→ [AppGallery Connect服务]
import agconnect from '@hw-agconnect/core-ohos';
import auth from '@hw-agconnect/auth-ohos';
// 应用启动时初始化
agconnect.instance().init(context);
// 华为账号登录
async function huaweiSignIn() {
try {
const service = auth.getInstance().getAuthService();
const user = await service.signIn();
console.log(`登录成功: ${user.getUid()}`);
} catch (err) {
console.error(`登录失败: ${err.message}`);
}
}
// 匿名登录
async function anonymousSignIn() {
const service = auth.getInstance().getAuthService();
const user = await service.signInAnonymously();
}
// 获取当前用户
function getCurrentUser() {
return auth.getInstance().getCurrentUser();
}
// 退出登录
async function signOut() {
const service = auth.getInstance().getAuthService();
await service.signOut();
}
auth.getInstance().onAuthStateChanged((user) => {
if (user) {
console.log('用户已登录:', user.getUid());
} else {
console.log('用户已退出');
}
});
import storage from '@hw-agconnect/storage-ohos';
const storageInstance = storage.getInstance();
// 上传文件
async function uploadFile(localPath: string, cloudPath: string) {
const reference = storageInstance.reference(cloudPath);
const uploadTask = reference.putFile(localPath);
uploadTask.on('progress', (snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log(`上传进度: ${progress.toFixed(2)}%`);
});
await uploadTask;
console.log('上传完成');
}
// 下载文件
async function downloadFile(cloudPath: string, localPath: string) {
const reference = storageInstance.reference(cloudPath);
const downloadTask = reference.getFile(localPath);
downloadTask.on('progress', (snapshot) => {
// 处理下载进度
});
await downloadTask;
}
// 获取文件URL
async function getFileUrl(cloudPath: string) {
const reference = storageInstance.reference(cloudPath);
return await reference.getDownloadURL();
}
// 删除文件
async function deleteFile(cloudPath: string) {
const reference = storageInstance.reference(cloudPath);
await reference.delete();
}
@Class
class Product {
id?: string;
name?: string;
price?: number;
category?: string;
createdAt?: Date;
}
import clouddb from '@hw-agconnect/clouddb-ohos';
// 初始化云数据库
async function initCloudDB() {
const cloudDB = clouddb.getInstance();
await cloudDB.createObjectType(clouddb.ObjectTypeInfoHelper.getObjectTypeInfo(Product));
const config = new clouddb.CloudDBZoneConfig('ProductZone');
return await cloudDB.openCloudDBZone(config);
}
// 添加数据
async function addProduct(zone: clouddb.CloudDBZone, product: Product) {
product.id = generateId(); // 自定义ID生成逻辑
product.createdAt = new Date();
await zone.executeUpsert(product);
}
// 查询数据
async function queryProducts(zone: clouddb.CloudDBZone, category?: string) {
let query = clouddb.CloudDBZoneQuery.where(Product)
.orderByDesc('createdAt');
if (category) {
query = query.equalTo('category', category);
}
const snapshot = await zone.executeQuery(query);
return await snapshot.getSnapshotObjects();
}
// 删除数据
async function deleteProduct(zone: clouddb.CloudDBZone, productId: string) {
const product = new Product();
product.id = productId;
await zone.executeDelete(product);
}
import cloudfunction from '@hw-agconnect/function-ohos';
async function callCloudFunction(functionName: string, data: Object) {
try {
const response = await cloudfunction.getInstance()
.wrap(functionName)
.setBody(data)
.run<{ code: number; message: string; data?: any }>();
if (response.code === 0) {
return response.data;
} else {
throw new Error(response.message);
}
} catch (err) {
console.error('云函数调用失败:', err);
throw err;
}
}
// 调用支付云函数
async function makePayment(orderId: string, amount: number) {
return await callCloudFunction('payment', {
orderId,
amount,
currency: 'CNY'
});
}
// 调用天气查询云函数
async function getWeather(city: string) {
return await callCloudFunction('getWeather', { city });
}
1、统一初始化:所有云服务使用前必须初始化AGConnect
agconnect.instance().init(context);
2、错误处理:所有云操作都应添加try-catch块
try {
// 云操作
} catch (err) {
// 错误处理
}