【HarmonyOS Next开发】云开发-云数据库(二)

背景


书接上回,实现了云侧和端侧的云数据库创建、更新、修改等操作。这篇文章实现调用云函数对云数据库进行增删改查。

CloudProgram 项目配置

新建函数

在cloudfunctions目录下点击右键,选择新建Cloud Function,输入query-student-function

导入SDK

在终端中切换到当前云函数的目录下

安装SDK

javascript 复制代码
npm install --save @hw-agconnect/cloud-server

导入云数据库类型

选择云数据库需要导出的json文件,右键选择Generate Server Model

选择存放的目录,例子直接放在云函数下,方便调用

可以看到云函数目录下多出一个ts文件

使用云函数调用云数据库

引入 @hw-agconnect/cloud-server 和云数据库对象类。 这个云函数实现的功能是,查询test存储区下,所有的t_Student的数据,并返回查询内容。

javascript 复制代码
import { cloud, CloudDBCollection } from '@hw-agconnect/cloud-server';
import { t_Student } from './t_Student';

let myHandler = async function (event, context, callback, logger) {
  logger.info(event);

  let collection: CloudDBCollection<t_Student> =
    cloud.database({ zoneName: "test" }).collection(t_Student)
  let result = await collection.query().get();

  return callback({
    code: 0,
    desc: "SUCCESS" ,
    result
  });
};

export { myHandler };

上传云函数

在云函数上右键,选择上传到云端。 在AGC上查看是否上传成功

在云端测试云数据库的获取,确定云数据库访问没有问题

Application端配置

1.项目配置

在AGC中的项目项目设置中导出agconnect-services.json文件,并放到项目的src/main/resources/rawfile目录下。

2.安装SDK

在终端中切换到entry目录

在entry的目录下,安装SDK

javascript 复制代码
ohpm install @hw-agconnect/hmcore
ohpm install @hw-agconnect/cloud

这样子显示安装进度,就是安装成功了

然后去oh-package.json5文件中去查看是否安装成功

3.初始化云模块

在EntryAbility.ets项目的onCreate方法下,调用数据库初始化

javascript 复制代码
import { abilityAccessCtrl, AbilityConstant, PermissionRequestResult, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { initialize } from '@hw-agconnect/hmcore';
import servicesJson from '../../resources/rawfile/agconnect-services.json';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    try {
      initialize(this.context, servicesJson);
    } catch (e) {
      hilog.error(0x0000, 'AGConnectError', JSON.stringify(e));
    }
    let AtManager = abilityAccessCtrl.createAtManager();
    AtManager.requestPermissionsFromUser(this.context, ['ohos.permission.READ_MEDIA', 'ohos.permission.MEDIA_LOCATION'])
      .then((data: PermissionRequestResult) => {
        hilog.info(0x0000, 'testTag', '%{public}s', 'request permissions from user success' + data);
      })
      .catch((err: Object) => {
        hilog.error(0x0000, 'testTag', 'Failed to request permissions from user. Cause: %{public}s',
          JSON.stringify(err) ?? '');
      });
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    windowStage.loadContent('pages/Student_Page', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}

4.项目中调用云函数

新建接受返回结果类Student

javascript 复制代码
export class Student {
  public id: number | undefined;
  public name: string | undefined;
  public age: string | undefined;
}

添加引用

javascript 复制代码
import cloud, { FunctionResult } from '@hw-agconnect/cloud';
import { JSON } from '@kit.ArkTS';
import { Student } from '../Model/Student';

UI调用

javascript 复制代码
import cloud, { FunctionResult } from '@hw-agconnect/cloud';
import { JSON } from '@kit.ArkTS';
import { Student } from '../Model/Student';


@Entry
@Component
struct Student_Page {
  @State message: string = 'Hello World';

  build() {
    Column() {
      Text(this.message)
        .fontSize(20)
      Button("查询数据")
        .width("80%")
        .margin({ top: 20 })
        .onClick(async () => {
          let funResult: FunctionResult = await cloud.callFunction({
            name: "query-student-function",
          })
          let student: Student[] = funResult.getValue().result;
          this.message = JSON.stringify(student);
        })
    }
    .height('100%')
    .width('100%')
  }
}

访问前

查询数据

总结

本片文章是想实现,通过云函数去对数据库进行增删改查的操作,类似前后端分离的操作,避免在App直接对云数据库进行操作。

相关推荐
遇到困难睡大觉哈哈5 小时前
HarmonyOS 公共事件机制介绍以及多进程之间的通信实现(9000字详解)
华为·harmonyos
幽蓝计划8 小时前
HarmonyOS NEXT仓颉开发语言实战案例:外卖App
开发语言·harmonyos
伍哥的传说8 小时前
鸿蒙系统(HarmonyOS)应用开发之实现电子签名效果
开发语言·前端·华为·harmonyos·鸿蒙·鸿蒙系统
Georgewu10 小时前
【HarmonyOS】应用开发拖拽功能详解
harmonyos
塞尔维亚大汉11 小时前
鸿蒙内核源码分析(构建工具篇) | 顺瓜摸藤调试鸿蒙构建过程
源码·harmonyos
kumalab13 小时前
HarmonyOS ArkTS卡片堆叠滑动组件实战与原理详解(含源码)
华为·harmonyos
别说我什么都不会14 小时前
【OpenHarmony】鸿蒙开发之xml2jsDemo
harmonyos
HarmonyOS_SDK17 小时前
HarmonyOS免密认证方案 助力应用登录安全升级
harmonyos
zhanshuo19 小时前
鸿蒙操作系统核心特性解析:从分布式架构到高效开发的全景技术图谱
harmonyos
塞尔维亚大汉19 小时前
鸿蒙内核源码分析(编译过程篇) | 简单案例窥视编译全过程
源码·harmonyos