Created
August 13, 2020 08:56
-
-
Save timkock/b38ae86cf5634c63dc482c7fc1c66be1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable no-param-reassign */ | |
/* eslint-disable object-curly-newline */ | |
// requirements | |
const ws = require('ws'); | |
const { SubscriptionServer } = require('subscriptions-transport-ws'); | |
const { formatApolloErrors } = require('apollo-server-errors'); | |
const { execute, subscribe } = require('graphql'); | |
// export patch | |
function installSubscriptionHandlers(server) { | |
if (!this.subscriptionServerOptions) { | |
if (this.config.gateway) { | |
throw Error('Subscriptions are not supported when operating as a gateway'); | |
} | |
if (this.supportsSubscriptions()) { | |
throw Error('Subscriptions are disabled, due to subscriptions set to false in the ApolloServer constructor'); | |
} else { | |
throw Error('Subscriptions are not supported, choose an integration, such as apollo-server-express that allows persistent connections'); | |
} | |
} | |
const { onDisconnect, onConnect, keepAlive, path } = this.subscriptionServerOptions; | |
const { schema } = this; | |
if (this.schema === undefined) throw new Error('Schema undefined during creation of subscription server.'); | |
this.subscriptionServer = SubscriptionServer.create({ | |
schema, | |
execute, | |
subscribe, | |
onConnect: onConnect || ((connectionParams) => ({ ...connectionParams })), | |
onDisconnect, | |
onOperation: async (message, connection) => { | |
connection.formatResponse = (value) => ({ | |
...value, | |
errors: value.errors | |
&& formatApolloErrors([...value.errors], { | |
formatter: this.requestOptions.formatError, | |
debug: this.requestOptions.debug, | |
}), | |
}); | |
connection.formatError = this.requestOptions.formatError; | |
let context = this.context ? this.context : { connection }; | |
try { | |
context = typeof this.context === 'function' | |
? await this.context({ connection, payload: message.payload }) | |
: context; | |
} catch (e) { | |
throw formatApolloErrors([e], { | |
formatter: this.requestOptions.formatError, | |
debug: this.requestOptions.debug, | |
})[0]; | |
} | |
return { ...connection, context }; | |
}, | |
keepAlive, | |
validationRules: this.requestOptions.validationRules, | |
}, server instanceof ws.Server | |
? server | |
: { | |
server, | |
path, | |
}); | |
} | |
module.exports = installSubscriptionHandlers; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typescript version
Changes made: