From 9b7a29203d5ee424a43066ce6d3797868dcad043 Mon Sep 17 00:00:00 2001 From: Lee Byron Date: Wed, 20 Dec 2017 13:45:12 -0800 Subject: [PATCH] Only trigger "one instance of graphql" error in DEV environments. This ensures the additional checking for multiple graphql instances only occurs in non-production builds. Not only does this improve the performance for production builds, it also solves a spurious error case for minified builds: Since this additional check compares the `.name` of the constructors as a proxy for determining if two classes are representationally equal, minified builds may result in spurious false-positives if class names are minified to single-character names and those characters are likely to conflict. This doesn't require `process` to exist (defaulting to the non-production mode), but bundlers like Webpack should consider using a stripping transform (see: https://webpack.js.org/guides/production/#specify-the-environment) in production builds if they also use a minifier. --- src/jsutils/instanceOf.js | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/jsutils/instanceOf.js b/src/jsutils/instanceOf.js index 8c37778360..cf5e204a0a 100644 --- a/src/jsutils/instanceOf.js +++ b/src/jsutils/instanceOf.js @@ -16,16 +16,18 @@ declare function instanceOf( constructor: mixed, ): boolean %checks(value instanceof constructor); -// eslint-disable-next-line no-redeclare -export default function instanceOf(value, constructor) { - if (value instanceof constructor) { - return true; - } - if (value) { - const valueConstructor = value.constructor; - if (valueConstructor && valueConstructor.name === constructor.name) { - throw new Error( - `Cannot use ${constructor.name} "${value}" from another module or realm. +export default (process && process.env.NODE_ENV !== 'production' + ? // eslint-disable-next-line no-shadow + function instanceOf(value: any, constructor: any) { + if (value instanceof constructor) { + return true; + } + if (value) { + const valueClass = value.constructor; + const className = constructor.name; + if (valueClass && valueClass.name === className) { + throw new Error( + `Cannot use ${className} "${value}" from another module or realm. Ensure that there is only one instance of "graphql" in the node_modules directory. If different versions of "graphql" are the dependencies of other @@ -37,8 +39,12 @@ Duplicate "graphql" modules cannot be used at the same time since different versions may have different capabilities and behavior. The data from one version used in the function from another could produce confusing and spurious results.`, - ); + ); + } + } + return false; } - } - return false; -} + : // eslint-disable-next-line no-shadow + function instanceOf(value: any, constructor: any) { + return value instanceof constructor; + });