Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apollo server 2 for hapi #1058

Merged
merged 4 commits into from
May 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 16 additions & 25 deletions packages/apollo-server-hapi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,46 +13,37 @@ npm install apollo-server-hapi

## Usage

With the Hapi plugins `graphqlHapi` and `graphiqlHapi` you can pass a route object that includes options to be applied to the route. The example below enables CORS on the `/graphql` route.
After constructing Apollo server, a hapi server can be enabled with a call to `registerServer`. Ensure that `autoListen` is set to false in the `Hapi.server` constructor.

The code below requires Hapi 17 or higher.

```js
import Hapi from 'hapi';
import { graphqlHapi } from 'apollo-server-hapi';
const Hapi = require('hapi');
const { ApolloServer } = require('apollo-server');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Odd — isn't that the express-specific class?

const { registerServer } = require('apollo-server-hapi');

const HOST = 'localhost';
const PORT = 3000;

async function StartServer() {
const server = new Hapi.server({
const server = new ApolloServer({ typeDefs, resolvers });

//Note: autoListen is required, since Apollo Server will start the listener
const app = new Hapi.server({
autoListen: false,
host: HOST,
port: PORT,
});

await server.register({
plugin: graphqlHapi,
options: {
path: '/graphql',
graphqlOptions: {
schema: myGraphQLSchema,
},
route: {
cors: true,
},
},
});
//apply other plugins

try {
await server.start();
} catch (err) {
console.log(`Error while starting server: ${err.message}`);
}
await registerServer({ server, app });

console.log(`Server running at: ${server.info.uri}`);
//port is optional and defaults to 4000
server.listen({ port: 4000 }).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
}

StartServer();
StartServer().catch(error => console.log(e));
```

## Principles
Expand Down
8 changes: 6 additions & 2 deletions packages/apollo-server-hapi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@
},
"homepage": "https://github.com/apollographql/apollo-server#readme",
"dependencies": {
"apollo-server-core": "^1.3.6",
"accept": "^3.0.2",
"apollo-server-core": "2.0.0-beta.0",
"apollo-server-module-graphiql": "^1.3.4",
"boom": "^7.1.0"
"boom": "^7.1.0",
"graphql-playground-html": "^1.5.6"
},
"devDependencies": {
"@types/graphql": "0.12.7",
"@types/hapi": "^17.0.12",
"@types/node": "^10.0.6",
"apollo-server-integration-testsuite": "^1.3.6",
"hapi": "17.4.0"
},
Expand Down
103 changes: 103 additions & 0 deletions packages/apollo-server-hapi/src/ApolloServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import * as hapi from 'hapi';
import { createServer, Server as HttpServer } from 'http';
import { ApolloServerBase, EngineLauncherOptions } from 'apollo-server-core';
import { parseAll } from 'accept';
import { renderPlaygroundPage } from 'graphql-playground-html';

import { graphqlHapi } from './hapiApollo';

export interface ServerRegistration {
app: hapi.Server;
server: ApolloServerBase<hapi.Request>;
path?: string;
}

export interface HapiListenOptions {
port?: number | string;
host?: string; // default: ''. This is where engineproxy listens.
pipePath?: string;
graphqlPaths?: string[]; // default: ['/graphql']
innerHost?: string; // default: '127.0.0.1'. This is where Node listens.
launcherOptions?: EngineLauncherOptions;
}

export const registerServer = async ({
app,
server,
path,
}: ServerRegistration) => {
if (!path) path = '/graphql';

await app.ext({
type: 'onRequest',
method: function(request, h) {
if (request.path !== path) {
return h.continue;
}

if (!server.disableTools && request.method === 'get') {
//perform more expensive content-type check only if necessary
const accept = parseAll(request.headers);
const types = accept.mediaTypes as string[];
const prefersHTML =
types.find(
(x: string) => x === 'text/html' || x === 'application/json',
) === 'text/html';

if (prefersHTML) {
return h
.response(
renderPlaygroundPage({
subscriptionsEndpoint: server.subscriptionsEnabled && path,
endpoint: path,
version: '1.4.0',
}),
)
.type('text/html')
.takeover();
}
}
return h.continue;
},
});

await app.register({
plugin: graphqlHapi,
options: {
path: path,
graphqlOptions: server.request.bind(server),
route: {
cors: true,
},
},
});

server.use({ path, getHttp: () => app.listener });

const listen = server.listen.bind(server);
server.listen = async options => {
//requires that autoListen is false, so that
//hapi sets up app.listener without start
await app.start();

//While this is not strictly necessary, it ensures that apollo server calls
//listen first, setting the port. Otherwise the hapi server constructor
//sets the port
if (app.listener.listening) {
throw Error(
`
Ensure that constructor of Hapi server sets autoListen to false, as follows:

const app = Hapi.server({
autoListen: false,
//other parameters
});
`,
);
}

//starts the hapi listener at a random port when engine proxy used,
//otherwise will start the server at the provided port
return listen({ ...options });
};
};
12 changes: 8 additions & 4 deletions packages/apollo-server-hapi/src/hapiApollo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Boom from 'boom';
import { Server, Response, Request, ReplyNoContinue } from 'hapi';
import { Server, Request } from 'hapi';
import * as GraphiQL from 'apollo-server-module-graphiql';
import {
GraphQLOptions,
Expand Down Expand Up @@ -39,13 +39,17 @@ const graphqlHapi: IPlugin = {
method: ['GET', 'POST'],
path: options.path || '/graphql',
vhost: options.vhost || undefined,
config: options.route || {},
options: options.route || {},
handler: async (request, h) => {
try {
const gqlResponse = await runHttpQuery([request], {
method: request.method.toUpperCase(),
options: options.graphqlOptions,
query: request.method === 'post' ? request.payload : request.query,
query:
request.method === 'post'
? //TODO type payload as string or Record
(request.payload as any)
: request.query,
});

const response = h.response(gqlResponse);
Expand Down Expand Up @@ -98,7 +102,7 @@ const graphiqlHapi: IPlugin = {
server.route({
method: 'GET',
path: options.path || '/graphiql',
config: options.route || {},
options: options.route || {},
handler: async (request, h) => {
const graphiqlString = await GraphiQL.resolveGraphiQLString(
request.query,
Expand Down
14 changes: 14 additions & 0 deletions packages/apollo-server-hapi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
// Expose types which can be used by both middleware flavors.
export { GraphQLOptions } from 'apollo-server-core';
export {
ApolloError,
toApolloError,
SyntaxError,
ValidationError,
AuthenticationError,
ForbiddenError,
} from 'apollo-server-core';

export {
IRegister,
HapiOptionsFunction,
Expand All @@ -7,3 +18,6 @@ export {
graphqlHapi,
graphiqlHapi,
} from './hapiApollo';

// ApolloServer integration
export { registerServer } from './ApolloServer';