将复杂的普通对象转换为Realm对象?

时间:2018-07-23 22:44:03

标签: javascript json node.js realm

我正在尝试将接收到的普通javascript对象转换和/或直接传递给Realm Object,但是这样做很麻烦。

“设置”-收到的普通对象(将Realm对象转换为Json并返回)

realm.create('Settings', {
    Id: settings.Id,
    User: settings.User,
    FavoriteChannels: settings.FavoriteChannels,
}, true)

这是一个简单的示例架构:

exports.Settings = {
    name: 'Settings',
    primaryKey: 'Id',
    properties: {
        Id: 'string',
        User: 'User',       
        FavoriteChannels: 'Channel[]',
    }
};

exports.User = {
    name: 'User',
    primaryKey: 'Id',
    properties: {
        Id: 'string',
        FirstName: 'string?',
        LastName: 'string?',            
        PhoneNumbers: 'PhoneNumber[]'           
    }
};

exports.PhoneNumber = {
    name: 'PhoneNumber',
    primaryKey: 'Id',
    properties: {
        Id: 'string',        
        Number: 'string',
    }
};

exports.Channel = {
    name: 'Channel',
    primaryKey: 'Id',
    properties: {
        Id: 'string',           
        ChannelName: 'string?',         
        Users: 'User[]',            
    }
};  

如果我尝试直接在“ realm.create”中传递“设置”,则会出现以下错误:

User.PhoneNumbers必须是'PhoneNumber[]'类型,得到'object' ([object Object]

它需要一个数组,但是普通对象的集合反序列化为对象/字典? (例如PhoneNumbers: { '0': [Object] })。解串器无法知道如何将Realm Object的"List {}"(例如[PhoneNumbers]: List { [0]: [Object] })解析为数组。

除非我遗漏了一些东西,否则Realm对于这些类型的操作似乎缺乏“对称性”。

1 个答案:

答案 0 :(得分:0)

一种解决方法是,仅在客户端使用对象构造函数,例如:

//file "dataModel.js"
export function Settings(obj) {
    this.Id = obj.Id;
    this.User = new User(obj.User); //check for null, if property in the schema is nullable, so you don't pass empty objects to Realm - example: obj.User ? new User(obj.User) : null;
    this.FavoriteChannels = Object.values(obj.FavoriteChannels).map(m => new Channel(m));
}

export function User(obj) {
    this.Id = obj.Id;
    this.FirstName = ojb.FirstName;
    this.LastName = obj.LastName;
    PhoneNumbers = Object.values(obj.PhoneNubmers).map(m => new PhoneNumber(m));
}

export function PhoneNumber(obj) {
    this.Id = obj.Id;
    this.Nubmer = obj.Number;
}

export function Channel(obj) {
    this.Id = obj.Id;
    this.ChannelName = obj.ChannelName;
    this.Users = Object.values(obj.Users).map(m => new User(m));
}


//file app.js
import * as dataModel from 'path-to-dataModel';
...
//receive data from server and create Settings using the constructor from dataModel
const testObj = new dataModel.Settings(plainSettingsObjectFromServer);  
//make any changes to the testObj and send it back to server

现在,我们可以将从客户端接收的普通对象传递给Realm.Create:

realm.create('Settings', {
    Id: plainSettingsObject.Id,
    User: plainSettingsObject.User,
    FavoriteChannels: plainSettingsObject.FavoriteChannels,
}, true)