Help me write a GraphQL server with Apollo and PostgreSQL that uses cursor-based pagination for an infinite scroll feed. I also need to solve the N+1 problem for nested fields like Users -> Posts -> Comments using dataloader.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Preparing GraphQL server with cursor pagination and DataLoader
I'm planning a concise example showing Apollo Server with PostgreSQL (using knex or pg) implementing cursor-based pagination for posts and DataLoader batching to solve N+1 in nested Users → Posts → Comments relations. The final answer will include schema definitions, DataLoader setup in context, and resolvers illustrating pagination queries and nested data fetching with batching.
Below is a minimal, end‑to‑end example of an Apollo GraphQL server (Node.js) with PostgreSQL that:
Implements cursor‑based pagination for an infinite‐scroll feed (using a created_at cursor).
Solves the N+1 problem for nested fields (User -> Post -> Comment) using DataLoader.
You can adapt it to your stack (ORM or SQL builder). Here I use pg for brevity.
// db.js
const { Pool } = require("pg");
// Replace with your own connection info
const pool = new Pool({
connectionString: process.env.DATABASE_URL || "postgres://user:pass@localhost:5432/mydb",
});
module.exports = {
query: (text, params) => pool.query(text, params),
};
Make sure you have tables like:
sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
title TEXT NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
CREATE TABLE comments (
id SERIAL PRIMARY KEY,
post_id INTEGER REFERENCES posts(id),
body TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
3) GraphQL type definitions (schema.js)
We’ll use a simple “connection” style for posts and comments to support cursor pagination.
js
// schema.js
const { gql } = require("apollo-server");
const typeDefs = gql`
scalar DateTime
type User {
id: ID!
name: String!
posts: [Post!]! # We'll batch-load these
}
type Post {
id: ID!
userId: ID!
title: String!
body: String!
createdAt: DateTime!
comments: [Comment!]! # We'll batch-load these
}
type Comment {
id: ID!
postId: ID!
body: String!
createdAt: DateTime!
}
# Cursor-based pagination
type PostEdge {
cursor: String!
node: Post!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
type Query {
# Infinite scroll: fetch posts sorted by createdAt DESC
feed(first: Int = 10, after: String): PostConnection!
# Just as an example:
user(id: ID!): User
}
`;
module.exports = typeDefs;
4) DataLoader setup (loaders.js)
We’ll create three loaders:
usersByIdLoader (if you need to fetch many users)
postsByUserIdsLoader (batch posts for multiple users)
commentsByPostIdsLoader (batch comments for multiple posts)
js
// loaders.js
const DataLoader = require("dataloader");
const db = require("./db");
const usersByIdLoader = () =>
new DataLoader(async (ids) => {
const { rows } = await db.query(
`SELECT * FROM users WHERE id = ANY($1)`,
[ids]
);
// Put rows in order matching ids:
const rowMap = new Map(rows.map((u) => [u.id, u]));
return ids.map((id) => rowMap.get(Number(id)));
});
const postsByUserIdsLoader = () =>
new DataLoader(async (userIds) => {
const { rows } = await db.query(
`SELECT * FROM posts WHERE user_id = ANY($1) ORDER BY created_at DESC`,
[userIds]
);
// Group by user_id
const map = new Map();
userIds.forEach((id) => map.set(Number(id), []));
for (const row of rows) {
map.get(row.user_id).push(row);
}
return userIds.map((id) => map.get(Number(id)));
});
const commentsByPostIdsLoader = () =>
new DataLoader(async (postIds) => {
const { rows } = await db.query(
`SELECT * FROM comments WHERE post_id = ANY($1) ORDER BY created_at ASC`,
[postIds]
);
// Group by post_id
const map = new Map();
postIds.forEach((id) => map.set(Number(id), []));
for (const row of rows) {
map.get(row.post_id).push(row);
}
return postIds.map((id) => map.get(Number(id)));
});
module.exports = {
usersByIdLoader,
postsByUserIdsLoader,
commentsByPostIdsLoader,
};
You’ll create these loaders fresh on each request and store them in the context so resolvers can call them.
5) Resolvers (resolvers.js)
Key points:
Feed uses a cursor based on created_at.
hasNextPage is determined by fetching one extra row.
User.posts and Post.comments use DataLoader to avoid N+1.
js
// resolvers.js
const { GraphQLScalarType, Kind } = require("graphql");
const db = require("./db");
const DateTime = new GraphQLScalarType({
name: "DateTime",
parseValue: (value) => new Date(value),
serialize: (value) => new Date(value).toISOString(),
parseLiteral: (ast) => (ast.kind === Kind.STRING ? new Date(ast.value) : null),
});
module.exports = {
DateTime,
Query: {
// Infinite scroll feed: posts ordered by created_at DESC
feed: async (_, { first = 10, after }, context) => {
// after is a cursor that encodes created_at
let cursor = after ? new Date(Buffer.from(after, "base64").toString("ascii")) : null;
// We’ll fetch first + 1 to check if next page exists
const params = [];
let query = `
SELECT * FROM posts
${cursor ? "WHERE created_at < $1" : ""}
ORDER BY created_at DESC
LIMIT ${first + 1}
`;
if (cursor) params.push(cursor);
const { rows } = await db.query(query, params);
// Determine pageInfo
const hasNextPage = rows.length > first;
const edges = rows.slice(0, first).map((post) => ({
cursor: Buffer.from(post.created_at.toISOString()).toString("base64"),
node: post,
}));
return {
edges,
pageInfo: {
hasNextPage,
endCursor: edges.length
? edges[edges.length - 1].cursor
: null,
},
};
},
user: async (_, { id }, context) => {
// Show how to get a single user; we could also use usersByIdLoader
const { rows } = await db.query(`SELECT * FROM users WHERE id = $1`, [id]);
return rows[0] || null;
},
},
User: {
posts: (parent, _, { loaders }) => {
// Avoid N+1: load all posts for these user IDs in batch
return loaders.postsByUserIds.load(parent.id);
},
},
Post: {
comments: (parent, _, { loaders }) => {
// Avoid N+1: load comments for each post in a batch
return loaders.commentsByPostIds.load(parent.id);
},
},
};
6) Server entry (server.js)
Create an ApolloServer and put new DataLoader instances in the context for each request.
Fetch the first 5 posts; for each subsequent request, use the endCursor from pageInfo:
graphql
query Feed($first: Int!, $after: String) {
feed(first: $first, after: $after) {
edges {
cursor
node {
id
title
createdAt
comments {
id
body
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
If hasNextPage is true, pass endCursor as after to get the next chunk. Because we rely on DataLoader, nested comments or posts won’t create N+1 queries.
Notes / Tips
Cursor: Here we base64‑encode the created_at timestamp. If you prefer to encode both created_at and id for uniqueness, that’s fine—just decode in the resolver.
Filtering: Add WHERE clauses (e.g. for user feed, hashtag filter, etc.) but keep the created_at condition in the cursor logic.
DataLoader keys: Always return arrays in the same order as keys. We used Map to group results.
Transactions & Migrations: In production, use migrations (e.g. knex, db-migrate), environment variables, and proper error handling.
ORM: You can swap pg for TypeORM, Sequelize, Prisma, etc. The pagination logic remains the same.
This should give you a solid starting point for a cursor‑based infinite scroll feed with nested batching via DataLoader.