I understand how dataLoader works with simple keys:
import DataLoader from 'dataloader';
import myService from './services/service';
export default () => new DataLoader((keys: any) => Promise.all(keys.map((key: string) => myService(key))));
Is there a good pattern for using posite keys?
What if I need to call the google maps api using something like lat and long? My key would need to be a unique bination of the lat and long and I would need to split the lat and long when calling my service
const key = `${latitude}|${longitude}`;
Thinking I could use a map to lookup the value to pass to my service based on the key, is there a good pattern for use cases like this?
I understand how dataLoader works with simple keys:
import DataLoader from 'dataloader';
import myService from './services/service';
export default () => new DataLoader((keys: any) => Promise.all(keys.map((key: string) => myService(key))));
Is there a good pattern for using posite keys?
What if I need to call the google maps api using something like lat and long? My key would need to be a unique bination of the lat and long and I would need to split the lat and long when calling my service
const key = `${latitude}|${longitude}`;
Thinking I could use a map to lookup the value to pass to my service based on the key, is there a good pattern for use cases like this?
Share Improve this question asked Dec 15, 2019 at 23:00 BhetzieBhetzie 2,94010 gold badges33 silver badges44 bronze badges1 Answer
Reset to default 7You can pass in a non-string value as the key and then utilize the cacheKeyFn
option to have DataLoader transform the key into an appropriate string representation.
Produces cache key for a given load key. Useful when objects are keys and two objects should be considered equivalent.
The format of the actual cache key matters very little, as long as two identical passed in keys result in the same cache key. This can be a gotcha with objects, where two identical objects can have properties in a different order and thus result in a different string key, unless you specifically sort the properties when stringifying. For coordinates, though, this shouldn't be an issue. In your case, assuming your coordinates are passed in as an array, I imagine the following would be sufficient:
new DataLoader(
batchLoadFn,
{
cacheKeyFn: (key) => { return key.toString() }
}
)