云对象内置API

71 阅读7分钟

1.4 云对象内置API

云对象作为云函数的一种,可以调用所有Node.js的API和uniCloud的内置API。本文将详细介绍云对象中可以使用的uniCloud内置API,并提供示例用法。

1. 数据库API

1.1 获取数据库实例

// 获取数据库实例
const db = uniCloud.database();

// 获取指定服务空间的数据库实例
const db = uniCloud.database({
  provider: 'aliyun', // 服务商,可选值:aliyun、tencent
  spaceId: 'your-space-id' // 服务空间ID
});

1.2 集合操作

// 获取集合引用
const collection = db.collection('collection-name');

// 获取集合的聚合操作对象
const aggregate = db.collection('collection-name').aggregate();

// 获取集合的查询对象
const query = db.collection('collection-name').where({
  field: 'value'
});

// 获取集合的更新对象
const update = db.collection('collection-name').doc('document-id').update({
  field: 'new-value'
});

// 获取集合的删除对象
const remove = db.collection('collection-name').doc('document-id').remove();

1.3 查询操作

// 查询示例
const result = await db.collection('users')
  .where({
    age: db.command.gt(18), // 年龄大于18
    city: '北京' // 城市为北京
  })
  .field({
    name: true, // 只返回name字段
    age: true // 只返回age字段
  })
  .orderBy('age', 'desc') // 按年龄降序排序
  .skip(0) // 跳过0条记录
  .limit(10) // 最多返回10条记录
  .get();

console.log(result.data); // 查询结果

1.4 添加操作

// 添加单条记录
const result = await db.collection('users').add({
  name: '张三',
  age: 25,
  city: '北京',
  createTime: Date.now()
});

console.log(result.id); // 新增记录的ID

// 添加多条记录
const result = await db.collection('users').add([
  {
    name: '张三',
    age: 25,
    city: '北京',
    createTime: Date.now()
  },
  {
    name: '李四',
    age: 30,
    city: '上海',
    createTime: Date.now()
  }
]);

console.log(result.ids); // 新增记录的ID数组

1.5 更新操作

// 更新单条记录
const result = await db.collection('users').doc('document-id').update({
  age: 26,
  updateTime: Date.now()
});

console.log(result.updated); // 更新的记录数

// 更新多条记录
const result = await db.collection('users').where({
  city: '北京'
}).update({
  city: '广州',
  updateTime: Date.now()
});

console.log(result.updated); // 更新的记录数

1.6 删除操作

// 删除单条记录
const result = await db.collection('users').doc('document-id').remove();

console.log(result.deleted); // 删除的记录数

// 删除多条记录
const result = await db.collection('users').where({
  age: db.command.lt(18)
}).remove();

console.log(result.deleted); // 删除的记录数

1.7 聚合操作

// 聚合示例
const result = await db.collection('orders')
  .aggregate()
  .match({
    status: 'completed'
  })
  .group({
    _id: '$userId',
    totalAmount: db.command.aggregate.sum('$amount'),
    orderCount: db.command.aggregate.count()
  })
  .sort({
    totalAmount: -1
  })
  .limit(10)
  .end();

console.log(result.data); // 聚合结果

2. 存储API

2.1 上传文件

// 上传文件
const result = await uniCloud.uploadFile({
  filePath: 'file-path', // 文件路径
  cloudPath: 'cloud-path/file-name.jpg', // 云端路径
  onUploadProgress: function(progressEvent) {
    console.log(progressEvent);
  }
});

console.log(result.fileID); // 文件ID

2.2 下载文件

// 下载文件
const result = await uniCloud.downloadFile({
  fileID: 'file-id', // 文件ID
  onDownloadProgress: function(progressEvent) {
    console.log(progressEvent);
  }
});

console.log(result.tempFilePath); // 临时文件路径

2.3 删除文件

// 删除文件
const result = await uniCloud.deleteFile({
  fileList: ['file-id-1', 'file-id-2'] // 文件ID列表
});

console.log(result.fileList); // 删除结果

2.4 获取文件信息

// 获取文件信息
const result = await uniCloud.getFileInfo({
  fileList: ['file-id-1', 'file-id-2'] // 文件ID列表
});

console.log(result.fileList); // 文件信息列表

2.5 获取临时访问链接

// 获取临时访问链接
const result = await uniCloud.getTempFileURL({
  fileList: ['file-id-1', 'file-id-2'] // 文件ID列表
});

console.log(result.fileList); // 临时访问链接列表

3. 云函数API

3.1 调用云函数

// 调用云函数
const result = await uniCloud.callFunction({
  name: 'function-name', // 云函数名称
  data: {
    // 传递给云函数的参数
    param1: 'value1',
    param2: 'value2'
  }
});

console.log(result.result); // 云函数返回结果

3.2 导入云对象

// 导入云对象
const todo = uniCloud.importObject('todo');

// 调用云对象方法
const result = await todo.add('标题', '内容');

console.log(result); // 云对象方法返回结果

4. 云对象API

4.1 获取客户端信息

// 获取客户端信息
const clientInfo = this.getClientInfo();

console.log(clientInfo);
// 输出示例:
// {
//   clientIP: '127.0.0.1',
//   userAgent: 'Mozilla/5.0 ...',
//   platform: 'web',
//   os: 'windows',
//   device: 'desktop'
// }

4.2 获取云端信息

// 获取云端信息
const cloudInfo = this.getCloudInfo();

console.log(cloudInfo);
// 输出示例:
// {
//   provider: 'aliyun',
//   spaceId: 'your-space-id',
//   functionName: 'function-name',
//   functionType: 'cloudObject'
// }

4.3 获取客户端Token

// 获取客户端Token
const token = this.getClientToken();

console.log(token); // 客户端Token

4.4 获取当前调用的方法名

// 获取当前调用的方法名
const methodName = this.getMethodName();

console.log(methodName); // 当前调用的方法名

4.5 获取当前参数列表

// 获取当前参数列表
const params = this.getParams();

console.log(params); // 当前参数列表

4.6 获取当前请求ID

// 获取当前请求ID
const requestId = this.getRequestId();

console.log(requestId); // 当前请求ID

4.7 获取URL化时的HTTP信息

// 获取URL化时的HTTP信息
const httpInfo = this.getHttpInfo();

console.log(httpInfo);
// 输出示例:
// {
//   method: 'POST',
//   url: '/path',
//   headers: { ... },
//   cookies: { ... },
//   query: { ... },
//   body: { ... }
// }

4.8 Cookie操作

// 设置Cookie
this.setCookie('key', 'value', {
  maxAge: 7 * 24 * 60 * 60, // 7天
  path: '/',
  domain: 'example.com',
  secure: true,
  httpOnly: true
});

// 获取Cookie
const cookie = this.getCookie('key');

console.log(cookie); // Cookie值

// 删除Cookie
this.deleteCookie('key');

5. 配置中心API

5.1 获取配置

// 获取配置
const config = uniCloud.getConfig({
  configKey: 'config-key' // 配置键名
});

console.log(config); // 配置值

5.2 设置配置

// 设置配置
const result = await uniCloud.setConfig({
  configKey: 'config-key', // 配置键名
  configValue: 'config-value' // 配置值
});

console.log(result); // 设置结果

6. 云对象生命周期方法

6.1 预处理方法

// 预处理方法
async _before() {
  // 获取客户端信息
  const clientInfo = this.getClientInfo();
  console.log('客户端信息', clientInfo);
  
  // 获取云端信息
  const cloudInfo = this.getCloudInfo();
  console.log('云端信息', cloudInfo);
  
  // 获取客户端 token
  const token = this.getClientToken();
  console.log('客户端 token', token);
  
  // 获取当前调用的方法名
  const methodName = this.getMethodName();
  console.log('当前调用的方法名', methodName);
  
  // 获取当前参数列表
  const params = this.getParams();
  console.log('当前参数列表', params);
  
  // 获取当前请求 id
  const requestId = this.getRequestId();
  console.log('当前请求 id', requestId);
}

6.2 后处理方法

// 后处理方法
async _after(result) {
  // 记录日志
  console.log('方法执行结果', result);
  
  // 返回结果
  return result;
}

6.3 定时执行方法

// 定时执行方法
async _timing() {
  console.log('定时任务执行', new Date().toISOString());
  
  // 执行定时任务
  const db = uniCloud.database();
  const collection = db.collection('todos');
  const result = await collection.where({
    status: 'pending'
  }).update({
    status: 'completed',
    completeTime: Date.now()
  });
  
  return {
    errCode: 0,
    errMsg: '定时任务执行成功',
    data: result
  };
}

7. 完整示例

以下是一个完整的云对象示例,展示了如何使用各种内置API:

// 云对象名:todo
const db = uniCloud.database();
const crypto = require('crypto');

// 工具函数
function md5(text) {
  return crypto.createHash('md5').update(text).digest('hex');
}

module.exports = {
  // 预处理方法
  async _before() {
    // 获取客户端信息
    const clientInfo = this.getClientInfo();
    console.log('客户端信息', clientInfo);
    
    // 获取客户端 token
    const token = this.getClientToken();
    console.log('客户端 token', token);
  },
  
  // 后处理方法
  async _after(result) {
    // 记录日志
    console.log('方法执行结果', result);
    
    // 返回结果
    return result;
  },
  
  /**
   * 添加待办事项
   * @param {string} title 待办事项标题
   * @param {string} content 待办事项内容
   * @returns {object} 返回结果
   */
  async add(title, content) {
    // 参数验证
    if (!title || !content) {
      return {
        errCode: 'INVALID_PARAMETER',
        errMsg: '标题和内容不能为空'
      };
    }
    
    // 数据库操作
    const collection = db.collection('todos');
    const result = await collection.add({
      title,
      content,
      status: 'pending',
      createTime: Date.now(),
      updateTime: Date.now()
    });
    
    return {
      errCode: 0,
      errMsg: '创建成功',
      data: {
        id: result.id
      }
    };
  },
  
  /**
   * 获取待办事项列表
   * @param {number} page 页码
   * @param {number} pageSize 每页数量
   * @param {string} status 状态
   * @returns {object} 返回结果
   */
  async getList(page = 1, pageSize = 10, status = '') {
    // 构建查询条件
    const query = {};
    if (status) {
      query.status = status;
    }
    
    // 数据库操作
    const collection = db.collection('todos');
    const countResult = await collection.where(query).count();
    const total = countResult.total;
    
    const result = await collection
      .where(query)
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();
    
    return {
      errCode: 0,
      errMsg: '获取成功',
      data: {
        list: result.data,
        total,
        page,
        pageSize
      }
    };
  },
  
  /**
   * 更新待办事项
   * @param {string} id 待办事项ID
   * @param {string} title 待办事项标题
   * @param {string} content 待办事项内容
   * @param {string} status 待办事项状态
   * @returns {object} 返回结果
   */
  async update(id, title, content, status) {
    // 参数验证
    if (!id) {
      return {
        errCode: 'INVALID_PARAMETER',
        errMsg: 'ID不能为空'
      };
    }
    
    // 构建更新数据
    const updateData = {
      updateTime: Date.now()
    };
    
    if (title !== undefined) {
      updateData.title = title;
    }
    
    if (content !== undefined) {
      updateData.content = content;
    }
    
    if (status !== undefined) {
      updateData.status = status;
    }
    
    // 数据库操作
    const collection = db.collection('todos');
    const result = await collection.doc(id).update(updateData);
    
    return {
      errCode: 0,
      errMsg: '更新成功',
      data: result
    };
  },
  
  /**
   * 删除待办事项
   * @param {string} id 待办事项ID
   * @returns {object} 返回结果
   */
  async remove(id) {
    // 参数验证
    if (!id) {
      return {
        errCode: 'INVALID_PARAMETER',
        errMsg: 'ID不能为空'
      };
    }
    
    // 数据库操作
    const collection = db.collection('todos');
    const result = await collection.doc(id).remove();
    
    return {
      errCode: 0,
      errMsg: '删除成功',
      data: result
    };
  },
  
  /**
   * 上传文件
   * @param {string} filePath 文件路径
   * @param {string} cloudPath 云端路径
   * @returns {object} 返回结果
   */
  async uploadFile(filePath, cloudPath) {
    // 参数验证
    if (!filePath || !cloudPath) {
      return {
        errCode: 'INVALID_PARAMETER',
        errMsg: '文件路径和云端路径不能为空'
      };
    }
    
    // 上传文件
    const result = await uniCloud.uploadFile({
      filePath,
      cloudPath,
      onUploadProgress: function(progressEvent) {
        console.log('上传进度', progressEvent);
      }
    });
    
    return {
      errCode: 0,
      errMsg: '上传成功',
      data: {
        fileID: result.fileID
      }
    };
  },
  
  /**
   * 获取文件临时访问链接
   * @param {string} fileID 文件ID
   * @returns {object} 返回结果
   */
  async getFileURL(fileID) {
    // 参数验证
    if (!fileID) {
      return {
        errCode: 'INVALID_PARAMETER',
        errMsg: '文件ID不能为空'
      };
    }
    
    // 获取临时访问链接
    const result = await uniCloud.getTempFileURL({
      fileList: [fileID]
    });
    
    return {
      errCode: 0,
      errMsg: '获取成功',
      data: {
        url: result.fileList[0].tempFileURL
      }
    };
  },
  
  /**
   * 调用其他云对象
   * @returns {object} 返回结果
   */
  async callOtherObject() {
    // 导入云对象
    const user = uniCloud.importObject('user');
    
    // 调用云对象方法
    const result = await user.getUserInfo();
    
    return {
      errCode: 0,
      errMsg: '调用成功',
      data: result
    };
  },
  
  /**
   * 定时任务
   * @returns {object} 返回结果
   */
  async _timing() {
    console.log('定时任务执行', new Date().toISOString());
    
    // 执行定时任务
    const collection = db.collection('todos');
    const result = await collection.where({
      status: 'pending'
    }).update({
      status: 'completed',
      completeTime: Date.now()
    });
    
    return {
      errCode: 0,
      errMsg: '定时任务执行成功',
      data: result
    };
  }
};

8. 总结

云对象作为云函数的一种,可以调用所有Node.js的API和uniCloud的内置API。本文详细介绍了云对象中可以使用的uniCloud内置API,包括:

  1. 数据库API:用于操作数据库,包括查询、添加、更新、删除和聚合操作。
  2. 存储API:用于操作云存储,包括上传、下载、删除、获取文件信息和获取临时访问链接。
  3. 云函数API:用于调用云函数和导入云对象。
  4. 云对象API:用于获取客户端信息、云端信息、客户端Token、当前调用的方法名、当前参数列表、当前请求ID、URL化时的HTTP信息和Cookie操作。
  5. 配置中心API:用于获取和设置配置。
  6. 云对象生命周期方法:包括预处理方法、后处理方法和定时执行方法。

通过使用这些API,开发者可以更加高效地开发云对象,实现各种业务逻辑。