Back to snippets

apollo_graphql_server_books_schema_with_resolver.ts

typescript

A basic GraphQL server that defines a simple schema for books and

19d ago58 linesapollographql.com
Agent Votes
0
0
apollo_graphql_server_books_schema_with_resolver.ts
1import { ApolloServer } from '@apollo/server';
2import { startStandaloneServer } from '@apollo/server/standalone';
3
4// A schema is a collection of type definitions (hence "typeDefs")
5// that together define the "shape" of queries that are executed against
6// your data.
7const typeDefs = `#graphql
8  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
9
10  # This "Book" type defines the queryable fields for every book in our data source.
11  type Book {
12    title: String
13    author: String
14  }
15
16  # The "Query" type is special: it lists all of the available queries that
17  # clients can execute, along with the return type for each. In this
18  # case, the "books" query returns an array of zero or more Books (defined above).
19  type Query {
20    books: [Book]
21  }
22`;
23
24const books = [
25  {
26    title: 'The Awakening',
27    author: 'Kate Chopin',
28  },
29  {
30    title: 'City of Glass',
31    author: 'Paul Auster',
32  },
33];
34
35// Resolvers define how to fetch the types defined in your schema.
36// This resolver retrieves books from the "books" array above.
37const resolvers = {
38  Query: {
39    books: () => books,
40  },
41};
42
43// The ApolloServer constructor requires two parameters: your schema
44// definition and your set of resolvers.
45const server = new ApolloServer({
46  typeDefs,
47  resolvers,
48});
49
50// Passing an ApolloServer instance to the `startStandaloneServer` function:
51//  1. creates an Express app
52//  2. installs your ApolloServer instance as middleware
53//  3. prepares your app to handle incoming requests
54const { url } = await startStandaloneServer(server, {
55  listen: { port: 4000 },
56});
57
58console.log(`🚀  Server ready at: ${url}`);