TExcelTAD
Home › GraphQL › Mini Project: Library API

Mini Project: Library API

Let's put the whole course together and build the GraphQL API for a small public library. Members can browse the catalogue, see who wrote what, borrow and return books, and librarians can see all loans. We'll build it in four steps, each one a complete, runnable program:

  1. Schema and queries: types, relationships and a resolver map.
  2. Mutations with business rules: borrowing and returning, with user errors and authorization.
  3. Performance: batching author lookups with a loader and paginating the catalogue.
  4. The finished API: everything together, protected by a depth limit, with a small test suite.

Step 1: schema and queries

We start with the data model. Books have authors; authors have books. Our "database" is a few arrays, and the relationships are stored as ids, just like real tables:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const db = {
  authors: [
    { id: 'a1', name: 'Ursula K. Le Guin', born: 1929 },
    { id: 'a2', name: 'Terry Pratchett', born: 1948 },
  ],
  books: [
    { id: 'b1', title: 'A Wizard of Earthsea', year: 1968, authorId: 'a1', copies: 2 },
    { id: 'b2', title: 'The Dispossessed', year: 1974, authorId: 'a1', copies: 1 },
    { id: 'b3', title: 'Guards! Guards!', year: 1989, authorId: 'a2', copies: 3 },
    { id: 'b4', title: 'Small Gods', year: 1992, authorId: 'a2', copies: 1 },
  ],
};

const typeDefs = `
  type Author {
    id: ID!
    name: String!
    born: Int
    books: [Book!]!
  }

  type Book {
    id: ID!
    title: String!
    year: Int!
    author: Author!
    copies: Int!
  }

  type Query {
    books(search: String): [Book!]!
    book(id: ID!): Book
    authors: [Author!]!
  }
`;

const resolvers = {
  Query: {
    books: (_, { search }) =>
      db.books.filter((b) => !search || b.title.toLowerCase().includes(search.toLowerCase())),
    book: (_, { id }) => db.books.find((b) => b.id === id) ?? null,
    authors: () => db.authors,
  },
  Author: {
    books: (author) => db.books.filter((b) => b.authorId === author.id),
  },
  Book: {
    author: (book) => db.authors.find((a) => a.id === book.authorId),
  },
};

function makeExecutableSchema({ typeDefs, resolvers }) {
  const schema = buildSchema(typeDefs);
  for (const [typeName, fields] of Object.entries(resolvers)) {
    const typeFields = schema.getType(typeName).getFields();
    for (const [fieldName, resolve] of Object.entries(fields)) typeFields[fieldName].resolve = resolve;
  }
  return schema;
}

const schema = makeExecutableSchema({ typeDefs, resolvers });

const run = async (source, variableValues) => {
  const result = await graphql({ schema, source, variableValues });
  console.log(JSON.stringify(result.data ?? result.errors.map((e) => e.message)));
};

await run('{ books(search: "gods") { title year author { name } } }');
await run('{ authors { name books { title } } }');
await run('query One($id: ID!) { book(id: $id) { title author { born } } }', { id: 'b2' });
{"books":[{"title":"Small Gods","year":1992,"author":{"name":"Terry Pratchett"}}]}
{"authors":[{"name":"Ursula K. Le Guin","books":[{"title":"A Wizard of Earthsea"},{"title":"The Dispossessed"}]},{"name":"Terry Pratchett","books":[{"title":"Guards! Guards!"},{"title":"Small Gods"}]}]}
{"book":{"title":"The Dispossessed","author":{"born":1929}}}

The resolver map only contains fields that need logic. Book.title, Author.name and friends fall back to the default resolver, which reads the property from the row.

Step 2: borrowing and returning

Now the business rules:

  • Only logged-in members may borrow; the member comes from the context, never from an argument.
  • A book can be borrowed only while copies are available, and a member can't borrow the same book twice.
  • Expected problems (no copies left) are returned as userErrors in a payload type; unexpected ones (not logged in) are GraphQL errors with a code.
  • Librarians may list all loans.
js · try it yourself
import { graphql, buildSchema, GraphQLError } from 'graphql';

const db = {
  books: [
    { id: 'b1', title: 'A Wizard of Earthsea', copies: 2 },
    { id: 'b4', title: 'Small Gods', copies: 1 },
  ],
  loans: [],
  nextLoanId: 1,
};

const typeDefs = `
  type Book { id: ID!, title: String!, available: Int! }
  type Loan { id: ID!, book: Book!, memberId: ID! }
  type UserError { message: String! }
  type LoanPayload { loan: Loan, userErrors: [UserError!]! }

  type Query { books: [Book!]!, allLoans: [Loan!]! }
  type Mutation {
    borrowBook(bookId: ID!): LoanPayload!
    returnBook(loanId: ID!): LoanPayload!
  }
`;

// --- business logic (no GraphQL in here) ---
const library = {
  available: (book) => book.copies - db.loans.filter((l) => l.bookId === book.id).length,
  borrow(member, bookId) {
    const book = db.books.find((b) => b.id === bookId);
    if (!book) return { userErrors: [{ message: `No book with id ${bookId}` }] };
    if (db.loans.some((l) => l.bookId === bookId && l.memberId === member.id)) {
      return { userErrors: [{ message: `You already have "${book.title}"` }] };
    }
    if (this.available(book) === 0) return { userErrors: [{ message: `"${book.title}" is not available` }] };
    const loan = { id: `L${db.nextLoanId++}`, bookId, memberId: member.id };
    db.loans.push(loan);
    return { loan, userErrors: [] };
  },
  giveBack(member, loanId) {
    const index = db.loans.findIndex((l) => l.id === loanId && l.memberId === member.id);
    if (index === -1) return { userErrors: [{ message: 'Loan not found' }] };
    const [loan] = db.loans.splice(index, 1);
    return { loan, userErrors: [] };
  },
};

const requireMember = (context) => {
  if (!context.member) throw new GraphQLError('Please log in', { extensions: { code: 'UNAUTHENTICATED' } });
  return context.member;
};

const resolvers = {
  Query: {
    books: () => db.books,
    allLoans: (_, __, context) => {
      if (requireMember(context).role !== 'librarian') {
        throw new GraphQLError('Librarians only', { extensions: { code: 'FORBIDDEN' } });
      }
      return db.loans;
    },
  },
  Mutation: {
    borrowBook: (_, { bookId }, context) => library.borrow(requireMember(context), bookId),
    returnBook: (_, { loanId }, context) => library.giveBack(requireMember(context), loanId),
  },
  Book: { available: (book) => library.available(book) },
  Loan: { book: (loan) => db.books.find((b) => b.id === loan.bookId) },
};

function makeExecutableSchema({ typeDefs, resolvers }) {
  const schema = buildSchema(typeDefs);
  for (const [typeName, fields] of Object.entries(resolvers)) {
    const typeFields = schema.getType(typeName).getFields();
    for (const [fieldName, resolve] of Object.entries(fields)) typeFields[fieldName].resolve = resolve;
  }
  return schema;
}
const schema = makeExecutableSchema({ typeDefs, resolvers });

const members = {
  ana: { id: 'm1', role: 'member' },
  ben: { id: 'm2', role: 'member' },
  liz: { id: 'm3', role: 'librarian' },
};

const BORROW = 'mutation Borrow($id: ID!) { borrowBook(bookId: $id) { loan { id book { title available } } userErrors { message } } }';

const as = async (who, source, variableValues) => {
  const result = await graphql({ schema, source, variableValues, contextValue: { member: members[who] ?? null } });
  const out = result.errors ? `${result.errors[0].extensions.code}: ${result.errors[0].message}` : JSON.stringify(result.data);
  console.log(`${who.padEnd(5)} ${out}`);
};

await as('ana', BORROW, { id: 'b4' });
await as('ben', BORROW, { id: 'b4' });
await as('ana', BORROW, { id: 'b4' });
await as('guest', BORROW, { id: 'b1' });
await as('ben', '{ allLoans { id } }');
await as('liz', '{ allLoans { id memberId book { title } } }');
await as('ana', 'mutation { returnBook(loanId: "L1") { loan { book { available } } userErrors { message } } }');
await as('ben', BORROW, { id: 'b4' });
ana   {"borrowBook":{"loan":{"id":"L1","book":{"title":"Small Gods","available":0}},"userErrors":[]}}
ben   {"borrowBook":{"loan":null,"userErrors":[{"message":"\"Small Gods\" is not available"}]}}
ana   {"borrowBook":{"loan":null,"userErrors":[{"message":"You already have \"Small Gods\""}]}}
guest UNAUTHENTICATED: Please log in
ben   FORBIDDEN: Librarians only
liz   {"allLoans":[{"id":"L1","memberId":"m1","book":{"title":"Small Gods"}}]}
ana   {"returnBook":{"loan":{"book":{"available":1}},"userErrors":[]}}
ben   {"borrowBook":{"loan":{"id":"L2","book":{"title":"Small Gods","available":0}},"userErrors":[]}}

Follow the story: Ana borrows the only copy of Small Gods, Ben is told it's unavailable, Ana can't borrow it twice, a guest must log in, Ben can't see all loans but the librarian Liz can, Ana returns the book, and now Ben gets it.

Step 3: batching and pagination

The catalogue will grow, so books becomes a connection with cursors, and Book.author goes through a per-request loader, so a page of books costs one author query, not one per book:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const db = {
  authors: [
    { id: 'a1', name: 'Ursula K. Le Guin' },
    { id: 'a2', name: 'Terry Pratchett' },
    { id: 'a3', name: 'N. K. Jemisin' },
  ],
  books: [
    { id: 'b1', title: 'A Wizard of Earthsea', authorId: 'a1' },
    { id: 'b2', title: 'The Dispossessed', authorId: 'a1' },
    { id: 'b3', title: 'Guards! Guards!', authorId: 'a2' },
    { id: 'b4', title: 'Small Gods', authorId: 'a2' },
    { id: 'b5', title: 'The Fifth Season', authorId: 'a3' },
  ],
};

const sqlLog = [];
const repo = {
  authorsByIds(ids) {
    sqlLog.push(`authors WHERE id IN (${ids.join(',')})`);
    return db.authors.filter((a) => ids.includes(a.id));
  },
};

function createLoader(batchFn) {
  const cache = new Map();
  let queue = [];
  return {
    load(key) {
      if (!cache.has(key)) {
        cache.set(key, new Promise((resolve) => {
          queue.push({ key, resolve });
          if (queue.length === 1) {
            queueMicrotask(async () => {
              const batch = queue;
              queue = [];
              const values = await batchFn(batch.map((b) => b.key));
              batch.forEach((b, i) => b.resolve(values[i]));
            });
          }
        }));
      }
      return cache.get(key);
    },
  };
}

const typeDefs = `
  type Author { id: ID!, name: String! }
  type Book { id: ID!, title: String!, author: Author! }
  type BookEdge { cursor: String!, node: Book! }
  type PageInfo { hasNextPage: Boolean!, endCursor: String }
  type BookConnection { edges: [BookEdge!]!, pageInfo: PageInfo!, totalCount: Int! }
  type Query { books(first: Int = 2, after: String): BookConnection! }
`;

const encodeCursor = (id) => btoa(`book:${id}`);
const decodeCursor = (cursor) => atob(cursor).slice('book:'.length);

const resolvers = {
  Query: {
    books: (_, { first, after }) => {
      const size = Math.min(Math.max(first, 1), 50);              // clamp page size
      const start = after ? db.books.findIndex((b) => b.id === decodeCursor(after)) + 1 : 0;
      const page = db.books.slice(start, start + size);
      return {
        edges: page.map((b) => ({ cursor: encodeCursor(b.id), node: b })),
        pageInfo: { hasNextPage: start + size < db.books.length, endCursor: page.length ? encodeCursor(page.at(-1).id) : null },
        totalCount: db.books.length,
      };
    },
  },
  Book: {
    author: (book, _, { loaders }) => loaders.author.load(book.authorId),
  },
};

function makeExecutableSchema({ typeDefs, resolvers }) {
  const schema = buildSchema(typeDefs);
  for (const [typeName, fields] of Object.entries(resolvers)) {
    const typeFields = schema.getType(typeName).getFields();
    for (const [fieldName, resolve] of Object.entries(fields)) typeFields[fieldName].resolve = resolve;
  }
  return schema;
}
const schema = makeExecutableSchema({ typeDefs, resolvers });

const createContext = () => ({
  loaders: {
    author: createLoader(async (ids) => {
      const rows = repo.authorsByIds(ids);
      return ids.map((id) => rows.find((r) => r.id === id));
    }),
  },
});

const PAGE = `query Catalogue($after: String) {
  books(first: 2, after: $after) {
    totalCount
    edges { node { title author { name } } }
    pageInfo { hasNextPage endCursor }
  }
}`;

let after = null;
do {
  sqlLog.length = 0;
  const { data } = await graphql({ schema, source: PAGE, variableValues: { after }, contextValue: createContext() });
  const titles = data.books.edges.map((e) => `${e.node.title} (${e.node.author.name})`);
  console.log(titles.join(' | '));
  console.log(`   ${sqlLog.length} author query: ${sqlLog[0]}`);
  after = data.books.pageInfo.hasNextPage ? data.books.pageInfo.endCursor : null;
} while (after);
A Wizard of Earthsea (Ursula K. Le Guin) | The Dispossessed (Ursula K. Le Guin)
   1 author query: authors WHERE id IN (a1)
Guards! Guards! (Terry Pratchett) | Small Gods (Terry Pratchett)
   1 author query: authors WHERE id IN (a2)
The Fifth Season (N. K. Jemisin)
   1 author query: authors WHERE id IN (a3)

Each page cost exactly one author query, and the page with two Le Guin books asked for a1 once, thanks to the loader's cache.

Step 4: the finished API, secured and tested

Finally, the complete library: queries, mutations, loaders, a depth-limit validation rule and the parse → validate → execute pipeline a server would run for every request. A handful of tests check that it all fits together:

js · try it yourself
import { buildSchema, parse, validate, execute, specifiedRules, GraphQLError, Kind } from 'graphql';

// ---------- data ----------
const db = {
  authors: [{ id: 'a1', name: 'Ursula K. Le Guin' }, { id: 'a2', name: 'Terry Pratchett' }],
  books: [
    { id: 'b1', title: 'A Wizard of Earthsea', authorId: 'a1', copies: 1 },
    { id: 'b3', title: 'Guards! Guards!', authorId: 'a2', copies: 2 },
  ],
  loans: [],
};

// ---------- schema ----------
const typeDefs = `
  type Author { id: ID!, name: String!, books: [Book!]! }
  type Book { id: ID!, title: String!, author: Author!, available: Int! }
  type Loan { id: ID!, book: Book! }
  type UserError { message: String! }
  type LoanPayload { loan: Loan, userErrors: [UserError!]! }
  type Member { id: ID!, name: String!, loans: [Loan!]! }
  type Query { books: [Book!]!, me: Member }
  type Mutation { borrowBook(bookId: ID!): LoanPayload! }
`;

const available = (book) => book.copies - db.loans.filter((l) => l.bookId === book.id).length;

const resolvers = {
  Query: {
    books: () => db.books,
    me: (_, __, { member }) => member,
  },
  Mutation: {
    borrowBook: (_, { bookId }, { member }) => {
      if (!member) throw new GraphQLError('Please log in', { extensions: { code: 'UNAUTHENTICATED' } });
      const book = db.books.find((b) => b.id === bookId);
      if (!book || available(book) === 0) return { loan: null, userErrors: [{ message: 'Not available' }] };
      const loan = { id: `L${db.loans.length + 1}`, bookId, memberId: member.id };
      db.loans.push(loan);
      return { loan, userErrors: [] };
    },
  },
  Member: { loans: (m) => db.loans.filter((l) => l.memberId === m.id) },
  Author: { books: (a) => db.books.filter((b) => b.authorId === a.id) },
  Book: {
    author: (b, _, { loaders }) => loaders.author.load(b.authorId),
    available: (b) => available(b),
  },
  Loan: { book: (l) => db.books.find((b) => b.id === l.bookId) },
};

const schema = buildSchema(typeDefs);
for (const [typeName, fields] of Object.entries(resolvers)) {
  for (const [fieldName, resolve] of Object.entries(fields)) schema.getType(typeName).getFields()[fieldName].resolve = resolve;
}

// ---------- per-request context ----------
let authorQueries = 0;
function createLoader(batchFn) {
  const cache = new Map();
  let queue = [];
  return {
    load(key) {
      if (!cache.has(key)) {
        cache.set(key, new Promise((resolve) => {
          queue.push({ key, resolve });
          if (queue.length === 1) queueMicrotask(async () => {
            const batch = queue;
            queue = [];
            const values = await batchFn(batch.map((b) => b.key));
            batch.forEach((b, i) => b.resolve(values[i]));
          });
        }));
      }
      return cache.get(key);
    },
  };
}
const createContext = (member) => ({
  member,
  loaders: {
    author: createLoader(async (ids) => {
      authorQueries += 1;
      return ids.map((id) => db.authors.find((a) => a.id === id));
    }),
  },
});

// ---------- security: depth limit ----------
const MAX_DEPTH = 4;
function DepthLimitRule(context) {
  const fragments = Object.fromEntries(
    context.getDocument().definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((d) => [d.name.value, d]),
  );
  const depthOf = (set, depth, seen = new Set()) =>
    Math.max(depth, ...set.selections.map((sel) => {
      if (sel.kind === Kind.FIELD) return sel.selectionSet ? depthOf(sel.selectionSet, depth + 1, seen) : depth + 1;
      if (sel.kind === Kind.INLINE_FRAGMENT) return depthOf(sel.selectionSet, depth, seen);
      const name = sel.name.value;
      if (seen.has(name) || !fragments[name]) return depth;
      return depthOf(fragments[name].selectionSet, depth, new Set([...seen, name]));
    }));
  return {
    OperationDefinition(node) {
      const depth = depthOf(node.selectionSet, 0);
      if (depth > MAX_DEPTH) context.reportError(new GraphQLError(`Query is too deep (${depth} > ${MAX_DEPTH})`, { nodes: node }));
    },
  };
}

// ---------- the request pipeline ----------
async function handle({ query, variables, member = null }) {
  let doc;
  try {
    doc = parse(query);
  } catch (e) {
    return { status: 400, body: { errors: [{ message: e.message }] } };
  }
  const errors = validate(schema, doc, [...specifiedRules, DepthLimitRule]);
  if (errors.length) return { status: 400, body: { errors: errors.map((e) => ({ message: e.message })) } };
  const result = await execute({ schema, document: doc, variableValues: variables, contextValue: createContext(member) });
  return { status: 200, body: JSON.parse(JSON.stringify(result)) };
}

// ---------- tests ----------
const ana = { id: 'm1', name: 'Ana' };
const report = [];
const test = async (name, fn) => {
  try { await fn(); report.push(`PASS ${name}`); } catch (e) { report.push(`FAIL ${name}: ${e.message}`); }
};
const expect = (actual, expected) => {
  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
    throw new Error(`expected ${JSON.stringify(expected)} but got ${JSON.stringify(actual)}`);
  }
};

await test('lists books with authors in one batch', async () => {
  authorQueries = 0;
  const res = await handle({ query: '{ books { title author { name } } }' });
  expect(res.body.data.books.map((b) => b.author.name), ['Ursula K. Le Guin', 'Terry Pratchett']);
  expect(authorQueries, 1);
});

await test('guests cannot borrow', async () => {
  const res = await handle({ query: 'mutation { borrowBook(bookId: "b1") { loan { id } } }' });
  expect(res.body.errors[0].extensions.code, 'UNAUTHENTICATED');
});

await test('members borrow and see their loans', async () => {
  const borrow = await handle({ member: ana, query: 'mutation B($id: ID!) { borrowBook(bookId: $id) { loan { id } userErrors { message } } }', variables: { id: 'b1' } });
  expect(borrow.body.data.borrowBook, { loan: { id: 'L1' }, userErrors: [] });
  const me = await handle({ member: ana, query: '{ me { name loans { book { title available } } } }' });
  expect(me.body.data.me, { name: 'Ana', loans: [{ book: { title: 'A Wizard of Earthsea', available: 0 } }] });
});

await test('unavailable books produce a user error', async () => {
  const res = await handle({ member: ana, query: 'mutation { borrowBook(bookId: "b1") { loan { id } userErrors { message } } }' });
  expect(res.body.data.borrowBook.userErrors, [{ message: 'Not available' }]);
});

await test('deep queries are rejected before execution', async () => {
  const res = await handle({ query: '{ books { author { books { author { books { title } } } } } }' });
  expect([res.status, res.body.errors[0].message], [400, 'Query is too deep (6 > 4)']);
});

await test('typos get a helpful message', async () => {
  const res = await handle({ query: '{ books { titel } }' });
  expect(res.body.errors[0].message, 'Cannot query field "titel" on type "Book". Did you mean "title"?');
});

console.log(report.join('\n'));
PASS lists books with authors in one batch
PASS guests cannot borrow
PASS members borrow and see their loans
PASS unavailable books produce a user error
PASS deep queries are rejected before execution
PASS typos get a helpful message

All six tests pass. You've built a GraphQL API with:

  • an SDL schema and a resolver map that follows relationships both ways,
  • mutations with business rules, payload types and userErrors,
  • authentication from the context and authorization checks,
  • a per-request loader that removes N+1 queries,
  • cursor pagination for the growing catalogue (step 3),
  • a depth limit that rejects abusive queries before they run,
  • and tests that exercise the real request pipeline.

Ideas to extend it

  1. Add a dueDate to loans with a custom Date scalar, and a overdueLoans field for librarians.
  2. Add searchCatalogue(text: String!): [SearchHit!]! with union SearchHit = Book | Author.
  3. Add a loanReturned subscription using the pub/sub pattern from the Subscriptions lesson.
  4. Wrap handle in a real server: GraphQL Yoga or graphql-http with Express (see Serving over HTTP).
  5. Replace the arrays with SQLite or PostgreSQL, keeping the resolvers unchanged: only the repository and the loaders' batch functions need to know about SQL.

Test yourself

In this project, where does the borrowing member come from?

  1. A memberId argument
  2. The per-request context
  3. A global variable
  4. The root value

Why did a page of books with two books by the same author trigger only one author lookup?

  1. The author was hard-coded
  2. The loader batched the keys and cached the repeated id
  3. GraphQL skips duplicate fields
  4. Pagination removed the second book

When is the depth-limit rule applied?

  1. After execution
  2. During validation, before any resolver runs
  3. Only on mutations
  4. When the server starts