Skip to content

Commit

Permalink
Lookup PK dynmically using object schema, during RealmValue of RealmO…
Browse files Browse the repository at this point in the history
…bject serialization
  • Loading branch information
nielsenko committed Jul 29, 2024
1 parent 46c7bea commit 146805c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
3 changes: 3 additions & 0 deletions packages/realm_dart/lib/src/configuration.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import 'dart:async';

// ignore: no_leading_underscores_for_library_prefixes
import 'package:collection/collection.dart';
import 'package:path/path.dart' as _path;

import 'app.dart';
Expand Down Expand Up @@ -431,6 +432,8 @@ class SchemaObject extends Iterable<SchemaProperty> {

@override
SchemaProperty elementAt(int index) => _properties.elementAt(index);

SchemaProperty? get primaryKey => _properties.firstWhereOrNull((p) => p.primaryKey);
}

/// Describes the complete set of classes which may be stored in a `Realm`
Expand Down
3 changes: 2 additions & 1 deletion packages/realm_dart/lib/src/handles/native/init.dart
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ impl.Decimal128 decodeDecimal128(EJsonValue ejson) => switch (ejson) {
EJsonValue encodeRealmValue(RealmValue value) {
final v = value.value;
if (v is RealmObject) {
// TODO: encode link as DBRef
final p = RealmObjectBase.get(v, v.objectSchema.primaryKey!.name);
return DBRef(v.objectSchema.name, p).toEJson();
}
return toEJson(v);
}
Expand Down
15 changes: 10 additions & 5 deletions packages/realm_dart/test/serialization_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,6 @@ void main() {
'a': {'\$numberInt': '1'},
'b': {'\$numberInt': '2'},
},
Player('Christian Eriksen'): {
// Player is a RealmObject, so it is encoded as a reference inside a RealmValue.
'@ref': 'Player',
'@id': 'Christian Eriksen'
},
}.entries) {
final value = entry.key;
final encoded = entry.value;
Expand All @@ -54,6 +49,16 @@ void main() {
expect(fromEJson<RealmValue>(r.toEJson()), r);
}
});

test('RealmValue with RealmObject', () {
// load custom codecs for Player and Game. This is done to test that it
// doesn't interfere with the RealmValue codecs.
Realm(Configuration.inMemory([Player.schema, Game.schema]));

final rv = RealmValue.from(Player('Christian Eriksen'));
expect(rv.toEJson(), {'\$id': 'Christian Eriksen', '\$ref': 'Player'});
expect(fromEJson<DBRef>(rv.toEJson()), isA<DBRef>().having((r) => r.id, '\$id', 'Christian Eriksen'));
});
}
});

Expand Down

0 comments on commit 146805c

Please sign in to comment.