Docs 菜单

Docs 主页开发应用程序Atlas Device SDKs

调用 Atlas 函数 - Kotlin SDK

在此页面上

  • 概述
  • 开始之前
  • 调用函数
  • Realm Kotlin SDK v1.8.x 及更早版本中的限制

您可以使用 Realm Kotlin SDK 从客户端应用程序调用Realm 函数 。函数是无服务器 JavaScript 函数,可让您定义和执行服务器端逻辑。 这些服务器端函数可以在经过身份验证的用户上下文中运行,从而遵守您在 Atlas 中为数据分配的规则、角色和权限。

1.9.0 版本中的新增功能

您可以使用 EJSON 编码器序列化函数参数并返回值。 有关包括示例在内的更多信息,请参阅Atlas 的 EJSON 编码。

有关配置和编写 Atlas Function 的更多信息,请参阅 App Services 文档中的Atlas Function

  1. 在 App Services App 中,定义 Atlas Function。

  2. 在客户端项目中,初始化 App 客户端。

  3. 然后,对用户进行身份验证。可通过用户对象访问函数。

重要

使用函数时,确保对客户端数据进行清理,以防止代码注入。

要从 Kotlin SDK 调用 Atlas 函数,请将其名称和所有参数传递给Functions.call()。

考虑在名为 sum的 App Services App 中运行的 Realm 函数,该函数接受两个参数,将它们相加并返回结果:

Atlas Function
// Add two numbers
exports = function(a, b) {
return a + b;
};

要从 Kotlin SDK 调用此 Atlas Function,请执行以下操作:

runBlocking {
val app: App = App.create(appID)
val user = app.login(credentials)
// Access the Atlas Function through the authenticated user
// Pass the Function name and all arguments
val response = user.functions.call<Int>("sum", 1, 2)
print(response) // prints: 3
}

在 1.9.0 版本中进行了更改

如果您使用的是 Kotlin SDK v1.9.0 或更高版本,则这些限制不再适用。

因为 Kotlin 序列化引擎 尚不支持第三方库,但可以作为参数传递的类型以及可以在被调用函数中将结果反序列化为的类型都有限制。

不能将对象作为参数传递。

以下是有效的参数值类型:

  • 基元

  • bson

  • MutableRealmInt

  • RealmUUID

  • ObjectId

  • RealmInstant

  • RealmAny

  • 阵列

  • collection(列表或集)

  • 映射(map)

以下是有效的返回值类型:

  • 基元

  • bson

  • MutableRealmInt

  • RealmUUID

  • ObjectId

  • RealmInstant

  • RealmAny

  • BsonArray(适用于数组和collection参数类型)

  • BsonDocument(针对 Map 参数类型)

← 连接到 Atlas App Services - Kotlin SDK