diff --git a/src/MSTGQLObject.ts b/src/MSTGQLObject.ts index 0f46b5ac..1c718913 100644 --- a/src/MSTGQLObject.ts +++ b/src/MSTGQLObject.ts @@ -44,7 +44,9 @@ export function MSTGQLRef( return node }, set(value: any) { - return [label, MSTGQL_ID_DELIM, value.id].join("") + const typeDef = value.store.getTypeDef(value.__typename) + const id = value[typeDef.identifierAttribute ?? 'id'] + return [label, MSTGQL_ID_DELIM, id].join("") } }) } diff --git a/src/deflateHelper.ts b/src/deflateHelper.ts index 49515248..972d7599 100644 --- a/src/deflateHelper.ts +++ b/src/deflateHelper.ts @@ -3,11 +3,14 @@ export function deflateHelper(store: any, data: any) { if (!data || typeof data !== "object") return data if (Array.isArray(data)) return data.map(deflate) - const { __typename, id } = data + const { __typename } = data + if (__typename && store.isRootType(__typename)) { - // GQL object with root type, keep only __typename & id - return { __typename, id } + // GQL object with root type, keep only __typename & identifier + const typeDef = store.getTypeDef(__typename) + const idName = typeDef.identifierAttribute ?? 'id' + return { __typename, [idName]: data[idName] } } else { // GQL object with non-root type, return object with all props deflated const snapshot: any = {} diff --git a/src/mergeHelper.ts b/src/mergeHelper.ts index f2b6d505..fc9e9161 100644 --- a/src/mergeHelper.ts +++ b/src/mergeHelper.ts @@ -6,7 +6,7 @@ export function mergeHelper(store: any, data: any) { if (!data || typeof data !== "object") return data if (Array.isArray(data)) return data.map(merge) - const { __typename, id } = data + const { __typename } = data // convert values deeply first to MST objects as much as possible const snapshot: any = {} @@ -18,6 +18,9 @@ export function mergeHelper(store: any, data: any) { if (__typename && store.isKnownType(__typename)) { // GQL object with known type, instantiate or recycle MST object const typeDef = store.getTypeDef(__typename) + + const id = data[typeDef.identifierAttribute ?? 'id'] + // Try to reuse instance, even if it is not a root type let instance = id !== undefined && resolveIdentifier(typeDef, store, id) if (instance) {