ladda-js / ladda

JavaScript data fetching layer with caching
https://petercrona.gitbooks.io/ladda/content/
MIT License
112 stars 16 forks source link

Feature Proposal: Associated entities #40

Open LFDM opened 6 years ago

LFDM commented 6 years ago

Let's consider having an entity called User and an entity called UserSettings. Each user has exactly one user settings object. A UserSettings object has a reference id to its user object in a field called userId.

The goal is to get more clever invalidations. Right now we can only say, that a change to a User should invalidate all UserSettings objects we have in our cache. By defining an association between these two entities, we could automatically do more fine grained invalidations. Only when the user with id x changes, the settings object with a reference id of x is invalidated.

The configuration for this could live in the regular config object, passed to build:

{
  user: {
    api: userApi
  },
  userSettings: {
    api: userSettingsApi,
    associatedEntity: 'user',
    associationIdFrom: (userSettings) => userSettings.userId
  }
}

Alternatively several such associations could be defined:

{
  user: {
    api: userApi
  },
  userSettings: {
    api: userSettingsApi,
    associatedEntities: [{ entity: 'user', referenceIdFrom: (userSettings) => userSettings.userId }]
  }
}

Does this sound like a legitimate and valuable use case?

herrherrmann commented 6 years ago

This feature would definitely make a lot of sense!

I'd try to keep the definition footprint a bit more "idiomatic" and smaller, e.g. like so:

{
  user: {
    api: userApi
  },
  userSettings: {
    api: userSettingsApi,
    linkedEntities: {
      user: {
        idFrom: (userSettings) => userSettings.userId
      }
    }
  }
}

At least this way the associated entity user "looks" a bit more like its own definition further above. I'd also favor a wording like "linkedEntities", "relatedEntities" or maybe even something like "invalidatesFrom"? But those are just details then!

LFDM commented 6 years ago

Important details though, because changing the syntax after the fact is typically not so cool 😊 But good point about following the definition practice from elsewhere. That's also what some plugins do for example (denormalizer)

petercrona commented 6 years ago

Just a small detail, rather than "following" the definition, we should be inspired by good examples ;)

Do you think it is enough to always invalidate the associated entity? Or do we need rules that control when to invalidate? I'm afraid that people end up invalidating their entities to often, and then we introduced complexity without really knowing/strongly believing that it will speed up things and reduce how much data is sent over the wire in the end.