Skip to content

Instantly share code, notes, and snippets.

@danielrearden
Last active December 30, 2020 12:41
Show Gist options
  • Save danielrearden/8ae1b7d95aac06d41998ae1502674051 to your computer and use it in GitHub Desktop.
Save danielrearden/8ae1b7d95aac06d41998ae1502674051 to your computer and use it in GitHub Desktop.
test.ts
/**
* Here we have type definitions and resolvers for a GraphQL schema. Also shown is the type for the context object passed
* to each resolver (other types have been omitted for brevity). Each resolver has one issue with it that will cause
* GraphQL to return an error if that field is requested. In a few sentences, explain what is wrong with each resolver
* and what you would change to fix it.
*/
interface Context {
db: DB;
rest: Rest;
}
interface DB {
getCommentsByPostId: (id: string) => Promise<Comment[]>;
getPosts: () => Promise<Post[]>;
getUsers: () => Promise<User[]>;
getUserById: (id: string) => Promise<User>;
}
interface User {
id: string;
firstName: string;
lastName: string;
}
interface Post {
id: string;
title: string;
body: string;
}
interface Comment {
id: string;
body: string;
}
interface Rest {
getPayments: (
cb: (error: Error | null, payments: Payment[]) => void
) => void;
}
interface Payment {
id: string;
amount: number;
}
const typeDefs = `
type Query {
payments: [Payment!]!
posts: [Post!]!
user(id: ID!): User
users: [User!]!
}
type Payment {
id: ID!
amount: Float!
}
type Post {
id: ID!
title: String!
body: String!
comments: [Comment!]!
}
type Comment {
id: ID!
body: String!
}
type User {
id: ID!
fullName: String!
}
`;
const resolvers = {
Query: {
payments: (_root, _args, ctx) => {
return ctx.rest.getPayments((error, payments) => {
return payments;
});
},
posts: async (_root, _args, ctx) => {
return ctx.db.getPosts().then((posts) => {
return Promise.all(
posts.map((post) => {
post.comments = ctx.db.getCommentsByPostId(post.id);
})
);
});
},
users: async (_args, ctx) => {
return ctx.db.getUsers();
},
user: (_root, args, ctx) => {
return ctx.db.getUserById(args.id).then((user) => {
return user;
});
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment