Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.
The problem
A product catalog API built with Apollo Server 4, TypeGraphQL and TypeORM returns products, their reviews, and each review's author. A DataLoader for users is created once per request and placed in the context to batch author lookups, but the database still receives one user query per review.
Stack:
- Node.js: 22
- Apollo Server: v4.x
- TypeORM: v0.3.x (with PostgreSQL v14 as the database)
dataloaderlibrary: v2.xtype-graphql: v2.x (for schema and resolver generation)
What happens: fetching 10 products with 5 reviews each produces 50 separate SELECT ... FROM users WHERE id = $1 queries, instead of one batched query for the distinct author IDs.
The relevant code, simplified:
src/index.ts (Apollo Server Setup & Context):
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSchema } from 'type-graphql';
import { AppDataSource } from './data-source'; // TypeORM data source
import { ProductResolver } from './resolvers/ProductResolver';
import { ReviewResolver } from './resolvers/ReviewResolver';
import { UserDataLoader } from './dataLoaders'; // DataLoader factory
import { User } from './entities/User';
import { Repository } from 'typeorm';
export interface MyContext {
dataSources: {
userRepository: Repository<User>;
};
dataLoaders: {
userLoader: UserDataLoader;
};
}
async function main() {
await AppDataSource.initialize();
const schema = await buildSchema({
resolvers: [ProductResolver, ReviewResolver],
});
const server = new ApolloServer<MyContext>({ schema });
const { url } = await startStandaloneServer(server, {
context: async ({ req, res }) => { // DataLoader instance created once per request
const userRepository = AppDataSource.getRepository(User);
const userLoader = new UserDataLoader(userRepository);
return {
dataSources: {
userRepository,
},
dataLoaders: {
userLoader,
},
};
},
});
console.log(`🚀 Server ready at ${url}`);
}
main().catch(console.error);src/dataLoaders.ts (User DataLoader Definition):
import DataLoader from 'dataloader';
import { In, Repository } from 'typeorm';
import { User } from './entities/User';
export class UserDataLoader extends DataLoader<string, User | null> {
constructor(userRepository: Repository<User>) {
super(async (userIds: readonly string[]) => {
// This batch function should ideally be called once per request for all unique user IDs.
console.log(`[DataLoader] Fetching users for IDs: ${userIds.join(', ')}`);
const users = await userRepository.findBy({ id: In(userIds as string[]) });
const userMap = new Map(users.map(user => [user.id, user]));
return userIds.map(id => userMap.get(id) || null);
});
}
}src/entities/User.ts, Product.ts, Review.ts (Simplified for brevity):
// Example User entity
import { BaseEntity, Column, Entity, PrimaryColumn } from 'typeorm';
@Entity()
export class User extends BaseEntity {
@PrimaryColumn() id: string;
@Column() name: string;
}
// Example Product entity (similar structure for Review)
import { BaseEntity, Column, Entity, OneToMany, PrimaryColumn } from 'typeorm';
import { Review } from './Review';
@Entity()
export class Product extends BaseEntity {
@PrimaryColumn() id: string;
@Column() name: string;
@OneToMany(() => Review, review => review.product)
reviews: Review[];
}
// Example Review entity
import { BaseEntity, Column, Entity, ManyToOne, PrimaryColumn } from 'typeorm';
import { Product } from './Product';
import { User } from './User';
@Entity()
export class Review extends BaseEntity {
@PrimaryColumn() id: string;
@Column() rating: number;
@Column() comment: string;
@Column() authorId: string; // Foreign key
@ManyToOne(() => User) author: User;
@ManyToOne(() => Product, product => product.reviews) product: Product;
}src/resolvers/ProductResolver.ts (Querying Products and Reviews):
import { Resolver, Query, FieldResolver, Root } from 'type-graphql';
import { Product } from '../entities/Product';
import { Review } from '../entities/Review';
import { AppDataSource } from '../data-source';
@Resolver(Product)
export class ProductResolver {
@Query(() => [Product])
async products(): Promise<Product[]> {
// Eagerly load reviews here to avoid N+1 for reviews themselves.
return AppDataSource.getRepository(Product).find({ relations: ['reviews'] });
}
@FieldResolver(() => [Review])
reviews(@Root() product: Product): Review[] {
return product.reviews; // Reviews are already loaded by `products` query
}
}src/resolvers/ReviewResolver.ts (Field Resolver for Author):
import { Resolver, FieldResolver, Root, Ctx } from 'type-graphql';
import { Review } from '../entities/Review';
import { User } from '../entities/User';
import { MyContext } from '../index';
@Resolver(Review)
export class ReviewResolver {
@FieldResolver(() => User)
async author(@Root() review: Review, @Ctx() ctx: MyContext): Promise<User | undefined> {
console.log(`[ReviewResolver] Attempting to fetch author ${review.authorId} directly.`);
const user = await ctx.dataSources.userRepository.findOne({ where: { id: review.authorId } });
return user || undefined;
}
}Expected behaviour:
A GraphQL query for products, their reviews, and each review's author (e.g., products { id name reviews { id rating author { id name } } }) should result in:
- One query for all requested products (with reviews eagerly loaded).
- A single batch query for all unique
authorIds across all fetched reviews, executed by theUserDataLoader.
Actual behaviour:
Products and reviews load in one query, but the database log shows one users query per review, and the [DataLoader] Fetching users for IDs: message never appears.
The question: why isn't the DataLoader batching these lookups?
