Skip to content

v3.2 中新的 Conversation 自定义属性 API

Lee Yeh edited this page Dec 19, 2019 · 5 revisions

背景

在 v3.0 中,Conversation 有了 attributes 这个字段,用于存放用户自定义的属性,对应着控制台 _Conversation 表中的 attr 列:

这个机制存在两个问题:

  • attr 中的自定义属性(如 attr.type)无法在控制台操作建立索引。(控制台已支持)
  • Conversation#setAttributes({ type: 0 }) 有歧义,需要第二个参数来表明是否会删除原有的 attr 中的其他属性。

鉴于此,在 v3.2 中,SDK 重新设计了自定义属性相关的 API。

废弃 Conversationattr 属性

概念上,Conversation 不再有单独的自定义属性这一属性(attr),自定义属性(如 type)与其他的属性一样,是 Conversation 的直接成员。在新的模型中定义自定义属性 type_Conversation 表中将会有一 type 列,你可以在控制台自行为其建立索引:

新增方法自定义属性操作 API

对自定义属性的操作将使用一组新的 API:Conversation#getConversation#set。与存储 SDK 的属性操作 API 一样,Conversation#set 也支持使用形如 'x.y.z' 的 key 来修改属性的部分字段:

// 设置对话的 color 属性
conversation.set('color', {
  text: '#000',
  background: '#DDD',
});
// 设置对话的 color.text 属性,该操作不会影响 color.background
conversation.set('color.text', '#333');

SDK 还提供了一个新的工具方法 Realtime.defineConversationProperty 来定义 Conversation 类自定义字段的 getter 与 setter:

conversation.get('type');
conversation.set('type', 0);

// equals to
Realtime.defineConversationProperty('type');
conversation.type;
conversation.type = 0;

废弃 attributes 相关的 API

由于废弃了 attributesattr)属性,与其相关的 API 也在这个版本中被标记为废弃(deprecated)。这些 API 仍然能正常使用,同时会给出一个 Deprecated 警告。下一个 major release 中(v4.0)这些 API 将会被移除。

必须指出的是,这些改动都是 SDK 层的改动,服务端与 Rest API 没有变化,现存的数据也不被改动。如果在之前已经使用了 attributes 相关的 API,_Conversation 表中已经存在了 attr 列并希望继续按照原来的方式使用,可以按照下表列出的方法进行迁移:

废弃的 API 替代方法
Conversationattributes 属性 Conversation.get('attr')Conversation.set('attr', value)
Conversation.setAttribute('key', value) Conversation.set('attr.key', value)
修改部分属性:
Conversation.setAttributes({'key', value}, true)
Conversation.set('attr.key', value)
修改全部属性:
Conversation.setAttributes({'key', value}[, false])
Conversation.set('attr', {'key': value})
Conversation.setName(value) Conversation.name = value
IMClient#createConversationoptions.attributes 属性:
client.createConversation({ attributes: {key: value})
options[propertyName]
client.createConversation({key: value})
Clone this wiki locally