经授权写入存储引擎 #

以下示例介绍了如何以授权方式写入存储引擎。

当使用StorageWrite函数一次写入多个存储对象时,将在一次事务中写入对象,从而确保所有对象写入成功或全部失败。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
userID, _ := ctx.Value(runtime.RUNTIME_CTX_USER_ID).(string)

unlockedHats := map[string]interface{}{
    "hats": []string{"alien", "cowboy", "space-soldier"},
}

hatBytes, err := json.Marshal(unlockedHats)
if err != nil {
    return err
}

unlockedSkins := map[string]interface{}{
    "skins": []string{"ninja", "robot", "bear"},
}

skinBytes, err := json.Marshal(unlockedSkins)
if err != nil {
    return err
}

hatWrite := &runtime.StorageWrite{
    Collection:      "Unlocks",
    Key:             "Hats",
    UserID:          userID,
    Value:           string(hatBytes),
    PermissionRead:  1, // Only the server and owner can read
    PermissionWrite: 0, // Only the server can write
}

skinWrite := &runtime.StorageWrite{
    Collection:      "Unlocks",
    Key:             "Skins",
    UserID:          userID,
    Value:           string(skinBytes),
    PermissionRead:  1, // Only the server and owner can read
    PermissionWrite: 0, // Only the server can write
}

_, err = nk.StorageWrite(ctx, []*runtime.StorageWrite{hatWrite, skinWrite})
if err != nil {
    return err
}