From f04b76f8097f7df84343d65eefbe7770babd8824 Mon Sep 17 00:00:00 2001 From: Evans Hauser Date: Tue, 22 May 2018 10:08:15 -0700 Subject: [PATCH] apollo-server-hapi: add options parameter to create a server (#1082) --- .../apollo-server-hapi/src/ApolloServer.ts | 41 ++++++++++++++++--- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/packages/apollo-server-hapi/src/ApolloServer.ts b/packages/apollo-server-hapi/src/ApolloServer.ts index c8bf559f0b4..cde43945e93 100644 --- a/packages/apollo-server-hapi/src/ApolloServer.ts +++ b/packages/apollo-server-hapi/src/ApolloServer.ts @@ -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; path?: string; } @@ -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) { @@ -61,7 +90,7 @@ export const registerServer = async ({ }, }); - await app.register({ + await hapiApp.register({ plugin: graphqlHapi, options: { path: path, @@ -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: