Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(toJSON): get the generic type T for toJSON response #6789

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/realm/src/JSONCacheMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
import { DefaultObject, INTERNAL, RealmObject } from "./internal";

/** @internal */
export class JSONCacheMap extends Map<number, Map<string, DefaultObject>> {
add<T>(object: RealmObject<T>, value: DefaultObject) {
export class JSONCacheMap<T = DefaultObject> extends Map<number, Map<string, T>> {
add<U>(object: RealmObject<U>, value: T) {
const tableKey = object[INTERNAL].table.key;
let cachedMap = this.get(tableKey);
if (!cachedMap) {
Expand All @@ -29,7 +29,7 @@ export class JSONCacheMap extends Map<number, Map<string, DefaultObject>> {
}
cachedMap.set(object._objectKey(), value);
}
find<T>(object: RealmObject<T>) {
find<U>(object: RealmObject<U>) {
return this.get(object[INTERNAL].table.key)?.get(object._objectKey());
}
}
6 changes: 3 additions & 3 deletions packages/realm/src/Object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,17 +382,17 @@ export class RealmObject<T = DefaultObject, RequiredProperties extends keyof Omi
* and [flatted](https://www.npmjs.com/package/flatted) to stringify Realm entities that have circular structures.
* @returns A plain object.
*/
toJSON(_?: string, cache?: unknown): DefaultObject;
toJSON(_?: string, cache?: unknown): OmittedRealmTypes<T>;
/** @internal */
toJSON(_?: string, cache = new JSONCacheMap()): DefaultObject {
toJSON(_?: string, cache = new JSONCacheMap<T>()): OmittedRealmTypes<T> {
// Construct a reference-id of table-name & primaryKey if it exists, or fall back to objectId.

// Check if current objectId has already processed, to keep object references the same.
const existing = cache.find(this);
if (existing) {
return existing;
}
const result: DefaultObject = {};
const result = {} as T;
cache.add(this, result);
// Move all enumerable keys to result, triggering any specific toJSON implementation in the process.
for (const key in this) {
Expand Down