import url from 'url';
import express from 'express';
import axios from 'axios';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import gql from 'graphql-tag';
import config from '../../src/config';
const router = express.Router();

const client = new ApolloClient({
  networkInterface: {
    query: ({ query, variables, operationName }) =>
      axios.post(`${config.serverUrl}/graphql`, { query, variables, operationName })
        .then(response => response.data)
        .catch(error => error)
  }
});


const sendQuery = async (query) => {
  const response = await client.query({ query })
    .catch((error) => {
      throw new Error(error);
    });
  return response.data;
};


router.get('/posts', async (req, res) => {
  try {
    const query = gql`
      {
        posts(first: 20) {
          pageInfo {
            endCursor
            hasNextPage
          }
          totalCount
          edges {
            cursor
            node {
              id
              title
            }
          }
        }
      }
    `;
    const { posts } = await sendQuery(query);
    res.json(posts);
  } catch (e) {
    res.status(400).json({ errors: [{ message: e.message }] });
  }
});


router.get('/posts/:id', async (req, res) => {
  try {
    const { data } = await sendQuery(`query { post(_id:"${req.params.id}") { id, title, body } }`);
    res.json(data.post);
  } catch (e) {
    res.status(400).json({ errors: [{ message: e.message }] });
  }
});


router.get('/home', async (req, res) => {
  try {
    const { data } = await sendQuery(`
      query {
        latestPosts: posts { id, title }
      }
    `);
    res.json(data);
  } catch (e) {
    res.status(400).json({ errors: [{ message: e.message }] });
  }
});


router.post('/login', (req, res) => {
  try {
    if (req.body.password !== '123') {
      throw new Error('Invalid password');
    }
    res.json({
      id: 809090,
      username: req.body.username,
      firstName: 'Dummy first name'
    });
  } catch (e) {
    res.status(400).json({ message: e.message });
  }
});


export default router;

@@ -799,19 +799,8 @@
 osts
-(first: 20)
  %7B%0A 
@@ -822,42 +822,19 @@
 fo %7B
-%0A            endCursor%0A           
+ endCursor,
  has
@@ -841,26 +841,16 @@
 NextPage
-%0A         
  %7D%0A     
@@ -924,57 +924,18 @@
 de %7B
-%0A              id%0A              title%0A           
+ id, title
  %7D%0A 
@@ -1452,33 +1452,29 @@
  %7B%0A    const
- %7B
  data
- %7D
  = await sen
@@ -1480,24 +1480,27 @@
 ndQuery(
+gql
 %60%0A      
 query %7B%0A
@@ -1491,22 +1491,16 @@
 %60%0A      
-query 
 %7B%0A      
@@ -1519,28 +1519,98 @@
 s: posts
- %7B id, title
+(first: 20) %7B%0A          edges %7B%0A            node %7B id, title %7D%0A          %7D%0A       
  %7D%0A     

Update graphql