大家好,欢迎来到IT知识分享网。
HarmonyOS–AGC(认证服务/云函数/云存储/云数据库)
文章目录
一、注册华为账号开通认证服务
二、添加项目:*包名要与项目的包名保持一致
三、获取需要的文件
四、创建项目:*包名要与项目的包名保持一致
五、添加json文件
六、加入请求权限
在module.json5文件中添加:"requestPermissions": [{
"name": "ohos.permission.INTERNET"}],
七、加入依赖
// 这三类可以整合为一个,统一使用这几个依赖(合起来的,下面单独分开的) "dependencies": {
"@hw-agconnect/crypto-ohos": "^1.0.10", "@hw-agconnect/function-ohos": "^1.1.2", "@hw-agconnect/auth-ohos": "^1.1.3", "@hw-agconnect/cloudstorage-ohos": "^1.0.10", "@hw-agconnect/api-ohos": "^1.1.2", "@hw-agconnect/base-ohos": "^1.1.2", "@hw-agconnect/core-ohos": "^1.1.2", "@hw-agconnect/credential-ohos": "^1.1.2", "@ohos/agconnect-auth-component": "^1.0.5", "@hw-agconnect/auth-component": "^1.0.0", "@hw-agconnect/cloud": "^1.0.1", "@hw-agconnect/hmcore": "^1.0.1", "long": "5.2.1" } // 认证服务 "dependencies": {
"@hw-agconnect/hmcore": "^1.0.1", "@hw-agconnect/cloud": "^1.0.1", "@hw-agconnect/auth-ohos": "^1.1.3" } // 下面的是端云项目依赖使用的 "dependencies": {
"@hw-agconnect/crypto-ohos": "^1.0.10", "@hw-agconnect/function-ohos": "^1.0.10", "@hw-agconnect/auth-ohos": "^1.0.10", "@hw-agconnect/cloudstorage-ohos": "^1.0.10", "@hw-agconnect/api-ohos": "^1.0.10", "@hw-agconnect/base-ohos": "^1.0.10", "@hw-agconnect/core-ohos": "^1.0.10", "@hw-agconnect/credential-ohos": "^1.0.10", "@ohos/agconnect-auth-component": "^1.0.5", "@hw-agconnect/auth-component": "^1.0.0", "@hw-agconnect/cloud": "^1.0.0", "@hw-agconnect/hmcore": "^1.0.0", "long": "5.2.1" } // 云函数使用 "dependencies": {
"@hw-agconnect/api-ohos": "^1.1.2", "@hw-agconnect/core-ohos": "^1.1.2", "@hw-agconnect/function-ohos": "^1.1.2", "@hw-agconnect/credential-ohos": "^1.1.2", "@hw-agconnect/base-ohos": "^1.1.2", "@hw-agconnect/cloud": "^1.0.0", "@hw-agconnect/hmcore": "^1.0.1" } // 云存储 "dependencies": {
"@hw-agconnect/hmcore": "^1.0.1", "@hw-agconnect/cloud": "^1.0.1" }
八、修改构建配置文件:build-profile.json5
{
"apiType": "stageMode", "showInServiceCenter": true, // 新添加 "buildOption": {
// 新添加:内容 //配置筛选har依赖.so资源文件的过滤规则 "napiLibFilterOption": {
//按照.so文件的优先级顺序,打包最高优先级的.so文件 "pickFirsts": [ "/1.so" ], //按照.so文件的优先级顺序,打包最低优先级的.so 文件 "pickLasts": [ "/2.so" ], //排除的.so文件 "excludes": [ "/3.so" ], //允许当.so重名冲突时,使用高优先级的.so文件覆盖低优先级的.so文件 "enableOverride": true, } }, "buildOptionSet": [ {
"name": "release", "arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": false, "files": [ "./obfuscation-rules.txt" ] } } } }, ], "targets": [ {
"name": "default" }, {
"name": "ohosTest", } ] }
九、集成SDK
导包: import {
initialize } from '@hw-agconnect/hmcore';
// 方式一(不推荐) 导包: import {
initialize } from '@hw-agconnect/hmcore'; async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 根据管理读取文件,根据信息读取里面的数据 try {
let input = await this.context.resourceManager .getRawFileContent('agconnect-services.json') let jsonString = util.TextDecoder.create('utf-8', {
ignoreBOM: true }).decodeWithStream(input, {
stream: false }); initialize(this.context, JSON.parse(jsonString)); console.info('system===>SDK集成成功') } catch (e) {
console.info('system===>SDK集成失败') hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); } } 方式二: // 直接获取json 文件 导包: import {
initialize } from '@hw-agconnect/hmcore'; import json from '../../resources/rawfile/agconnect-services.json' onCreate(want, launchParam) {
// 方式二:引入 try {
initialize(this.context,json ); console.info('system===>SDK集成成功') } catch (err){
console.info('system===>SDK集成失败') } }
十、手机号认证–工具包
import cloud, {
AuthUser, SignInResult, VerifyCodeAction, VerifyCodeResult } from '@hw-agconnect/cloud'; // 手机验证 // class PhoneAgcUtils.ets / * 获取当前登录用户 * */ export function getCurrentUser(): Promise<AuthUser | null> {
return cloud.auth().getCurrentUser() } /* * 获取验证码(登录设置使用,并需要传参使用) * REGISTER_LOGIN: 登录相关使用 * RESET_PASSWORD: 修改密码相关使用 * */ export function phoneGetVerifyCode(action: VerifyCodeAction, phoneNumber: string): Promise<VerifyCodeResult> {
return cloud.auth().requestVerifyCode({
action: action, lang: `zh_CN`, sendInterval: 60, verifyCodeType: {
phoneNumber: phoneNumber, countryCode: '86', kind: `phone` } }) } /* * 验证码登录 * */ export async function phoneSignInByVerifyCode(phoneNumber: string, verifyCode: string, autoCreateUser: boolean = false): Promise<SignInResult> {
// 登录之前要先登出 await logOut() return cloud.auth().signIn({
autoCreateUser: autoCreateUser, // 自己创建用户 credentialInfo: {
kind: 'phone', countryCode: '86', // 区号 phoneNumber: phoneNumber, verifyCode: verifyCode } }) } /* * 密码登录 * */ export async function phoneSignInByPassWord(phoneNumber: string, password: string, autoCreateUser: boolean = false): Promise<SignInResult> {
// 登录之前要先登出 await logOut() return cloud.auth().signIn({
autoCreateUser: autoCreateUser, // 自己创建用户 credentialInfo: {
kind: 'phone', countryCode: '86', // 区号 phoneNumber: phoneNumber, password: password } }) } /* * 验证码和密码登录(全填) * */ export async function phoneSignIn(phoneNumber: string, password: string, verifyCode: string, autoCreateUser: boolean = false): Promise<SignInResult> {
// 登录之前要先登出 await logOut() return cloud.auth().signIn({
autoCreateUser: autoCreateUser, // 自己创建用户 credentialInfo: {
kind: 'phone', countryCode: '86', // 区号 phoneNumber: phoneNumber, password: password, verifyCode: verifyCode } }) } /* * 注册用户 * */ export function phoneCreateUser(phoneNumber: string, password: string, verifyCode: string): Promise<SignInResult> {
return cloud.auth().createUser({
kind: 'phone', phoneNumber: phoneNumber, // 手机号 countryCode: '86', password: password, // 确认密码 verifyCode: verifyCode // 验证码 }) } /* * 修改密码 * 其中user: cloud.auth().getCurrentUser()的结果 * */ export function phoneUpdatePassword(user: AuthUser, password: string, verifyCode: string): Promise<void> {
return user.updatePassword( {
password: password, providerType: 'phone', verifyCode: verifyCode }) } /* * 重置密码/忘记密码 * */ export function phoneResetPassword(phoneNumber: string, password: string, verifyCode: string): Promise<void> {
return cloud.auth().resetPassword({
kind: 'phone', countryCode: '86', phoneNumber: phoneNumber, password: password, verifyCode: verifyCode }) } /* * 登出 * */ export function logOut(): Promise<void> {
return cloud.auth().signOut() } / * 销户 */ export function deleteUser(): Promise<void> {
return cloud.auth().deleteUser() } / * 修改手机号 */ export function phoneUpdatePhone(user: AuthUser, newPhone: string, newVerifyCode: string): Promise<void> {
return user.updatePhone({
phoneNumber: newPhone, countryCode: '86', verifyCode: newVerifyCode, lang: 'zh_CN' }) } / * 账号重认证(密码认证) * 报: 则需要重认证 */ export function phoneUserReauthenticateByPassWord(user: AuthUser, passWord: string): Promise<SignInResult> {
return user.userReauthenticate({
credentialInfo: {
kind: 'phone', countryCode: '86', phoneNumber: user.getPhone().replace('+86-', ''), password: passWord // verifyCode?: string; } }) } / * 账号重认证(验证码认证) * 报: 则需要重认证 */ export function phoneUserReauthenticateByVerifyCode(user: AuthUser, verifyCode: string): Promise<SignInResult> {
return user.userReauthenticate({
credentialInfo: {
kind: 'phone', countryCode: '86', phoneNumber: user.getPhone().replace('+86-', ''), // password: passWord verifyCode: verifyCode } }) } / * 账号重认证(全) * 报: 则需要重认证 */ export function phoneUserReauthenticateByAll(user: AuthUser, passWord: string, verifyCode: string): Promise<SignInResult> {
return user.userReauthenticate({
credentialInfo: {
kind: 'phone', countryCode: '86', phoneNumber: user.getPhone().replace('+86-', ''), password: passWord, verifyCode: verifyCode } }) } / * 匿名/手机关联邮箱(验证码方式) * 可以使用密码--暂未封装函数 * 关联用户或取消关联都必须限定时间在5分钟以内,超时需重新登录或重认证 * * 手机不可以关联手机 * 匿名也是转为实名的操作 */ export function phoneLink(authUser: AuthUser,email:string,emailVerifyCode:string):Promise<SignInResult> {
return authUser.link({
kind: 'email', // password: password, // 给这个关联设置的登录密码 email: email, verifyCode: emailVerifyCode }) } / * 手机取消关联邮箱 * 关联用户或取消关联都必须限定时间在5分钟以内,超时需重新登录或重认证 */ export function phoneUnLink(authUser: AuthUser):Promise<SignInResult> {
return authUser.unlink('email') } / * 保存修改个人信息(名称+头像) */ export function savaPhotoUrl(authUser: AuthUser, displayName: string, photoUrl: string):Promise<void> {
return authUser.updateProfile({
displayName: displayName, photoUrl: photoUrl }) } /* * 匿名登录 */ export function anonymous(): Promise<SignInResult> {
return cloud.auth().signInAnonymously() } //提示信息 export function messageInfo(string: string) {
console.info('system===>', string) } export function messageError(string: string) {
console.error('system===>', string) }
十一、邮箱认证–工具包
import cloud, {
AuthUser, SignInResult, VerifyCodeAction, VerifyCodeResult } from '@hw-agconnect/cloud'; // 邮箱验证 // class EmailAgcUtils.ets / * 获取当前登录用户 * */ export function getCurrentUser(): Promise<AuthUser | null> {
return cloud.auth().getCurrentUser() } /* * 获取验证码(登录设置使用,并需要传参使用) * REGISTER_LOGIN: 登录相关使用/注册 * RESET_PASSWORD: 修改密码相关使用 * */ export function emailGetVerifyCode(action: VerifyCodeAction, email: string): Promise<VerifyCodeResult> {
return cloud.auth().requestVerifyCode({
action: action, lang: `zh_CN`, sendInterval: 60, verifyCodeType: {
kind: 'email', email: email } }) } /* * 验证码登录 * */ export async function emailSignInByVerifyCode(email: string, verifyCode: string, autoCreateUser: boolean = false): Promise<SignInResult> {
// 登录之前要先登出 await logOut() return cloud.auth().signIn({
autoCreateUser: autoCreateUser, // 自己创建用户 credentialInfo: {
kind: 'email', email: email, verifyCode: verifyCode } }) } /* * 密码登录 * */ export async function emailSignInByPassWord(email: string, password: string, autoCreateUser: boolean = false): Promise<SignInResult> {
// 登录之前要先登出 await logOut() return cloud.auth().signIn({
autoCreateUser: autoCreateUser, // 自己创建用户 credentialInfo: {
kind: 'email', email: email, password: password } }) } /* * 验证码和密码登录(全填) * */ export async function emailSignIn(email: string, password: string, verifyCode: string, autoCreateUser: boolean = false): Promise<SignInResult> {
// 登录之前要先登出 await logOut() return cloud.auth().signIn({
autoCreateUser: autoCreateUser, // 自己创建用户 credentialInfo: {
kind: 'email', email: email, password: password, verifyCode: verifyCode } }) } /* * 注册用户 * */ export function emailUCreateUser(email: string, password: string, verifyCode: string): Promise<SignInResult> {
return cloud.auth().createUser({
kind: 'email', email: email, password: password, // 确认密码 verifyCode: verifyCode // 验证码 }) } /* * 修改密码 * 其中user: cloud.auth().getCurrentUser()的结果 * */ export function emailUpdatePassword(user: AuthUser, password: string, verifyCode: string): Promise<void> {
return user.updatePassword( {
password: password, providerType: 'email', verifyCode: verifyCode }) } /* * 重置密码/忘记密码 * */ export function emailUResetPassword(email: string, password: string, verifyCode: string): Promise<void> {
return cloud.auth().resetPassword({
kind: 'email', email: email, password: password, verifyCode: verifyCode }) } /* * 登出 * */ export function logOut(): Promise<void> {
return cloud.auth().signOut() } / * 销户 */ export function deleteUser(): Promise<void> {
return cloud.auth().deleteUser() } / * 修改邮箱 */ export function emailUpdateEmail(user: AuthUser, newEmail: string, newVerifyCode: string): Promise<void> {
return user.updateEmail({
email: newEmail, verifyCode: newVerifyCode, lang: 'zh_CN' }) } / * 账号重认证(密码认证) */ export function emailUserReauthenticateByPassWord(user: AuthUser, passWord: string): Promise<SignInResult> {
return user.userReauthenticate({
credentialInfo: {
kind: 'email', email: user.getEmail(), password: passWord // verifyCode?: string; } }) } / * 账号重认证(验证码认证) */ export function emailUserReauthenticateByVerifyCode(user: AuthUser, verifyCode: string): Promise<SignInResult> {
return user.userReauthenticate({
credentialInfo: {
kind: 'email', email: user.getEmail(), // password: passWord verifyCode: verifyCode } }) } / * 账号重认证(全) */ export function emailUserReauthenticateByAll(user: AuthUser, passWord: string, verifyCode: string): Promise<SignInResult> {
return user.userReauthenticate({
credentialInfo: {
kind: 'email', email: user.getEmail(), password: passWord, verifyCode: verifyCode } }) } / *匿名/邮箱关联手机(验证码方式) * 可以使用密码--暂未封装函数 * * 邮箱不可以关联邮箱 * 匿名也是转为实名的操作 */ export function emailLink(authUser: AuthUser,phoneNumber:string,phoneVerifyCode:string):Promise<SignInResult> {
return authUser.link({
kind: 'phone', countryCode: '86', phoneNumber: phoneNumber, // password?: string; // 给这个关联设置的登录密码 verifyCode:phoneVerifyCode }) } / * 邮箱取消关联手机 */ export function emailUnLink(authUser: AuthUser):Promise<SignInResult> {
return authUser.unlink('phone') } //提示信息 export function messageEmailInfo(string: string) {
console.info('system===>', string) } export function messageEmailError(string: string) {
console.error('system===>', string) }
十二、匿名认证–工具包
/* * 匿名登录 */ export function anonymous(): Promise<SignInResult> {
return cloud.auth().signInAnonymously() }
十三、认证服务FAQ
问题:{
"code":,"message":"third provider is disabled"} 查看服务配置,相关验证是否启动。
十四、云函数
1.AGC中开启云函数 2.创建函数 3.在函数代码---代码文件中编辑并提交,格式见图片:(注意判断) 4.在IDE工具中进行调用此方法,见代码:在开发前要准备环境(认证服务一致): 1.json文件的导入 2.依赖 3.构建文件 4.集成SDK
建造云函数,方式一:
建造云函数,方式二:(创建端云项目)
在TS文件中编辑云函数: 格式: let myHandler = async function (event, context, callback, logger) {
// 获取登录值 let name = '' let passWord = '' try {
if(event.body){
// 这里需要判断,不确定走哪一个 const res = JSON.parse(event.body) name = res.name passWord = res.passWord } else {
name = event.name passWord = event.passWord } // 业务处理 if (name == 'admin' && passWord == '') {
callback({
code: 0, desc: "Success", result:'登录成功' }); } else {
callback({
code: 0, desc: "Success.", result:'账号密码错误' }); } } catch (err){
callback({
code:-1 , desc: "Error", result:"服务器异常" }); } // do something here }; // 导出 export {
myHandler };
编辑完成后,需要上传至云函数
端侧调用方式
导包:import cloud from '@hw-agconnect/cloud' async fun_sum() {
const rep = await cloud.callFunction({
name: 'fun-jisuan', // 函数名 version: '$latest', // 版本 params: {
// 参数 "num1": 3, "num2": 3 } }) console.log('hmlog-->', JSON.stringify(rep.getValue())) this.result1 = rep.getValue().result + ''; }
十五、云存储(云存储方法工具包)
首先还是需要,导入json文件,加入权限,引入依赖,修改构建配置,和认证服务信息一致
注意: 云路径定义格式: myImages名字自定义 let cloudPath = 'myImages/' + (new Date().getTime()) + '.' + path.split(".")[1] // 文件名+后缀 本地文件: localPath
import {
ListParam, ListResult, MetadataComplete, MetadataUpdatable, ProgressEvent, Storage, TransResult } from '@hw-agconnect/cloud/src/main/ets/storage/storage' import cloud from '@hw-agconnect/cloud' import {
photoAccessHelper } from '@kit.MediaLibraryKit' import {
fileIo, picker } from '@kit.CoreFileKit' import {
getContext } from '@hw-agconnect/hmcore/src/main/ets/core' import fs from '@ohos.file.fs'; // 使用方法 private storage:YunCunChu = YunCunChu.initClass() export class YunCunChu {
// 单例 // 私有变量 private static storage: Storage | null = null private static yunCunChu: YunCunChu | null = null // 私有构造 private constructor() {
} // 公开调用 public static initClass(): YunCunChu {
if (YunCunChu.yunCunChu == null) {
YunCunChu.yunCunChu = new YunCunChu() } return YunCunChu.yunCunChu } // 私有初始化实例 private initStorage(): Storage {
if (YunCunChu.storage == null) {
YunCunChu.storage = cloud.storage() } return YunCunChu.storage } / * 图片:获取本地路径 获取的路径的是file:// 开头正常的 */ async getUpLoadFileByImage(): Promise<string> {
try {
// 1. 从相簿中选照片 const options = new photoAccessHelper.PhotoSelectOptions() options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE options.maxSelectNumber = 1 const result = await new photoAccessHelper.PhotoViewPicker().select(options) return result.photoUris[0]; } catch (e) {
throw new Error(e) } } / * 文件:获取本地路径 获取的路径的是file:// 开头正常的 */ async selectDocFile(): Promise<string> {
// 创建文档选择器实例 const docViewPicker = new picker.DocumentViewPicker() // 创建文件选择 const docSelectOptions = new picker.DocumentSelectOptions() // 现在数量 docSelectOptions.maxSelectNumber = 1 try {
const selectRes = await docViewPicker.select(docSelectOptions) return selectRes[0] } catch (e) {
throw new Error(e) } } / * 下载文件存储路径文件夹路径(并校验是否存在,存在先删除) * 使用时,需要加入文件的名称 */ getLocalFileDir(fileName: string): string {
//fileIo 也可以使用 fs替换 let fileDir = getContext().filesDir let file = fileDir + '/' + fileName if (fileIo.accessSync(file)) {
// 判断是否存在 fileIo.unlinkSync(file) //删除 } return file } / * 下载文档读取内容 */ readContent(localPath: string): string {
//fileIo 也可以使用 fs替换 return fileIo.readTextSync(localPath) } / * * 上传函数思路 * 1.实例 * 2.知道本地文件路径 * 3.云路径 * @param localPath * @param cloudPath * @param onUploadProgress 获取进度 * @returns TransResult 也可以获取进度 */ upload(localPath: string, cloudPath: string, onUploadProgress?: (p: ProgressEvent) => void): Promise<TransResult> {
return this.initStorage().upload({
localPath: localPath, cloudPath: cloudPath, onUploadProgress: onUploadProgress }) } / * * 下载函数 * @param localPath 下载函数需要定义本地接收文件 * @param cloudPath 云路径 * @param onUploadProgress 获取进度 * @returns TransResult 也可以获取进度 */ download(localPath: string, cloudPath: string, onUploadProgress?: (p: ProgressEvent) => void): Promise<TransResult> {
return this.initStorage().download({
localPath: localPath, cloudPath: cloudPath, onDownloadProgress: onUploadProgress }) } / * 获取云存储URl (http开头的区分) * 用于回显云存储地址 */ downloadUrl(cloudPath: string): Promise<string> {
return this.initStorage().getDownloadURL(cloudPath) } / * 获取云存储集合(可以实现分页) */ list(listParam?: ListParam): Promise<ListResult> {
return this.initStorage().list(listParam) } / * 设置元数据 * metaData格式:(不允许中文) contentType: contentType, // 链接类型 (图片:"image/jpeg/jpg", 文件:'application/pdf', 文本:text/plain ) cacheControl: "no-store", // 不缓存 contentDisposition: 'attachment;filename=文件名.后缀', // 作为下载显示的文件名 contentEncoding: "identity", // 编码 contentLanguage: "en-US", // 不允许中文,只能英文 customMetadata: { 如:自定义的JSON格式 "fileExt": extName, "fileName": fileName, "desc": desc } */ setMetaData(cloudPath: string, metaData: MetadataUpdatable): Promise<MetadataComplete> {
return this.initStorage().setMetaData({
cloudPath: cloudPath, metaData: metaData }) } / * 获取元数据 * @param cloudPath 云路经 * @returns */ getMetaData(cloudPath: string): Promise<MetadataComplete> {
return this.initStorage().getMetaData(cloudPath) } / * 删除 * @param cloudPath 云路经 * @returns */ delete(cloudPath: string): Promise<void> {
return this.initStorage().delete(cloudPath) } }
十六、云数据库
云数据库的使用方式有三种:
1.直接使用 ,在AGC定义存储区和对象类型,通过cloud.databaseAPI进行调用。—-普通项目或者端云项目
2.在AGC创建云函数和云数据库,也就是相当于进行了解耦,将数据库隐藏在了云函数中: 见方式一。 —-普通项目或者端云项目
3. 第三种和第二种类似,把云函数和云数据库,放到了端云项目中进行去创建。使用方式基本类似。 见方式二。 —-端云项目
云数据库(创建及端则的使用—-直接使用)
首先还是需要,导入json文件,加入权限,引入依赖,修改构建配置,和认证服务信息一致
另外:增加js文件和数据权限的导出
js文件复制到传递的对象文件中
导出的JSON文件和认证的JSON位置保持一致
import cloud from '@hw-agconnect/cloud' import schema from '../../resources/rawfile/schema.json' import {
BookInfo } from '../entry/BookInfo' export default class BookInfoDBHelper {
private zoneName: string = 'QuickStartDome' // 私有类 private static bookInfoDBHelper: BookInfoDBHelper | null = null // 私有构造 private constructor() {
} public static initDBHelper(): BookInfoDBHelper {
if (BookInfoDBHelper.bookInfoDBHelper == null) {
BookInfoDBHelper.bookInfoDBHelper = new BookInfoDBHelper() } return BookInfoDBHelper.bookInfoDBHelper } // 链接 private concat() {
return cloud.database({
objectTypeInfo: schema, zoneName: this.zoneName }) .collection(BookInfo) } / * 变更增加 * @param books */ public upsert(books: BookInfo[] | BookInfo): Promise<number> {
return this.concat().upsert(books) } / * 删除 * @param books * @returns * * 如何调用: *let ids = [{"id":2},{"id":3}] as Record<string,number>[]|Record<string,number> this.bookInfoDBHelper.delete(ids) */ public delete(ids: Record<string, number>[] | Record<string, number>): Promise<number> {
return this.concat().delete(ids) } / * 获取所有数据 * @returns */ public queryAll(): Promise<BookInfo[]> {
return this.concat().query().get() } / * 根据ID查询 * @param value * @returns */ public queryById(value: ResourceStr | number): Promise<BookInfo[]> {
return this.concat().query().equalTo("id", value).get() } / * 根据条件查询 * @param value * @param isLike * @returns * * 其他条件 (链式之间默认:and() 或者需要指明:or()) * .greaterThan() : > * .greaterThanOrEqualTo() :>= * * 存在 and 和 or复杂使用方法: * 使用 .beginGroup() .endGroup() 分别相当于 ( ) * * 排序: order('字段') * 分页:.limit(number) * 第几条至第几条 .limit // (显示数量,跳过前面的行数) */ public queryByPar(value: ResourceStr | number, isLike: boolean = false): Promise<BookInfo[]> {
if (isLike) {
return this.concat().query() .contains("bookName", value) .get() // contains模糊查询 } else {
return this.concat().query() .equalTo("bookName", value) .get() // contains模糊查询 } } / * 分页:查询 * page:当前页 * pageSize:显示数量 */ queryByLimit(page:number,pageSize:number): Promise<BookInfo[]> {
return this.concat().query() .orderByDesc("id") .limit(pageSize,((page-1)*pageSize)) // (显示数量,跳过前面的行数) .get() } }
方式一:创建—>云数据库(云侧+云函数)–端则调用云函数在调用云数据库,使用方式见使用
首先还是需要,导入json文件,加入权限,引入依赖,修改构建配置,和认证服务信息一致
另外:需要 server SDK 和 导出js格式(服务端)–并修改里面的参数并提交至云函数
并且需要结合dome案例: 变更和查询不一致
操作步骤: 1.server SDK 2.导出 :js格式(服务端) 3.下载【[变更](https://communityfile-drcn.op.dbankcloud.cn/FileServer/getFile/cmtyPub/011/111/111/00000000000.811.:000:2800:C801E4A4F7F10B6DE1C5B16C94C12FBE2B1A97F06DE238B291F97DCA.zip?needInitFileName=true)】zip 和 【[查询](https://communityfile-drcn.op.dbankcloud.cn/FileServer/getFile/cmtyPub/011/111/111/00000000000.809.:000:2800:76BF9DAF4F13CF3B3CD1503BDED9D73C0AB2CD15038BC.zip?needInitFileName=true)】zip文件 4.修改zip文件内容 5.当为变更时的zip,记得查看下面的函数,getDataList 和 setMainKey 函数 6.创建云函数,并且端则调用云函数
操作1:
操作2:
操作3: 根据网址下载 【变更】zip 和 【查询】zip文件
操作4: 修改zip文件内容:
4.1:将下载的 server SDK Json文件放入到 zip中的resources中
4.2: 将导出的JS文件放入到文件跟目录下
4.3:修改 zip中的CloudDBZoneWrapper.js 导入对象包,变更配置区域
操作5:当为变更时的zip,记得查看下面的函数,getDataList 和 setMainKey 函数
操作6:创建云函数将下载的zip上传,并且端则调用云函数
方式一:使用—>云数据库(云函数调用云侧格式)
查询
await cloud.callFunction({
name: this.funQuery, params: {
"action": "count", "extraData": {
"equalTo": {
// 当存在多个复杂查询可以设置同级参数 "userAccount": this.user.getUserAccount() }, "target": "id" // 聚合使用 } } })
其中:可以看下载的zip中的handler.js 。传递的参数
- action:用于指定具体查询方式。
- extraData:用于设置不同查询方式下,需要传入的参数。
修改数据
await cloud.callFunction({
name: this.funUpData, params: {
"action": "insert", "extraData": [obj] } })
其中:可以看下载的zip中的handler.js 。传递的参数
- action:用于指定具体查询方式。
- extraData:用于设置不同查询方式下,需要传入的参数。
方式二:创建—>云数据库(云函数+云侧)–端则调用云函数在调用云数据库(端云项目)
云侧引入依赖
"dependencies": {
"@agconnect/database-server":"^1.0.7", "@agconnect/common-server": "^1.1.0", "@agconnect/database": "^1.1.1", "@agconnect/auth-server": "^1.1.0" }
在AGC导出JS对象–备用
在端云项目中创建文件(案例文件在顶部)
方式二:使用—>云数据库(端侧调用云函数–>云数据库)
端侧封装的工具包(3个)
CloudDBRequest 与 CloudFunction 在同一个目录下
CloudDBRequest:
import {
CloudFunction } from './CloudFunction'; import {
ValueType } from '@kit.ArkData'; const TAG = 'cloudDB-->'; // 云函数请求类 export class CloudDBRequest {
private function: CloudFunction |null = null; constructor() {
this.function = CloudFunction.instance(); } / * 调用云函数的接口方法 * @param trigger 云函数名称 * @param operation 云函数操作类型 * @param params 传递给云函数的参数 * @returns {result:[....]} */ async invoke(trigger: string, operation: string,params?: Record<string,ValueType|number[]>,token?:string) {
let result = await this.function!.callWithParams(trigger, operation,params,token); console.log(TAG,'invoke result='+JSON.stringify(result)); return result; } }
CloudFunction :
import cloud from '@hw-agconnect/cloud'; import {
ValueType } from '@kit.ArkData'; import {
FuncParam } from '../common/commonType'; // import Logger from '@ohos.hilog'; // import agconnect from '@hw-agconnect/api-ohos'; // import "@hw-agconnect/core-ohos"; // import "@hw-agconnect/credential-ohos"; // import "@hw-agconnect/function-ohos"; // import { RequestType } from '../common/commonType'; // import { ValueType } from '@kit.ArkData'; // import { Context } from '@kit.AbilityKit'; const TAG = 'cloudDB-->' export class CloudFunction {
static _instance: CloudFunction; static instance() {
if (!CloudFunction._instance) {
CloudFunction._instance = new CloudFunction(); } return CloudFunction._instance; } // 调用云函数 async callWithParams(trigger: string, operation: string, params?: Record<string, ValueType | number[]>, token?: string) {
let ps = params ?? {
}; let body: FuncParam = {
} if (token) {
body = {
"operation": operation, "params": ps, "token":token } } else {
body = {
"operation": operation, "params": ps } } try {
const functionResult = await cloud.callFunction({
name: trigger, params: body }); let result = functionResult.getValue().result as Record<string, ValueType> | Record<string, ValueType>[]; console.log(TAG, 'callWithParams functionResult.getValue()=' + JSON.stringify(functionResult.getValue())); console.log(TAG, 'callWithParams result=' + JSON.stringify(result)); return result; } catch (err) {
console.error(TAG, 'operation ' + operation + 'catch a err: ' + err); return null; } } }
同时可以对调用函数进行封装为枚举
import {
ValueType } from '@kit.ArkData'; export enum Triggers {
born_func = 'born-crud' //云函数 } //云函数操作类型 export enum RequestType {
Insert = 'insert', Query = 'query', Update = 'update', Delete = 'delete', QueryById = 'queryById', QueryByYear = 'queryByYear', QueryComplex = 'queryComplex' } // 云函数工具类 export interface FuncParam {
"operation": string; "params": Record<string, ValueType | number[]>; "token"?: string }
端侧调用方式
private request: CloudDBRequest | null = null; // 无token: let result: Record<string, ValueType | number[]> = await this.request!.invoke( Triggers.born_func, RequestType.Delete, {
"id_list": [born.id] } )as Record<string, ValueType | number[]>; // 有token: token的获取在认证服务中获取,需要用到登录等操作了 this.request!.invoke(Triggers.born_func, RequestType.Query,undefined,token) .then((res) => {
this.bornList.length = 0 this.bornList = res as [] }).catch((err: BusinessError) => {
console.error(JSON.stringify(err)) }) .finally(() => {
this.isLoaded = true })
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/154267.html