Tips for Apollo Server/Client which is GraphQL Server[JavaScript]


  • Apollo Server is GraphQL server for Node.js project. Apollo server is community-based, Simplicity, Well-Performance.
  • Apollo Client is a fully-featured GraphQL client.

This article shows some tips for Apollo Server, Apollo Client with TypeScript.

🐞 Autorization by request header

Apollo Server

Apollo Server as GraphQL API server receives req.headers.token

import * as express from "express";
import { ApolloServer, gql } from "apollo-server-express";

const PORT = 4000;

const app = express();

const typeDefs = gql`
type Query {
messages: [Message]
}
type Message {
id: Int
content: String
from: String
to: String
}
`;

const resolvers = {
Query: {
messages: async (parent, args, context, info) => {
if (context.token !== 'SECRET_TOKEN') {
throw Error('Invalid token!')
}
const fields = info.fieldNodes[0].selectionSet.selections.map(
s => s.name.value
);
return await Message.find({ select: fields });
}
},
Mutation: {
createMessage: async async (parent, args, context, info) => {
}
}
};

const server = new ApolloServer({
context: ({ req, _res }) => ({
token: req.headers.token
}),
typeDefs,
resolvers
});
server.applyMiddleware({
app,
// Allow specified domain
cors: {
origin: "http://localhost:3000"
}
});

app.listen({ port: PORT }, () =>
console.log(
`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`
)
);

Apollo Client

In client side, you should pass the token in request header like this:

export function getClient(): ApolloClient<any> {
return new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
fetch,
uri: "/graphql",
headers: {
token: "SECRET_TOKEN"
}
})
});
}

More Details

If you want to know more detail, please see:

🏀 Use Apollo Client in Node.js

Installation

yarn add apollo-cache-inmemory apollo-client apollo-link-http isomorphic-fetch

Example

When using Apollo Client in Node.js, you need to prepare fetch method.
isomorphic-fetch provides fetch method like major browser.
(Please do not use node-fetch library. It does not match in this case.)

import fetch from "isomorphic-fetch";

import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { HttpLink } from "apollo-link-http";

export function getClient(): any {
return new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
fetch,
uri: "/graphql"
})
});
}

Also, if you want to set timeout configuration, please use that:

private static fetchTimeout(url, options = {} as any): any {
return new Promise((resolve, reject) => {
fetch(url, options).then(resolve, reject);
setTimeout(
reject.bind(null, {
ok: false,
status: 408
}),
options.timeout || 30000
);
});
}

🎃 How to accepts a dinamic array in Mutation

Schema definition in server side:

const schema = `
type Movie {
name: String
}
input MovieInput {
name: String
}
mutation {
addMovies(movies: [MovieInput]): [Movie]
}
`

In client side:

mutation {
addMovies(movies: [{name: 'name1'}, {name: 'name2'}]) {
name
}
}

🍄 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!