This tutorial is based on https://www.apollographql.com/docs/apollo-server/getting-started/
Install node and npm. If you don't have them installed do the following 1 and 2:
1. Install homebrew from https://brew.sh/
2. Install node and npm using homebrew
Create a new folder named graphql-server-example
cd into it.
setup node project using the command: npm init --yes
This creates a package.json file.
Install apollo-server and graphql using: npm install apollo-server graphql
Create an empty index.js file with command touch index.js
Add the following content to the file:
const { ApolloServer, gql } = require('apollo-server');
// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
# Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
# This "Book" type defines the queryable fields for every book in our data source.
type Book {
title: String
author: String
}
# The "Query" type is special: it lists all of the available queries that
# clients can execute, along with the return type for each. In this
# case, the "books" query returns an array of zero or more Books (defined above).
type Query {
books: [Book]
}
`;
const books = [
{
title: 'The Awakening',
author: 'Kate Chopin',
},
{
title: 'City of Glass',
author: 'Paul Auster',
},
];
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
};
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Now run the server with the command: node index.js
Now the server should be ready. Open the given URL in a browser.
You can go to https://github.com/sulavtimsina/BasicWorkingGraphqlServer to view the code and README.
Comments
Post a Comment