文档开发者中心
我的

云开发之多端同步你的用户数据

浏览109发布于2026-05-28 09:00山东

目前使用了云开发的多种服务,云存储、云托管,既省了买服务器的钱,还能实现cdn,何乐而不为呢?

今天说云存储

存储用户的数据一直是服务器该干的活,现在有了华为的云开发,不用买服务器拉,多端同步用户的数据变得傻瓜化。

首先在项目的开发与服务中开通云存储

1.设置云实例和安全策略

cke_7199.png

2.按照顺序开发

3.其他步骤真的没什么难度,这里重点想讲下关于用户跟用户的数据绑定的问题

开发者可以使用AGC认证服务SDK获取AuthProvider,或者使用华为账号服务Access Token接口自定义AuthProvider。

我推荐大家使用AGC认证服务

步骤如下

3.1 增加依赖

收起
自动换行
深色代码主题
复制
"dependencies": {
    "@hw-agconnect/auth": "^1.0.5"
  },

3.2 EntryAbility.ets增加初始化

收起
自动换行
深色代码主题
复制
private initCloudAuth(): void {
    try {
      const file = this.context.resourceManager.getRawFileContentSync('agconnect-services.json');
      const json: string = buffer.from(file.buffer).toString();
      auth.init(this.context, json);
      hilog.info(DOMAIN, TAG, 'AGC auth initialized');
    } catch (error) {
      const err = error as BusinessError;
      hilog.error(DOMAIN, TAG, `Failed to init AGC auth, code: ${err.code}, message: ${err.message}`);
    }
  }
收起
自动换行
深色代码主题
复制
 private async initCloudSyncWithoutLoginPage(): Promise<void> {
    try {
      const user = await auth.getCurrentUser();
      if (user === null) {
        await auth.signIn({
          autoCreateUser: true,
          credentialInfo: { 'kind': 'hwid' }
        });
      }
    } catch (error) {
      const err = error as BusinessError;
      hilog.error(DOMAIN, TAG, `Silent auth failed, code: ${err.code}, message: ${err.message}`);
    }

    try {
      await CloudDB.syncDbOnStartup();
    } catch (error) {
      const err = error as BusinessError;
      hilog.error(DOMAIN, TAG, `Cloud sync startup failed, code: ${err.code}, message: ${err.message}`);
    }
  }

3.3 需要的工具类来上传和下载文件

收起
自动换行
深色代码主题
复制
import { BusinessError, request } from '@kit.BasicServicesKit'
import { cloudCommon, cloudStorage } from '@kit.CloudFoundationKit'
import { hilog } from '@kit.PerformanceAnalysisKit'
import { fileIo as fs } from '@kit.CoreFileKit'
import auth from '@hw-agconnect/auth'
import appDB, { AppDB } from '../db/AppDB'

const DOMAIN = 0x0000
const TAG = 'CloudDB'
const STORAGE_BUCKET_NAME = '存储实例名'
const DB_FILE_NAME: string = AppDB.DB_NAME
const CLOUD_USER_DIR = 'userdata/users'

class CloudDB {
  private context: Context | null = null
  private storageBucket: cloudStorage.StorageBucket | null = null

  initDb(context: Context): void {
    this.context = context
    appDB.initDb(context)
  }

  async syncDbOnStartup(): Promise<void> {
    if (this.context === null) {
      return
    }
    this.initCloudStorage()
    await this.syncDbFile()
  }

  async uploadDbForCurrentUser(): Promise<boolean> {
    if (this.context === null) {
      hilog.warn(DOMAIN, TAG, 'Skip manual upload: context is null')
      return false
    }

    this.initCloudStorage()
    const cloudPath = await this.getCloudDbPathForCurrentUser()
    if (cloudPath === null) {
      hilog.warn(DOMAIN, TAG, 'Skip manual upload: current Huawei account unavailable')
      return false
    }

    const uploaded = await this.uploadDbFile(cloudPath)
    if (uploaded) {
      hilog.info(DOMAIN, TAG, `Manual upload completed, cloudPath: ${cloudPath}`)
    }
    return uploaded
  }

  private initCloudStorage(): void {
    try {
      cloudCommon.init({
        region: cloudCommon.CloudRegion.CHINA,
        authProvider: auth.getAuthProvider()
      })
      this.storageBucket = cloudStorage.bucket(STORAGE_BUCKET_NAME)
      hilog.info(DOMAIN, TAG, `Cloud storage initialized with auth provider, bucket: ${STORAGE_BUCKET_NAME}`)
    } catch (error) {
      const authErr = error as BusinessError
      hilog.error(DOMAIN, TAG, `Init cloud storage with auth failed, code: ${authErr.code}, message: ${authErr.message}`)
      try {
        cloudCommon.init({
          region: cloudCommon.CloudRegion.CHINA
        })
        this.storageBucket = cloudStorage.bucket(STORAGE_BUCKET_NAME)
        hilog.warn(DOMAIN, TAG, `Cloud storage initialized without auth provider, bucket: ${STORAGE_BUCKET_NAME}`)
      } catch (fallbackError) {
        const fallbackErr = fallbackError as BusinessError
        this.storageBucket = null
        hilog.error(DOMAIN, TAG, `Failed to init cloud storage fallback, code: ${fallbackErr.code}, message: ${fallbackErr.message}`)
      }
    }
  }

  private async syncDbFile(): Promise<void> {
    const cloudPath = await this.getCloudDbPathForCurrentUser()
    if (cloudPath === null) {
      hilog.warn(DOMAIN, TAG, 'Skip cloud sync: current Huawei account unavailable')
      return
    }

    const downloaded = await this.downloadDbFile(cloudPath)
    if (downloaded) {
      hilog.info(DOMAIN, TAG, 'Cloud DB downloaded and applied')
      return
    }
    const uploaded = await this.uploadDbFile(cloudPath)
    if (uploaded) {
      hilog.info(DOMAIN, TAG, 'Local DB uploaded to cloud')
    } else {
      hilog.warn(DOMAIN, TAG, 'Cloud DB sync skipped')
    }
  }

  private async uploadDbFile(cloudPath: string): Promise<boolean> {
    if (this.context === null) {
      return false
    }
    if (this.storageBucket === null) {
      this.initCloudStorage()
    }
    if (this.storageBucket === null) {
      return false
    }

    try {
      const context = this.context
      const dbPath = `${context.databaseDir}/rdb/${DB_FILE_NAME}`
      const cachePath = `${context.cacheDir}/${DB_FILE_NAME}`
      let uploadLocalPath: string | null = await appDB.createConsistentDbSnapshotForUpload(context)

      if (uploadLocalPath === null) {
        try {
          fs.accessSync(dbPath)
        } catch (_) {
          hilog.error(DOMAIN, TAG, `DB file not found at: ${dbPath}`)
          return false
        }
        const srcFile = fs.openSync(dbPath, fs.OpenMode.READ_ONLY)
        const dstFile = fs.openSync(cachePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        fs.copyFileSync(srcFile.fd, dstFile.fd)
        fs.closeSync(srcFile)
        fs.closeSync(dstFile)
        uploadLocalPath = cachePath
      }
      if (uploadLocalPath === null) {
        return false
      }

      const localPathForUpload: string = uploadLocalPath
      const task = await this.storageBucket.uploadFile(context, {
        localPath: localPathForUpload,
        cloudPath: cloudPath,
        mode: request.agent.Mode.FOREGROUND
      })

      return await new Promise<boolean>((resolve) => {
        task.on('completed', () => {
          fs.unlink(localPathForUpload).catch(() => {})
          resolve(true)
        })
        task.on('failed', (progress: request.agent.Progress) => {
          fs.unlink(localPathForUpload).catch(() => {})
          hilog.error(DOMAIN, TAG, `Upload task failed, progress: ${JSON.stringify(progress)}`)
          resolve(false)
        })
        task.on('response', (response: request.agent.HttpResponse) => {
          hilog.info(DOMAIN, TAG, `Upload response: ${JSON.stringify(response)}`)
        })
        task.start((err: BusinessError) => {
          if (err) {
            fs.unlink(localPathForUpload).catch(() => {})
            hilog.error(DOMAIN, TAG, `Upload task start failed, code: ${err.code}, message: ${err.message}`)
            resolve(false)
          } else {
            hilog.info(DOMAIN, TAG, `Upload task started, cloudPath: ${cloudPath}`)
          }
        })
      })
    } catch (error) {
      const err = error as BusinessError
      hilog.error(DOMAIN, TAG, `Upload DB file error, code: ${err.code}, message: ${err.message}`)
      return false
    }
  }

  private async downloadDbFile(cloudPath: string): Promise<boolean> {
    if (this.context === null) {
      return false
    }
    if (this.storageBucket === null) {
      this.initCloudStorage()
    }
    if (this.storageBucket === null) {
      return false
    }

    try {
      const context = this.context
      const localFileName = `cloud_${DB_FILE_NAME}`
      const task = await this.storageBucket.downloadFile(context, {
        localPath: localFileName,
        cloudPath: cloudPath,
        overwrite: true,
        mode: request.agent.Mode.FOREGROUND
      })

      return await new Promise<boolean>((resolve) => {
        task.on('completed', async () => {
          try {
            const cachePath = `${context.cacheDir}/${localFileName}`
            const dbPath = `${context.databaseDir}/rdb/${DB_FILE_NAME}`

            await appDB.deleteStore(context)

            const srcFile = fs.openSync(cachePath, fs.OpenMode.READ_ONLY)
            const dstFile = fs.openSync(dbPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
            fs.copyFileSync(srcFile.fd, dstFile.fd)
            fs.closeSync(srcFile)
            fs.closeSync(dstFile)
            fs.unlink(cachePath).catch(() => {})

            await appDB.initDbAsync(context)
            resolve(true)
          } catch (restoreError) {
            const err = restoreError as BusinessError
            hilog.error(DOMAIN, TAG, `Restore DB after download failed, code: ${err.code}, message: ${err.message}`)
            resolve(false)
          }
        })
        task.on('failed', (progress: request.agent.Progress) => {
          hilog.error(DOMAIN, TAG, `Download task failed, progress: ${JSON.stringify(progress)}`)
          resolve(false)
        })
        task.on('response', (response: request.agent.HttpResponse) => {
          hilog.info(DOMAIN, TAG, `Download response: ${JSON.stringify(response)}`)
        })
        task.start((err: BusinessError) => {
          if (err) {
            hilog.error(DOMAIN, TAG, `Download task start failed, code: ${err.code}, message: ${err.message}`)
            resolve(false)
          } else {
            hilog.info(DOMAIN, TAG, `Download task started, cloudPath: ${cloudPath}`)
          }
        })
      })
    } catch (error) {
      const err = error as BusinessError
      hilog.error(DOMAIN, TAG, `Download DB file error, code: ${err.code}, message: ${err.message}`)
      return false
    }
  }

  private async getCloudDbPathForCurrentUser(): Promise<string | null> {
    try {
      const user = await auth.getCurrentUser()
      if (user === null) {
        return null
      }
      const uid = user.getUid().trim()
      if (uid.length === 0) {
        return null
      }
      const safeUid = this.sanitizePathSegment(uid)
      return `${CLOUD_USER_DIR}/${safeUid}/${DB_FILE_NAME}`
    } catch (error) {
      const err = error as BusinessError
      hilog.error(DOMAIN, TAG, `Get current user for cloud path failed, code: ${err.code}, message: ${err.message}`)
      return null
    }
  }

  private sanitizePathSegment(raw: string): string {
    return raw.replace(/[^0-9A-Za-z._-]/g, '_')
  }
}

export default new CloudDB()

温馨提示:如果希望出现每次是否上传或者下载了文件,需要将

mode: request.agent.Mode.BACKGROUND

方便调试

收藏
1
回复
3
分享
全部评论
authorIcon
lorin
支持一下,谢谢分享
回复于2026-05-29 00:30广东
authorIcon
匿名用户
学习了
回复于2026-05-28 13:58辽宁
authorIcon
匿名用户
非常详细
回复于2026-05-28 11:57河南
写评论
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。
发表
我要写文章
目录 收起
1.设置云实例和安全策略
2.按照顺序开发
3.其他步骤真的没什么难度,这里重点想讲下关于用户跟用户的数据绑定的问题
了解社区公约,与您携手共创和谐专业的开发者社区。