[Log] Apollo: Getting Started

ยท

2 min read

Official reference

Create a project directory.

mkdir apollo-server
cd apollo-server
npm init -y

Install dependencies

npm install apollo-server graphql

Create an index.js.

touch index.js

Write code.

const { ApolloServer, gql } = require("apollo-server");

const typeDefs = gql`
  type Mountain {
    name: String
    elevation: Int
    first_ascent: [String]
  }

  type Query {
    mountains: [Mountain]
  }
`;

const mountains = [
  {
    name: "Mount Everest",
    elevation: 8848,
    first_ascent:["Edmund Hillary", "Tenzing Norgay"]
  },
  {
    name: "K2",
    elevation: 8610,
    first_ascent:["Achille Compagnoni", "Lino Lacedelli"]
  }
];

const resolvers = {
  Query: {
    mountains: () => mountains
  }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`๐Ÿš€ Server ready at ${url}`);
});

Start the server

node index.js

Output

๐Ÿš€ Server ready at http://localhost:4000/

You can access GraphQL Playground if you open the link. Let's execute a query string.

{
  mountains{
    name
    elevation
    first_ascent
  }
}

Output

{
  "data": {
    "mountains": [
      {
        "name": "Mount Everest",
        "elevation": 8848,
        "first_ascent": [
          "Edmund Hillary",
          "Tenzing Norgay"
        ]
      },
      {
        "name": K2,
        "elevation": 8610,
        "first_ascent": [
          "Achille Compagnoni",
          "Lino Lacedelli"
        ]
      }
    ]
  }
}