Apollo - стек данных на JavaScript, основанный на GraphQL. Я ожидаю, что Apollo очень прост и интуитивно понятен в использовании GraphQL, поэтому я хочу попробовать, насколько легко я могу его использовать. Ниже приведен код, который я надеюсь быть наглядным в качестве минимального примера. Предполагается, что вы знакомы с Node.js и Express.

Код сервера (server.js)

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const apolloExpress = require('apollo-server').apolloExpress;
const graphiqlExpress = require('apollo-server').graphiqlExpress;
const makeExecutableSchema =
  require('graphql-tools').makeExecutableSchema;

const postsData = [
  { name: 'John', title: 'Hello', content: 'pen pineapple' },
  { name: 'Mike', title: 'Hi', content: 'apple pen' },
];

const typeDefs = [`
  type Post {
    name: String
    title: String
    content: String
  }
  type Query {
    posts(keyword: String): [Post]
  }
  type Mutation {
    addPost(name: String, title: String, content: String): Post
  }
  schema {
    query: Query
    mutation: Mutation
  }
  `];

const resolvers = {
  Query: {
    posts(root, args) {
      return postsData.filter(post =>
        !args.keyword || post.content.indexOf(args.keyword) >= 0);
    },
  },
  Mutation: {
    addPost(root, doc) {
      postsData.push(doc);
      return doc;
    },
  },
};

const schema = makeExecutableSchema({ typeDefs, resolvers });
const app = express();

app.use('/graphql', bodyParser.json(), apolloExpress({ schema }));
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
app.use('/', express.static(path.join(__dirname, 'public')));

app.listen(process.env.PORT || 3000);

Клиентский код (общедоступный / vanilla.html)

<html>
  <head>
    <title>Vanilla JS example for Apollo</title>
    <script src="https://wzrd.in/standalone/[email protected]">
    </script>
    <script src="https://wzrd.in/standalone/[email protected]">
    </script>
  </head>
  <body>
    <h1>Vanilla JS example for Apollo</h1>
    <pre id="result"></pre>
    <input id="content" />
    <button id="add">Add</button>
    <script src="vanilla.js"></script>
  </body>
</html>

Клиентский код (общедоступный / vanilla.js)

const ApolloClient = apolloClient.default;
const gql = graphqlTag.default;

const client = new ApolloClient();

const query = gql`query {
  posts {
    name
    title
    content
  }
}`;

const showResult = (posts) => {
  document.getElementById('result').innerHTML =
    JSON.stringify(posts, null, 2);
};

const observableQuery =
  client.watchQuery({ query, pollInterval: 1000 });
observableQuery.subscribe({
  next: ({ data }) => showResult(data.posts),
});

const mutation = gql`mutation ($content: String){
  addPost(name: "Mary", title: "No title", content: $content) {
    name
    title
    content
  }
}`;

document.getElementById('add').addEventListener('click', () => {
  const content = document.getElementById('content').value;
  client.mutate({ mutation, variables: { content } });
});

Резюме

Несмотря на то, что это простой пример, вам может потребоваться прочитать Документ Аполлона, чтобы понять его. Если вы хотите увидеть полный код, смотрите здесь. Также есть пример для React.