I developed an API using node with GraphQL, when I add the DataLoaders, the resolvers starts returning wrong data, like I pass 4 Ids [3, 3, 1, 2], the batch function find in Database and return ordered like [1, 2, 3] and when return to the resolver, the first object who has id 3, receive the response with id 1.
Project Packages versions ->
"dataloader": "1.3.0",
"express": "^4.17.1",
"express-graphql": "^0.11.0",
"graphql": "^15.3.0",
"graphql-fields": "^2.0.3",
"graphql-tools": "^6.2.4",
I also tried to use the dataloader latest version, but didn't worked
Follow my code.
Resolver ->
Address: {
idCity: (parent, args, { db, dataloaders: { cityLoader } }: { db: DbConnection, dataloaders: DataLoaders }, info: GraphQLResolveInfo) => {
return cityLoader.load({ info, key: parent.get('idCity') })
.catch(handleError);
}
},
Data Loader Factory ->
cityLoader: new DataLoader<DataLoaderParam<number>, CityInstance>(
(params: DataLoaderParam<number>[]) => CityLoader.batchCities(this.db.City, params, this.requestedFields),
{
cacheKeyFn: (param: DataLoaderParam<number[]>) => param.key
}
),
DataLoaderParam ->
export interface DataLoaderParam<T> {
key: T;
info: GraphQLResolveInfo;
}
City Loader ->
export class CityLoader {
static async batchCities(City: CityModel, params: DataLoaderParam<number>[], requestedFields: RequestedFields) {
const ids: number[] = params.map(item => item.key);
return City["findAll"]({
where: { id: { $in: ids } },
attributes: requestedFields.getFields(params[0].info, { keep: ['id'], exclude: [] })
});
}
}