GraphQL Schema & Resolver
Apollo Server schema definition with typed resolvers and context.
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
const typeDefs = `#graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
body: String!
author: User!
}
type Query {
users: [User!]!
user(id: ID!): User
posts: [Post!]!
}
type Mutation {
createPost(title: String!, body: String!, authorId: ID!): Post!
}
`;
const resolvers = {
Query: {
users: (_: unknown, __: unknown, { db }: Context) => db.users.findAll(),
user: (_: unknown, { id }: { id: string }, { db }: Context) =>
db.users.findById(id),
posts: (_: unknown, __: unknown, { db }: Context) => db.posts.findAll(),
},
Mutation: {
createPost: (_: unknown, args: CreatePostArgs, { db }: Context) =>
db.posts.create(args),
},
User: {
posts: (user: User, _: unknown, { db }: Context) =>
db.posts.findByAuthor(user.id),
},
Post: {
author: (post: Post, _: unknown, { db }: Context) =>
db.users.findById(post.authorId),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`GraphQL ready at ${url}`);