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

Add caching of process.env.NODE_ENV, for performance reasons #6660

Closed
wants to merge 3 commits into from
Closed
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
9 changes: 5 additions & 4 deletions src/cache/inmemory/readFromStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
maybeDeepFreeze,
mergeDeepArray,
} from '../../utilities';
import { isProduction } from '../../utilities/common/environment';
import { Cache } from '../core/types/Cache';
import {
DiffQueryAgainstStoreOptions,
Expand Down Expand Up @@ -288,7 +289,7 @@ export class StoreReader {
// as a scalar value. However, that value should not contain any
// Reference objects, and should be frozen in development, if it
// happens to be an object that is mutable.
if (process.env.NODE_ENV !== 'production') {
if (!isProduction()) {
assertSelectionSetForIdValue(
context.store,
selection,
Expand Down Expand Up @@ -337,7 +338,7 @@ export class StoreReader {
// defensive shallow copies than necessary.
finalResult.result = mergeDeepArray(objectsToMerge);

if (process.env.NODE_ENV !== 'production') {
if (!isProduction()) {
Object.freeze(finalResult.result);
}

Expand Down Expand Up @@ -414,7 +415,7 @@ export class StoreReader {
}), i);
}

if (process.env.NODE_ENV !== 'production') {
if (!isProduction()) {
assertSelectionSetForIdValue(context.store, field, item);
}

Expand All @@ -423,7 +424,7 @@ export class StoreReader {
return item;
});

if (process.env.NODE_ENV !== 'production') {
if (!isProduction()) {
Object.freeze(array);
}

Expand Down
5 changes: 3 additions & 2 deletions src/cache/inmemory/writeToStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
hasDirectives,
cloneDeep,
} from '../../utilities';
import { isProduction } from '../../utilities/common/environment';

import { NormalizedCache, ReadMergeModifyContext } from './types';
import { makeProcessedFieldsMerger, FieldValueToBeMerged, fieldNameFromStoreName } from './helpers';
Expand Down Expand Up @@ -259,7 +260,7 @@ export class StoreWriter {
mergedFields = policies.applyMerges(entityRef, mergedFields, context);
}

if (process.env.NODE_ENV !== "production") {
if (!isProduction()) {
Object.keys(mergedFields).forEach(storeFieldName => {
const fieldName = fieldNameFromStoreName(storeFieldName);
// If a merge function was defined for this field, trust that it
Expand Down Expand Up @@ -293,7 +294,7 @@ export class StoreWriter {
// In development, we need to clone scalar values so that they can be
// safely frozen with maybeDeepFreeze in readFromStore.ts. In production,
// it's cheaper to store the scalar values directly in the cache.
return process.env.NODE_ENV === 'production' ? value : cloneDeep(value);
return isProduction() ? value : cloneDeep(value);
}

if (Array.isArray(value)) {
Expand Down
5 changes: 3 additions & 2 deletions src/core/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { invariant, InvariantError } from 'ts-invariant';
import { ApolloLink, FetchResult, GraphQLRequest, execute } from '../link/core';
import { ApolloCache, DataProxy } from '../cache';
import { Observable, compact } from '../utilities';
import { isProduction } from '../utilities/common/environment';
import { version } from '../version';
import { HttpLink, UriFunction } from '../link/http';

Expand Down Expand Up @@ -171,7 +172,7 @@ export class ApolloClient<TCacheShape> implements DataProxy {
// Attach the client instance to window to let us be found by chrome devtools, but only in
// development mode
const defaultConnectToDevTools =
process.env.NODE_ENV !== 'production' &&
!isProduction() &&
typeof window !== 'undefined' &&
!(window as any).__APOLLO_CLIENT__;

Expand All @@ -186,7 +187,7 @@ export class ApolloClient<TCacheShape> implements DataProxy {
/**
* Suggest installing the devtools for developers who don't have them
*/
if (!hasSuggestedDevtools && process.env.NODE_ENV !== 'production') {
if (!hasSuggestedDevtools && !isProduction()) {
hasSuggestedDevtools = true;
if (
typeof window !== 'undefined' &&
Expand Down
3 changes: 2 additions & 1 deletion src/core/ObservableQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
FetchMoreQueryOptions,
SubscribeToMoreOptions,
} from './watchQueryOptions';
import { isProduction } from '../utilities/common/environment';
import { Reobserver } from './Reobserver';
import { QueryInfo } from './QueryInfo';

Expand Down Expand Up @@ -312,7 +313,7 @@ export class ObservableQuery<
const { updateQuery } = fetchMoreOptions;

if (updateQuery) {
if (process.env.NODE_ENV !== "production" &&
if (!isProduction() &&
!warnedAboutUpdateQuery) {
invariant.warn(
`The updateQuery callback for fetchMore is deprecated, and will be removed
Expand Down
3 changes: 2 additions & 1 deletion src/core/QueryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
Concast,
ConcastSourcesIterable,
} from '../utilities';
import { isProduction } from '../utilities/common/environment';
import { ApolloError, isApolloError } from '../errors';
import { MutationStore } from './MutationStore';
import {
Expand Down Expand Up @@ -961,7 +962,7 @@ export class QueryManager<TStore> {
) => {
const data = diff.result as TData;

if (process.env.NODE_ENV !== 'production' &&
if (!isProduction() &&
isNonEmptyArray(diff.missing) &&
!equal(data, {})) {
invariant.warn(`Missing cache result fields: ${
Expand Down
23 changes: 15 additions & 8 deletions src/utilities/common/__tests__/environment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { isEnv, isDevelopment, isTest } from '../environment';
import { refreshEnv, isEnv, isDevelopment, isTest } from '../environment';

function setNodeEnv(env: string|undefined) {
process.env.NODE_ENV = env;
refreshEnv();
}

describe('environment', () => {
let keepEnv: string | undefined;
Expand All @@ -10,48 +15,50 @@ describe('environment', () => {

afterEach(() => {
// restore the NODE_ENV
process.env.NODE_ENV = keepEnv;
setNodeEnv(keepEnv);
});

describe('isEnv', () => {
it(`should match when there's a value`, () => {
['production', 'development', 'test'].forEach(env => {
process.env.NODE_ENV = env;
setNodeEnv(env);
expect(isEnv(env)).toBe(true);
});
});

it(`should treat no proces.env.NODE_ENV as it'd be in development`, () => {
it(`should treat no process.env.NODE_ENV as it'd be in development`, () => {
delete process.env.NODE_ENV;
refreshEnv();
expect(isEnv('development')).toBe(true);
});
});

describe('isTest', () => {
it('should return true if in test', () => {
process.env.NODE_ENV = 'test';
setNodeEnv('test');
expect(isTest()).toBe(true);
});

it('should return true if not in test', () => {
process.env.NODE_ENV = 'development';
setNodeEnv('development');
expect(!isTest()).toBe(true);
});
});

describe('isDevelopment', () => {
it('should return true if in development', () => {
process.env.NODE_ENV = 'development';
setNodeEnv('development');
expect(isDevelopment()).toBe(true);
});

it('should return true if not in development and environment is defined', () => {
process.env.NODE_ENV = 'test';
setNodeEnv('test');
expect(!isDevelopment()).toBe(true);
});

it('should make development as the default environment', () => {
delete process.env.NODE_ENV;
refreshEnv();
expect(isDevelopment()).toBe(true);
});
});
Expand Down
28 changes: 22 additions & 6 deletions src/utilities/common/environment.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
export function getEnv(): string | undefined {
// Functions for checking whether we're in a development, production, or test
// environment. Uses the NODE_ENV environment variable as the source of truth.
// This is cached on startup, because process.env is actually a C function and
// calling it is somewhat expensive (enough to show up prominently in profiler
// results, if not cached.)

let node_env: string = "development";

export function refreshEnv(): void {
if (typeof process !== 'undefined' && process.env.NODE_ENV) {
return process.env.NODE_ENV;
node_env = process.env.NODE_ENV;
} else {
node_env = "development";
}
}
refreshEnv();

// default environment
return 'development';
export function getEnv(): string | undefined {
return node_env;
}

export function isEnv(env: string): boolean {
return getEnv() === env;
}

export function isDevelopment(): boolean {
return isEnv('development') === true;
return node_env==='development';
}

export function isProduction(): boolean {
return node_env==='production';
}

export function isTest(): boolean {
return isEnv('test') === true;
return node_env==='test';
}
4 changes: 2 additions & 2 deletions src/utilities/common/maybeDeepFreeze.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isDevelopment, isTest } from './environment';
import { isDevelopment, isProduction, isTest } from './environment';

function isObject(value: any) {
return value !== null && typeof value === "object";
Expand All @@ -18,7 +18,7 @@ function deepFreeze(value: any) {
}

export function maybeDeepFreeze<T>(obj: T): T {
if (process.env.NODE_ENV !== "production" && (isDevelopment() || isTest())) {
if (!isProduction() && (isDevelopment() || isTest())) {
deepFreeze(obj);
}
return obj;
Expand Down