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

Determining if a relationship has been loaded. #929

Open
SomewhatCloudy opened this issue Feb 22, 2022 · 2 comments
Open

Determining if a relationship has been loaded. #929

SomewhatCloudy opened this issue Feb 22, 2022 · 2 comments

Comments

@SomewhatCloudy
Copy link

SomewhatCloudy commented Feb 22, 2022

At the moment there doesn't seem to be a way of determining if a relationship on a model has already been loaded. For example there is no way to tell if this:

memory.cache.query(q => q.findRelatedRecords(ident, relationKey));

Will always return an array, regardless of if the relation has been loaded already. The same applies to hasOne/belongsTo. This forces you to re-fetch relations that are empty as you don't know if they have already been fetched.

If there a way of finding out if a relation is already loaded, or possibly (and I know this may be breaking) make findRelatedRecords/findRelatedRecord return undefined if there is no relation?

@dgeb
Copy link
Member

dgeb commented Feb 22, 2022

There are a few alternative ways to check the contents of the cache, but also a caveat.

First, the alternatives:

// Cache#query followed by inspection of the record
const planet = memory.cache.query(q => q.findRecord(ident));
const moonIds = planet?.relationships?.moons?.data;
// Cache#getRecord followed by inspection of the record
const planet = memory.cache.getRecord(ident);
const moonIds = planet?.relationships?.moons?.data;
// Cache#getRelatedRecordsSync - returns `RecordIdentity[] | undefined`
const moonIds = memory.cache.getRelatedRecordsSync(ident, 'moons');

The caveat is that caches by default maintain inverse relationships automatically when they are declared in a schema. Thus, fetching moons but not a planet may still assign those inverse relationships to a sparsely populated planet record in the cache. If you have no inverses on the relationship in question, then this is not a factor.

@SomewhatCloudy
Copy link
Author

Thanks I'll give that a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants