Skip to content

Commit

Permalink
apollo-server-hapi: add options parameter to create a server (#1082)
Browse files Browse the repository at this point in the history
  • Loading branch information
evans authored May 22, 2018
1 parent dccb482 commit f04b76f
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions packages/apollo-server-hapi/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { renderPlaygroundPage } from 'graphql-playground-html';
import { graphqlHapi } from './hapiApollo';

export interface ServerRegistration {
app: hapi.Server;
app?: hapi.Server;
//The options type should exclude port
options?: hapi.ServerOptions;
server: ApolloServerBase<hapi.Request>;
path?: string;
}
Expand All @@ -23,12 +25,39 @@ export interface HapiListenOptions {

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

await app.ext({
let hapiApp: hapi.Server;
if (app) {
hapiApp = app;
if (options) {
console.warn(`A Hapi Server was passed in, so the options are ignored`);
}
} else if (options) {
if ((options as any).port) {
throw new Error(`
The options for registerServer should not include a port, since autoListen is set to false. Please set the port under the http options in listen:
const server = new ApolloServer({ typeDefs, resolvers });
registerServer({
server,
options,
});
server.listen({ http: { port: YOUR_PORT_HERE } });
`);
}
hapiApp = new hapi.Server({ ...options, autoListen: false });
} else {
hapiApp = new hapi.Server({ autoListen: false });
}

await hapiApp.ext({
type: 'onRequest',
method: function(request, h) {
if (request.path !== path) {
Expand Down Expand Up @@ -61,7 +90,7 @@ export const registerServer = async ({
},
});

await app.register({
await hapiApp.register({
plugin: graphqlHapi,
options: {
path: path,
Expand All @@ -72,18 +101,18 @@ export const registerServer = async ({
},
});

server.use({ path, getHttp: () => app.listener });
server.use({ path, getHttp: () => hapiApp.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();
await hapiApp.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) {
if (hapiApp.listener.listening) {
throw Error(
`
Ensure that constructor of Hapi server sets autoListen to false, as follows:
Expand Down

0 comments on commit f04b76f

Please sign in to comment.