Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm.js: Storing unstructured object as property

We have a content delivery app, where we bring down objects on our JSON that are dynamic in structure. React Native consumes the JSON, and builds up the user interface from these objects.

This is the schema that I'm working with now:

const CardSchema = {
    name: 'Card',
    properties: {
        id: 'string',
        cardSubType: 'string',
        cardType: 'string',
        state: 'string',
        contentType: 'string',
        context: {},
    },
};

The field context is the dynamic part. It's basically an object that can have any number of fields. We don't know at compile time which fields are in there.

We would like to use realm.js to persist our data, because it's nice and fast and 99% of our objects we can module at compile time.

It's just this one field (and a few others) that we want to store any object on.

Is this possible with Realm for React Native? Or would I need to model it as a string and do serialization when I store and deserialization when I load?

like image 201
hendrikswan Avatar asked Jul 21 '16 13:07

hendrikswan


1 Answers

Realm does not yet support storing dictionaries/dynamic objects. This is definitely something on the roadmap as it would be very natural to be able to simply store and retrieve JSON objects. Until there is full support for dictionaries you will either need to store your data as a string as you suggest, or to create your own JSON model. Something like

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' }
    }
}

Doing this will be a bit verbose but it would allow you to fully use the query system with keyPath queries, where storing a JSON blob would force you to use CONTAINS queries. Not sure if all the effort is worth it for your application.

like image 132
Ari Avatar answered Oct 20 '22 04:10

Ari