Realm.js:将非结构化对象存储为属性

hen*_*wan 5 realm react-native

我们有一个内容交付应用程序,在该应用程序中,我们在JSON上放下了动态结构的对象。React Native使用JSON,并从这些对象构建用户界面。

这是我现在正在使用的架构:

const CardSchema = {
    name: 'Card',
    properties: {
        id: 'string',
        cardSubType: 'string',
        cardType: 'string',
        state: 'string',
        contentType: 'string',
        context: {},
    },
};
Run Code Online (Sandbox Code Playgroud)

领域context是动态的一部分。它基本上是一个对象,可以具有任意多个字段。我们在编译时不知道其中有哪些字段。

我们想使用realm.js来持久化我们的数据,因为它既好又快,并且我们99%的对象都可以在编译时进行模块化。

我们要在其中存储任何对象的就是这个字段(和其他几个字段)。

Realm for React Native是否可以做到这一点?还是我需要将其建模为字符串并在存储时进行序列化并在加载时进行反序列化?

Ari*_*Ari 6

Realm 尚不支持存储字典/动态对象。这绝对是路线图上的内容,因为能够简单地存储和检索 JSON 对象是非常自然的。在完全支持字典之前,您需要按照建议将数据存储为字符串,或者创建自己的 JSON 模型。就像是

const UNDEFINEDTYPE = 0;
const INTTYPE = 1;
const STRINGTYPE = 2;

const JSONValueSchema = {
    name: 'JSONValue',
    properties: {
        type: 'int',
        stringValue: { type: 'string', optional: true },
        intValue:    { type: 'int', optional: true },
        jsonValue:   { type: 'JSON', optional: true },        
    }
};

const JSONEntrySchema = {
    name: 'JSONEntry',
    properties: {
        key: 'string',
        value: 'string'
    }
};

const JSONSchema = {
    name: 'JSON',
    properties: {
        entries: { type: 'list', objectType: 'JSONEntry' }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做会有点冗长,但它可以让您完全使用带有 keyPath 查询的查询系统,其中存储 JSON blob 将迫使您使用CONTAINS查询。不确定所有的努力对于您的应用程序是否值得。