diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000000..58351a5c98 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,8 @@ +node_modules +lib +coverage +npm +package.json +dist +*.snap +package-lock.json diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index 760edb4d65..0000000000 --- a/.prettierrc +++ /dev/null @@ -1,4 +0,0 @@ -printWidth: 80 -semi: true -singleQuote: true -trailingComma: all diff --git a/ROADMAP.md b/ROADMAP.md index 440eb51543..0fe9b28905 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -88,11 +88,7 @@ A new way to interact with Apollo and React, the `Query` component will allow us Like the `Query` component, the `Mutation` component will allow using Apollo without an HOC but still get all of the benefits of Apollo. The rough draft looks something like this: ```js - Component} -/> + Component} /> ``` The stateUpdater prop allows for setting local component state based on the state of the _latest_ mutation fired or potentially allow a Map of results and statues. This API is still early and may change. diff --git a/dangerfile.ts b/dangerfile.ts index b9298d6aac..f606ef5696 100644 --- a/dangerfile.ts +++ b/dangerfile.ts @@ -13,8 +13,7 @@ const trivialPR = bodyAndTitle.includes('trivial'); const acceptedNoTests = bodyAndTitle.includes('skip new tests'); const typescriptOnly = (file: string) => includes(file, '.ts'); -const filesOnly = (file: string) => - fs.existsSync(file) && fs.lstatSync(file).isFile(); +const filesOnly = (file: string) => fs.existsSync(file) && fs.lstatSync(file).isFile(); // Custom subsets of known files const modifiedAppFiles = modified @@ -42,15 +41,10 @@ const toSentence = (array: Array): string => { }; // ("/href/thing", "name") to "name" -const createLink = (href: string, text: string): string => - `${text}`; +const createLink = (href: string, text: string): string => `${text}`; // Raise about missing code inside files -const raiseIssueAboutPaths = ( - type: Function, - paths: string[], - codeToInclude: string, -) => { +const raiseIssueAboutPaths = (type: Function, paths: string[], codeToInclude: string) => { if (paths.length > 0) { const files = linkableFiles(paths); const strict = '' + codeToInclude + ''; @@ -81,10 +75,7 @@ if (!isBot) { // Warn when there is a big PR const bigPRThreshold = 500; - if ( - danger.github.pr.additions + danger.github.pr.deletions > - bigPRThreshold - ) { + if (danger.github.pr.additions + danger.github.pr.deletions > bigPRThreshold) { warn(':exclamation: Big PR'); } diff --git a/examples/base/src/App.js b/examples/base/src/App.js index ca1f484d17..e4a4da30a9 100644 --- a/examples/base/src/App.js +++ b/examples/base/src/App.js @@ -37,8 +37,7 @@ export const CharacterWithoutData = ({ loading, hero, error }) => { friend => friend && (
- {friend.name}:{' '} - {friend.appearsIn.map(x => x && x.toLowerCase()).join(', ')} + {friend.name}: {friend.appearsIn.map(x => x && x.toLowerCase()).join(', ')}
), )} diff --git a/examples/base/src/__tests__/App.js b/examples/base/src/__tests__/App.js index fd11aaa13f..521e6d5cc4 100644 --- a/examples/base/src/__tests__/App.js +++ b/examples/base/src/__tests__/App.js @@ -7,13 +7,7 @@ import { MockedProvider } from 'react-apollo/lib/test-utils'; import { addTypenameToDocument } from 'apollo-client'; -import { - HERO_QUERY, - withCharacter, - CharacterWithoutData, - App, - ShapedProps, -} from '../App'; +import { HERO_QUERY, withCharacter, CharacterWithoutData, App, ShapedProps } from '../App'; const query = addTypenameToDocument(HERO_QUERY); @@ -40,9 +34,7 @@ describe('withCharacter', () => { } const ContainerWithData = withCharacter(Container); - const mocks = [ - { request: { query, variables }, result: { data: { hero: empty } } }, - ]; + const mocks = [{ request: { query, variables }, result: { data: { hero: empty } } }]; renderer.create( @@ -107,9 +99,7 @@ describe('withCharacter', () => { } componentWillReceiveProps(next: ShapedProps) { expect(next.loading).toBe(false); - expect(next.error.message).toMatch( - /these are not the droids you are looking for/, - ); + expect(next.error.message).toMatch(/these are not the droids you are looking for/); done(); } render() { @@ -182,21 +172,15 @@ describe('CharacterWithoutData', () => { expect(output.toJSON()).toMatchSnapshot(); }); it('returns markup for a hero with no friends', () => { - const output = renderer.create( - , - ); + const output = renderer.create(); expect(output.toJSON()).toMatchSnapshot(); }); it('returns markup for empty array of friends', () => { - const output = renderer.create( - , - ); + const output = renderer.create(); expect(output.toJSON()).toMatchSnapshot(); }); it('returns markup for a friend without an appearsIn', () => { - const output = renderer.create( - , - ); + const output = renderer.create(); expect(output.toJSON()).toMatchSnapshot(); }); it('renders a full data result', () => { @@ -207,9 +191,7 @@ describe('CharacterWithoutData', () => { describe('App', () => { it('renders the data from NEWHOPE', () => { - const mocks = [ - { request: { query, variables }, result: { data: { hero: empty } } }, - ]; + const mocks = [{ request: { query, variables }, result: { data: { hero: empty } } }]; const output = renderer.create( diff --git a/examples/base/src/__tests__/__snapshots__/App.js.snap b/examples/base/src/__tests__/__snapshots__/App.js.snap index 0a5609e091..82c98c8b3a 100644 --- a/examples/base/src/__tests__/__snapshots__/App.js.snap +++ b/examples/base/src/__tests__/__snapshots__/App.js.snap @@ -36,9 +36,7 @@ exports[`CharacterWithoutData renders a full data result 1`] = ` `; -exports[ - `CharacterWithoutData returns markup for a friend without an appearsIn 1` -] = ` +exports[`CharacterWithoutData returns markup for a friend without an appearsIn 1`] = `

diff --git a/examples/components/src/App.js b/examples/components/src/App.js index 24a7e9050a..9370d910b3 100644 --- a/examples/components/src/App.js +++ b/examples/components/src/App.js @@ -39,10 +39,7 @@ const Character = ({ episode }) => ( friend => friend && (

- {friend.name}:{' '} - {friend.appearsIn - .map(x => x && x.toLowerCase()) - .join(', ')} + {friend.name}: {friend.appearsIn.map(x => x && x.toLowerCase()).join(', ')}
), )} diff --git a/examples/flow/src/App.js b/examples/flow/src/App.js index 048bd6b16d..aad116bbd7 100644 --- a/examples/flow/src/App.js +++ b/examples/flow/src/App.js @@ -1,17 +1,10 @@ // @flow import React from 'react'; -import { - graphql, - type OperationComponent, - type QueryProps, -} from 'react-apollo'; +import { graphql, type OperationComponent, type QueryProps } from 'react-apollo'; import gql from 'graphql-tag'; -import type { - GetCharacterQuery, - GetCharacterQueryVariables, -} from './schema.flow.js'; +import type { GetCharacterQuery, GetCharacterQueryVariables } from './schema.flow.js'; export const HERO_QUERY = gql` query GetCharacter($episode: Episode!) { @@ -55,9 +48,7 @@ export const CharacterWithoutData = ({ loading, hero, error }: Props) => { friend && (
{friend.name}:{' '} - {friend.appearsIn - .map(epis => epis && epis.toLowerCase()) - .join(', ')} + {friend.appearsIn.map(epis => epis && epis.toLowerCase()).join(', ')}
), )} diff --git a/examples/flow/src/__tests__/App.js b/examples/flow/src/__tests__/App.js index 0353279463..0cf7b5d45e 100644 --- a/examples/flow/src/__tests__/App.js +++ b/examples/flow/src/__tests__/App.js @@ -7,13 +7,7 @@ import { MockedProvider } from 'react-apollo/lib/test-utils'; import { addTypenameToDocument } from 'apollo-client'; -import { - HERO_QUERY, - withCharacter, - CharacterWithoutData, - App, - ShapedProps, -} from '../App'; +import { HERO_QUERY, withCharacter, CharacterWithoutData, App, ShapedProps } from '../App'; const query = HERO_QUERY; @@ -40,9 +34,7 @@ describe('withCharacter', () => { } const ContainerWithData = withCharacter(Container); - const mocks = [ - { request: { query, variables }, result: { data: { hero: empty } } }, - ]; + const mocks = [{ request: { query, variables }, result: { data: { hero: empty } } }]; renderer.create( @@ -107,9 +99,7 @@ describe('withCharacter', () => { } componentWillReceiveProps(next: ShapedProps) { expect(next.loading).toBe(false); - expect(next.error.message).toMatch( - /these are not the droids you are looking for/, - ); + expect(next.error.message).toMatch(/these are not the droids you are looking for/); done(); } render() { @@ -182,21 +172,15 @@ describe('CharacterWithoutData', () => { expect(output.toJSON()).toMatchSnapshot(); }); it('returns markup for a hero with no friends', () => { - const output = renderer.create( - , - ); + const output = renderer.create(); expect(output.toJSON()).toMatchSnapshot(); }); it('returns markup for empty array of friends', () => { - const output = renderer.create( - , - ); + const output = renderer.create(); expect(output.toJSON()).toMatchSnapshot(); }); it('returns markup for a friend without an appearsIn', () => { - const output = renderer.create( - , - ); + const output = renderer.create(); expect(output.toJSON()).toMatchSnapshot(); }); it('renders a full data result', () => { @@ -207,9 +191,7 @@ describe('CharacterWithoutData', () => { describe('App', () => { it('renders the data from NEWHOPE', () => { - const mocks = [ - { request: { query, variables }, result: { data: { hero: empty } } }, - ]; + const mocks = [{ request: { query, variables }, result: { data: { hero: empty } } }]; const output = renderer.create( diff --git a/examples/flow/src/__tests__/__snapshots__/App.js.snap b/examples/flow/src/__tests__/__snapshots__/App.js.snap index 0a5609e091..82c98c8b3a 100644 --- a/examples/flow/src/__tests__/__snapshots__/App.js.snap +++ b/examples/flow/src/__tests__/__snapshots__/App.js.snap @@ -36,9 +36,7 @@ exports[`CharacterWithoutData renders a full data result 1`] = `
`; -exports[ - `CharacterWithoutData returns markup for a friend without an appearsIn 1` -] = ` +exports[`CharacterWithoutData returns markup for a friend without an appearsIn 1`] = `

diff --git a/examples/flow/src/schema.json b/examples/flow/src/schema.json index b8919dcfc7..63950949e4 100644 --- a/examples/flow/src/schema.json +++ b/examples/flow/src/schema.json @@ -12,8 +12,7 @@ { "kind": "OBJECT", "name": "Query", - "description": - "The query type, represents all of the entry points into our object graph", + "description": "The query type, represents all of the entry points into our object graph", "fields": [ { "name": "hero", @@ -220,22 +219,19 @@ "enumValues": [ { "name": "NEWHOPE", - "description": - "Star Wars Episode IV: A New Hope, released in 1977.", + "description": "Star Wars Episode IV: A New Hope, released in 1977.", "isDeprecated": false, "deprecationReason": null }, { "name": "EMPIRE", - "description": - "Star Wars Episode V: The Empire Strikes Back, released in 1980.", + "description": "Star Wars Episode V: The Empire Strikes Back, released in 1980.", "isDeprecated": false, "deprecationReason": null }, { "name": "JEDI", - "description": - "Star Wars Episode VI: Return of the Jedi, released in 1983.", + "description": "Star Wars Episode VI: Return of the Jedi, released in 1983.", "isDeprecated": false, "deprecationReason": null } @@ -281,8 +277,7 @@ }, { "name": "friends", - "description": - "The friends of the character, or an empty list if they have none", + "description": "The friends of the character, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -298,8 +293,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the character exposed as a connection with edges", + "description": "The friends of the character exposed as a connection with edges", "args": [ { "name": "first", @@ -439,8 +433,7 @@ }, { "name": "friends", - "description": - "A list of the friends, as a convenience when edges are not needed.", + "description": "A list of the friends, as a convenience when edges are not needed.", "args": [], "type": { "kind": "LIST", @@ -499,8 +492,7 @@ }, { "name": "node", - "description": - "The character represented by this friendship edge", + "description": "The character represented by this friendship edge", "args": [], "type": { "kind": "INTERFACE", @@ -570,8 +562,7 @@ { "kind": "SCALAR", "name": "Boolean", - "description": - "The `Boolean` scalar type represents `true` or `false`.", + "description": "The `Boolean` scalar type represents `true` or `false`.", "fields": null, "inputFields": null, "interfaces": null, @@ -717,8 +708,7 @@ }, { "name": "friends", - "description": - "This human's friends, or an empty list if they have none", + "description": "This human's friends, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -734,8 +724,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the human exposed as a connection with edges", + "description": "The friends of the human exposed as a connection with edges", "args": [ { "name": "first", @@ -922,8 +911,7 @@ { "kind": "OBJECT", "name": "Droid", - "description": - "An autonomous mechanical character in the Star Wars universe", + "description": "An autonomous mechanical character in the Star Wars universe", "fields": [ { "name": "id", @@ -959,8 +947,7 @@ }, { "name": "friends", - "description": - "This droid's friends, or an empty list if they have none", + "description": "This droid's friends, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -976,8 +963,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the droid exposed as a connection with edges", + "description": "The friends of the droid exposed as a connection with edges", "args": [ { "name": "first", @@ -1059,8 +1045,7 @@ { "kind": "OBJECT", "name": "Mutation", - "description": - "The mutation type, represents all updates we can make to our data", + "description": "The mutation type, represents all updates we can make to our data", "fields": [ { "name": "createReview", @@ -1108,8 +1093,7 @@ { "kind": "INPUT_OBJECT", "name": "ReviewInput", - "description": - "The input object sent when someone is creating a new review", + "description": "The input object sent when someone is creating a new review", "fields": null, "inputFields": [ { @@ -1173,8 +1157,7 @@ }, { "name": "queryType", - "description": - "The type that query operations will be rooted at.", + "description": "The type that query operations will be rooted at.", "args": [], "type": { "kind": "NON_NULL", @@ -1216,8 +1199,7 @@ }, { "name": "directives", - "description": - "A list of all directives supported by this server.", + "description": "A list of all directives supported by this server.", "args": [], "type": { "kind": "NON_NULL", @@ -1434,8 +1416,7 @@ { "kind": "ENUM", "name": "__TypeKind", - "description": - "An enum describing what kind of type a given `__Type` is.", + "description": "An enum describing what kind of type a given `__Type` is.", "fields": null, "inputFields": null, "interfaces": null, @@ -1462,15 +1443,13 @@ }, { "name": "UNION", - "description": - "Indicates this type is a union. `possibleTypes` is a valid field.", + "description": "Indicates this type is a union. `possibleTypes` is a valid field.", "isDeprecated": false, "deprecationReason": null }, { "name": "ENUM", - "description": - "Indicates this type is an enum. `enumValues` is a valid field.", + "description": "Indicates this type is an enum. `enumValues` is a valid field.", "isDeprecated": false, "deprecationReason": null }, @@ -1483,15 +1462,13 @@ }, { "name": "LIST", - "description": - "Indicates this type is a list. `ofType` is a valid field.", + "description": "Indicates this type is a list. `ofType` is a valid field.", "isDeprecated": false, "deprecationReason": null }, { "name": "NON_NULL", - "description": - "Indicates this type is a non-null. `ofType` is a valid field.", + "description": "Indicates this type is a non-null. `ofType` is a valid field.", "isDeprecated": false, "deprecationReason": null } @@ -1986,15 +1963,13 @@ }, { "name": "INPUT_OBJECT", - "description": - "Location adjacent to an input object type definition.", + "description": "Location adjacent to an input object type definition.", "isDeprecated": false, "deprecationReason": null }, { "name": "INPUT_FIELD_DEFINITION", - "description": - "Location adjacent to an input object field definition.", + "description": "Location adjacent to an input object field definition.", "isDeprecated": false, "deprecationReason": null } @@ -2049,8 +2024,7 @@ }, { "name": "deprecated", - "description": - "Marks an element of a GraphQL schema as no longer supported.", + "description": "Marks an element of a GraphQL schema as no longer supported.", "locations": ["FIELD_DEFINITION", "ENUM_VALUE"], "args": [ { diff --git a/examples/ssr/client/main.js b/examples/ssr/client/main.js index 12ed0f71dd..dd6dee7759 100644 --- a/examples/ssr/client/main.js +++ b/examples/ssr/client/main.js @@ -1,10 +1,6 @@ import { render } from 'react-dom'; import { onPageLoad } from 'meteor/server-render'; -import { - ApolloProvider, - ApolloClient, - createNetworkInterface, -} from 'react-apollo'; +import { ApolloProvider, ApolloClient, createNetworkInterface } from 'react-apollo'; import { App } from '/imports/app'; diff --git a/examples/ssr/imports/app.js b/examples/ssr/imports/app.js index abfcb7dd8a..2a81f9fa36 100644 --- a/examples/ssr/imports/app.js +++ b/examples/ssr/imports/app.js @@ -33,8 +33,7 @@ export const Character = withCharacter(({ loading, hero, error }) => { {hero.friends.map(friend => (

- {friend.name}:{' '} - {friend.appearsIn.map(x => x.toLowerCase()).join(', ')} + {friend.name}: {friend.appearsIn.map(x => x.toLowerCase()).join(', ')}
))}
diff --git a/examples/ssr/server/main.js b/examples/ssr/server/main.js index 1666ad23ac..828d5e7dcf 100644 --- a/examples/ssr/server/main.js +++ b/examples/ssr/server/main.js @@ -31,9 +31,7 @@ export const render = async sink => { const body = renderToString(WrappedApp); sink.renderIntoElementById('app', body); sink.appendToBody(` - + `); }; diff --git a/examples/typescript/schema.json b/examples/typescript/schema.json index b8919dcfc7..63950949e4 100644 --- a/examples/typescript/schema.json +++ b/examples/typescript/schema.json @@ -12,8 +12,7 @@ { "kind": "OBJECT", "name": "Query", - "description": - "The query type, represents all of the entry points into our object graph", + "description": "The query type, represents all of the entry points into our object graph", "fields": [ { "name": "hero", @@ -220,22 +219,19 @@ "enumValues": [ { "name": "NEWHOPE", - "description": - "Star Wars Episode IV: A New Hope, released in 1977.", + "description": "Star Wars Episode IV: A New Hope, released in 1977.", "isDeprecated": false, "deprecationReason": null }, { "name": "EMPIRE", - "description": - "Star Wars Episode V: The Empire Strikes Back, released in 1980.", + "description": "Star Wars Episode V: The Empire Strikes Back, released in 1980.", "isDeprecated": false, "deprecationReason": null }, { "name": "JEDI", - "description": - "Star Wars Episode VI: Return of the Jedi, released in 1983.", + "description": "Star Wars Episode VI: Return of the Jedi, released in 1983.", "isDeprecated": false, "deprecationReason": null } @@ -281,8 +277,7 @@ }, { "name": "friends", - "description": - "The friends of the character, or an empty list if they have none", + "description": "The friends of the character, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -298,8 +293,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the character exposed as a connection with edges", + "description": "The friends of the character exposed as a connection with edges", "args": [ { "name": "first", @@ -439,8 +433,7 @@ }, { "name": "friends", - "description": - "A list of the friends, as a convenience when edges are not needed.", + "description": "A list of the friends, as a convenience when edges are not needed.", "args": [], "type": { "kind": "LIST", @@ -499,8 +492,7 @@ }, { "name": "node", - "description": - "The character represented by this friendship edge", + "description": "The character represented by this friendship edge", "args": [], "type": { "kind": "INTERFACE", @@ -570,8 +562,7 @@ { "kind": "SCALAR", "name": "Boolean", - "description": - "The `Boolean` scalar type represents `true` or `false`.", + "description": "The `Boolean` scalar type represents `true` or `false`.", "fields": null, "inputFields": null, "interfaces": null, @@ -717,8 +708,7 @@ }, { "name": "friends", - "description": - "This human's friends, or an empty list if they have none", + "description": "This human's friends, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -734,8 +724,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the human exposed as a connection with edges", + "description": "The friends of the human exposed as a connection with edges", "args": [ { "name": "first", @@ -922,8 +911,7 @@ { "kind": "OBJECT", "name": "Droid", - "description": - "An autonomous mechanical character in the Star Wars universe", + "description": "An autonomous mechanical character in the Star Wars universe", "fields": [ { "name": "id", @@ -959,8 +947,7 @@ }, { "name": "friends", - "description": - "This droid's friends, or an empty list if they have none", + "description": "This droid's friends, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -976,8 +963,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the droid exposed as a connection with edges", + "description": "The friends of the droid exposed as a connection with edges", "args": [ { "name": "first", @@ -1059,8 +1045,7 @@ { "kind": "OBJECT", "name": "Mutation", - "description": - "The mutation type, represents all updates we can make to our data", + "description": "The mutation type, represents all updates we can make to our data", "fields": [ { "name": "createReview", @@ -1108,8 +1093,7 @@ { "kind": "INPUT_OBJECT", "name": "ReviewInput", - "description": - "The input object sent when someone is creating a new review", + "description": "The input object sent when someone is creating a new review", "fields": null, "inputFields": [ { @@ -1173,8 +1157,7 @@ }, { "name": "queryType", - "description": - "The type that query operations will be rooted at.", + "description": "The type that query operations will be rooted at.", "args": [], "type": { "kind": "NON_NULL", @@ -1216,8 +1199,7 @@ }, { "name": "directives", - "description": - "A list of all directives supported by this server.", + "description": "A list of all directives supported by this server.", "args": [], "type": { "kind": "NON_NULL", @@ -1434,8 +1416,7 @@ { "kind": "ENUM", "name": "__TypeKind", - "description": - "An enum describing what kind of type a given `__Type` is.", + "description": "An enum describing what kind of type a given `__Type` is.", "fields": null, "inputFields": null, "interfaces": null, @@ -1462,15 +1443,13 @@ }, { "name": "UNION", - "description": - "Indicates this type is a union. `possibleTypes` is a valid field.", + "description": "Indicates this type is a union. `possibleTypes` is a valid field.", "isDeprecated": false, "deprecationReason": null }, { "name": "ENUM", - "description": - "Indicates this type is an enum. `enumValues` is a valid field.", + "description": "Indicates this type is an enum. `enumValues` is a valid field.", "isDeprecated": false, "deprecationReason": null }, @@ -1483,15 +1462,13 @@ }, { "name": "LIST", - "description": - "Indicates this type is a list. `ofType` is a valid field.", + "description": "Indicates this type is a list. `ofType` is a valid field.", "isDeprecated": false, "deprecationReason": null }, { "name": "NON_NULL", - "description": - "Indicates this type is a non-null. `ofType` is a valid field.", + "description": "Indicates this type is a non-null. `ofType` is a valid field.", "isDeprecated": false, "deprecationReason": null } @@ -1986,15 +1963,13 @@ }, { "name": "INPUT_OBJECT", - "description": - "Location adjacent to an input object type definition.", + "description": "Location adjacent to an input object type definition.", "isDeprecated": false, "deprecationReason": null }, { "name": "INPUT_FIELD_DEFINITION", - "description": - "Location adjacent to an input object field definition.", + "description": "Location adjacent to an input object field definition.", "isDeprecated": false, "deprecationReason": null } @@ -2049,8 +2024,7 @@ }, { "name": "deprecated", - "description": - "Marks an element of a GraphQL schema as no longer supported.", + "description": "Marks an element of a GraphQL schema as no longer supported.", "locations": ["FIELD_DEFINITION", "ENUM_VALUE"], "args": [ { diff --git a/examples/typescript/src/Character.tsx b/examples/typescript/src/Character.tsx index 5dedd5ee14..497af8fbef 100644 --- a/examples/typescript/src/Character.tsx +++ b/examples/typescript/src/Character.tsx @@ -1,16 +1,9 @@ import * as React from 'react'; -import { - GetCharacterQuery, - GetCharacterQueryVariables, - Episode, -} from './__generated__/types'; +import { GetCharacterQuery, GetCharacterQueryVariables, Episode } from './__generated__/types'; import { GetCharacter as QUERY } from './queries'; import { Query } from 'react-apollo'; -class CharacterQuery extends Query< - GetCharacterQuery, - GetCharacterQueryVariables -> {} +class CharacterQuery extends Query {} export interface CharacterProps { episode: Episode; @@ -38,9 +31,7 @@ export const Character: React.SFC = props => { friend && (
{friend.name}:{' '} - {friend.appearsIn - .map(x => x && x.toLowerCase()) - .join(', ')} + {friend.appearsIn.map(x => x && x.toLowerCase()).join(', ')}
), )} diff --git a/examples/typescript/src/schema.json b/examples/typescript/src/schema.json index b8919dcfc7..63950949e4 100644 --- a/examples/typescript/src/schema.json +++ b/examples/typescript/src/schema.json @@ -12,8 +12,7 @@ { "kind": "OBJECT", "name": "Query", - "description": - "The query type, represents all of the entry points into our object graph", + "description": "The query type, represents all of the entry points into our object graph", "fields": [ { "name": "hero", @@ -220,22 +219,19 @@ "enumValues": [ { "name": "NEWHOPE", - "description": - "Star Wars Episode IV: A New Hope, released in 1977.", + "description": "Star Wars Episode IV: A New Hope, released in 1977.", "isDeprecated": false, "deprecationReason": null }, { "name": "EMPIRE", - "description": - "Star Wars Episode V: The Empire Strikes Back, released in 1980.", + "description": "Star Wars Episode V: The Empire Strikes Back, released in 1980.", "isDeprecated": false, "deprecationReason": null }, { "name": "JEDI", - "description": - "Star Wars Episode VI: Return of the Jedi, released in 1983.", + "description": "Star Wars Episode VI: Return of the Jedi, released in 1983.", "isDeprecated": false, "deprecationReason": null } @@ -281,8 +277,7 @@ }, { "name": "friends", - "description": - "The friends of the character, or an empty list if they have none", + "description": "The friends of the character, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -298,8 +293,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the character exposed as a connection with edges", + "description": "The friends of the character exposed as a connection with edges", "args": [ { "name": "first", @@ -439,8 +433,7 @@ }, { "name": "friends", - "description": - "A list of the friends, as a convenience when edges are not needed.", + "description": "A list of the friends, as a convenience when edges are not needed.", "args": [], "type": { "kind": "LIST", @@ -499,8 +492,7 @@ }, { "name": "node", - "description": - "The character represented by this friendship edge", + "description": "The character represented by this friendship edge", "args": [], "type": { "kind": "INTERFACE", @@ -570,8 +562,7 @@ { "kind": "SCALAR", "name": "Boolean", - "description": - "The `Boolean` scalar type represents `true` or `false`.", + "description": "The `Boolean` scalar type represents `true` or `false`.", "fields": null, "inputFields": null, "interfaces": null, @@ -717,8 +708,7 @@ }, { "name": "friends", - "description": - "This human's friends, or an empty list if they have none", + "description": "This human's friends, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -734,8 +724,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the human exposed as a connection with edges", + "description": "The friends of the human exposed as a connection with edges", "args": [ { "name": "first", @@ -922,8 +911,7 @@ { "kind": "OBJECT", "name": "Droid", - "description": - "An autonomous mechanical character in the Star Wars universe", + "description": "An autonomous mechanical character in the Star Wars universe", "fields": [ { "name": "id", @@ -959,8 +947,7 @@ }, { "name": "friends", - "description": - "This droid's friends, or an empty list if they have none", + "description": "This droid's friends, or an empty list if they have none", "args": [], "type": { "kind": "LIST", @@ -976,8 +963,7 @@ }, { "name": "friendsConnection", - "description": - "The friends of the droid exposed as a connection with edges", + "description": "The friends of the droid exposed as a connection with edges", "args": [ { "name": "first", @@ -1059,8 +1045,7 @@ { "kind": "OBJECT", "name": "Mutation", - "description": - "The mutation type, represents all updates we can make to our data", + "description": "The mutation type, represents all updates we can make to our data", "fields": [ { "name": "createReview", @@ -1108,8 +1093,7 @@ { "kind": "INPUT_OBJECT", "name": "ReviewInput", - "description": - "The input object sent when someone is creating a new review", + "description": "The input object sent when someone is creating a new review", "fields": null, "inputFields": [ { @@ -1173,8 +1157,7 @@ }, { "name": "queryType", - "description": - "The type that query operations will be rooted at.", + "description": "The type that query operations will be rooted at.", "args": [], "type": { "kind": "NON_NULL", @@ -1216,8 +1199,7 @@ }, { "name": "directives", - "description": - "A list of all directives supported by this server.", + "description": "A list of all directives supported by this server.", "args": [], "type": { "kind": "NON_NULL", @@ -1434,8 +1416,7 @@ { "kind": "ENUM", "name": "__TypeKind", - "description": - "An enum describing what kind of type a given `__Type` is.", + "description": "An enum describing what kind of type a given `__Type` is.", "fields": null, "inputFields": null, "interfaces": null, @@ -1462,15 +1443,13 @@ }, { "name": "UNION", - "description": - "Indicates this type is a union. `possibleTypes` is a valid field.", + "description": "Indicates this type is a union. `possibleTypes` is a valid field.", "isDeprecated": false, "deprecationReason": null }, { "name": "ENUM", - "description": - "Indicates this type is an enum. `enumValues` is a valid field.", + "description": "Indicates this type is an enum. `enumValues` is a valid field.", "isDeprecated": false, "deprecationReason": null }, @@ -1483,15 +1462,13 @@ }, { "name": "LIST", - "description": - "Indicates this type is a list. `ofType` is a valid field.", + "description": "Indicates this type is a list. `ofType` is a valid field.", "isDeprecated": false, "deprecationReason": null }, { "name": "NON_NULL", - "description": - "Indicates this type is a non-null. `ofType` is a valid field.", + "description": "Indicates this type is a non-null. `ofType` is a valid field.", "isDeprecated": false, "deprecationReason": null } @@ -1986,15 +1963,13 @@ }, { "name": "INPUT_OBJECT", - "description": - "Location adjacent to an input object type definition.", + "description": "Location adjacent to an input object type definition.", "isDeprecated": false, "deprecationReason": null }, { "name": "INPUT_FIELD_DEFINITION", - "description": - "Location adjacent to an input object field definition.", + "description": "Location adjacent to an input object field definition.", "isDeprecated": false, "deprecationReason": null } @@ -2049,8 +2024,7 @@ }, { "name": "deprecated", - "description": - "Marks an element of a GraphQL schema as no longer supported.", + "description": "Marks an element of a GraphQL schema as no longer supported.", "locations": ["FIELD_DEFINITION", "ENUM_VALUE"], "args": [ { diff --git a/package.json b/package.json index c88da01298..ac7d7e2df6 100644 --- a/package.json +++ b/package.json @@ -1,40 +1,53 @@ { "name": "react-apollo", "version": "2.1.0-beta.2", + "author": "opensource@apollographql.com", + "browser": "lib/react-apollo.browser.umd.js", "description": "React data container for Apollo Client", + "keywords": [ + "apollo", + "graphql", + "react" + ], + "license": "MIT", + "main": "lib/react-apollo.umd.js", "module": "src/index.ts", - "browser": "lib/react-apollo.browser.umd.js", "typings": "lib/index.d.ts", - "main": "lib/react-apollo.umd.js", + "repository": { + "type": "git", + "url": "apollostack/react-apollo" + }, "scripts": { - "precommit": "lint-staged", + "compile": "npm run compile:esm && npm run compile:cjs", + "compile:cjs": "tsc --project tsconfig.cjs.json && rimraf lib/test && mv lib/src/* lib/. && rimraf lib/src", + "compile:esm": "tsc --project tsconfig.json -d && rimraf lib/test && mv lib/src/* lib/. && rimraf lib/src && cd lib && rename js mjs", "danger": "danger run --verbose", - "predeploy": "npm run compile", "deploy": "cd lib && npm publish --tag=beta", - "prefilesize": "npm run compile", "filesize": "bundlesize", - "test": "npm run lint && npm run type-check && npm run jest", "jest": "jest --maxWorkers=4 --coverage", - "test-watch": "jest --watch", + "lint": "tslint --project tsconfig.json --config tslint.json", + "lint-staged": "lint-staged", + "lint:fix": "npm run prettier && tslint 'src/*.ts*' --project tsconfig.json --fix", + "postcompile": "rollup -c && ./scripts/prepare-package.sh", + "precommit": "pretty-quick --staged", + "precompile": "rimraf lib", + "predeploy": "npm run compile", + "prefilesize": "npm run compile", + "prettier": "prettier --write \"./**/*.{js,jsx,ts*,md,graphql,json}\"", + "test": "npm run lint && npm run type-check && npm run jest", "test-preact": "jest --config ./jest.preact.config.json --no-cache", - "type-check": "tsc --project tsconfig.json --noEmit ", - "test:compiled": - "npm run test:compiled:browser:umd && npm run test:compiled:server:umd && npm run test:compiled:cjs", + "test-watch": "jest --watch", + "test:compiled": "npm run test:compiled:browser:umd && npm run test:compiled:server:umd && npm run test:compiled:cjs", "test:compiled:browser:umd": "jest --config jest.browser.umd.config.js", - "test:compiled:server:umd": "jest --config jest.server.umd.config.js", "test:compiled:cjs": "jest --config jest.cjs.config.js", - "precompile": "rimraf lib", - "compile": "npm run compile:esm && npm run compile:cjs", - "compile:esm": - "tsc --project tsconfig.json -d && rimraf lib/test && mv lib/src/* lib/. && rimraf lib/src && cd lib && rename js mjs", - "compile:cjs": - "tsc --project tsconfig.cjs.json && rimraf lib/test && mv lib/src/* lib/. && rimraf lib/src", - "postcompile": "rollup -c && ./scripts/prepare-package.sh", - "watch": "tsc -w", - "lint": "tslint --project tsconfig.json --config tslint.json", - "lint:fix": "npm run prettier && tslint 'src/*.ts*' --project tsconfig.json --fix", - "lint-staged": "lint-staged", - "prettier": "prettier --write \"{,!(node_modules|lib|coverage|npm)/**/}*.{ts*,js*,json,md}\"" + "test:compiled:server:umd": "jest --config jest.server.umd.config.js", + "type-check": "tsc --project tsconfig.json --noEmit ", + "watch": "tsc -w" + }, + "babel": { + "presets": [ + "env" + ] }, "bundlesize": [ { @@ -42,36 +55,6 @@ "maxSize": "11 KB" } ], - "lint-staged": { - "*.{ts*}": [ - "prettier --write", - "npm run lint", - "git add" - ], - "*.{js*,json,md}": [ - "prettier --write", - "git add" - ] - }, - "repository": { - "type": "git", - "url": "apollostack/react-apollo" - }, - "keywords": [ - "ecmascript", - "es2015", - "jsnext", - "javascript", - "relay", - "npm", - "react" - ], - "author": "James Baxley ", - "babel": { - "presets": [ - "env" - ] - }, "jest": { "testEnvironment": "jsdom", "transform": { @@ -99,7 +82,12 @@ "/test/test-utils/setup.ts" ] }, - "license": "MIT", + "prettier": { + "printWidth": 100, + "singleQuote": true, + "semi": true, + "trailingComma": "all" + }, "peerDependencies": { "apollo-client": "^2.2.3", "react": "0.14.x || 15.* || ^15.0.0 || ^16.0.0" @@ -120,6 +108,7 @@ "@types/zen-observable": "0.5.3", "apollo-cache-inmemory": "1.1.9", "apollo-client": "2.2.5", + "apollo-link": "^1.0.6", "babel-core": "6.26.0", "babel-jest": "22.4.0", "babel-preset-env": "1.6.1", @@ -129,14 +118,15 @@ "enzyme": "3.3.0", "enzyme-adapter-react-16": "1.1.1", "flow-bin": "0.66.0", - "graphql": "0.11.7", + "graphql": "0.13.1", + "graphql-tag": "^2.7.0", "husky": "0.14.3", "jest": "22.3.0", "jsdom": "11.6.2", - "lint-staged": "6.1.0", "preact": "8.2.7", "preact-compat": "3.18.0", "prettier": "1.10.2", + "pretty-quick": "^1.4.1", "react": "16.2.0", "react-dom": "16.2.0", "react-test-renderer": "16.2.0", @@ -156,12 +146,10 @@ "zen-observable-ts": "0.5.0" }, "dependencies": { - "apollo-link": "^1.0.6", "fbjs": "^0.8.16", - "graphql-tag": "^2.7.0", "hoist-non-react-statics": "^2.3.1", "invariant": "^2.2.2", "lodash": "4.17.5", "prop-types": "^15.6.0" } -} \ No newline at end of file +} diff --git a/src/ApolloConsumer.tsx b/src/ApolloConsumer.tsx index 8644ebe450..437706decb 100644 --- a/src/ApolloConsumer.tsx +++ b/src/ApolloConsumer.tsx @@ -8,10 +8,7 @@ export interface ApolloConsumerProps { children: (client: ApolloClient) => React.ReactElement | null; } -const ApolloConsumer: React.StatelessComponent = ( - props, - context, -) => { +const ApolloConsumer: React.StatelessComponent = (props, context) => { invariant( !!context.client, `Could not find "client" in the context of ApolloConsumer. Wrap the root component in an `, diff --git a/src/ApolloProvider.tsx b/src/ApolloProvider.tsx index 431a44128e..495c296a08 100644 --- a/src/ApolloProvider.tsx +++ b/src/ApolloProvider.tsx @@ -11,9 +11,7 @@ export interface ApolloProviderProps { children: React.ReactNode; } -export default class ApolloProvider extends Component< - ApolloProviderProps -> { +export default class ApolloProvider extends Component> { static propTypes = { client: PropTypes.object.isRequired, children: PropTypes.element.isRequired, @@ -41,9 +39,7 @@ export default class ApolloProvider extends Component< render() { return ( - - {React.Children.only(this.props.children)} - + {React.Children.only(this.props.children)} ); } } diff --git a/src/Mutation.tsx b/src/Mutation.tsx index dbb644f3f6..dfcb604ef2 100644 --- a/src/Mutation.tsx +++ b/src/Mutation.tsx @@ -31,10 +31,9 @@ export declare type MutationUpdaterFn< } > = (proxy: DataProxy, mutationResult: FetchResult) => void; -export declare type FetchResult< - C = Record, - E = Record -> = ExecutionResult & { +export declare type FetchResult, E = Record> = ExecutionResult< + C +> & { extensions?: E; context?: C; }; @@ -53,9 +52,7 @@ export interface MutationProps { refetchQueries?: string[] | PureQueryOptions[] | RefetchQueriesProviderFn; update?: MutationUpdaterFn; children: ( - mutateFn: ( - options?: MutationOptions, - ) => Promise, + mutateFn: (options?: MutationOptions) => Promise, result?: MutationResult, ) => React.ReactNode; onCompleted?: (data: TData) => void; @@ -73,10 +70,7 @@ const initialState = { notCalled: true, }; -class Mutation< - TData = any, - TVariables = OperationVariables -> extends React.Component< +class Mutation extends React.Component< MutationProps, MutationState > { @@ -118,10 +112,7 @@ class Mutation< nextProps: MutationProps, nextContext: MutationContext, ) { - if ( - shallowEqual(this.props, nextProps) && - this.client === nextContext.client - ) { + if (shallowEqual(this.props, nextProps) && this.client === nextContext.client) { return; } @@ -167,14 +158,14 @@ class Mutation< private mutate = (options: MutationOptions) => { const { mutation, variables, optimisticResponse, refetchQueries, update } = this.props; - + return this.client.mutate({ mutation, variables, optimisticResponse, refetchQueries, update, - ...options + ...options, }); }; @@ -189,10 +180,7 @@ class Mutation< } }; - private onCompletedMutation = ( - response: ExecutionResult, - mutationId: number, - ) => { + private onCompletedMutation = (response: ExecutionResult, mutationId: number) => { const { onCompleted } = this.props; const data = response.data as TData; diff --git a/src/Query.tsx b/src/Query.tsx index 61db0bc661..087e056c2b 100644 --- a/src/Query.tsx +++ b/src/Query.tsx @@ -41,21 +41,14 @@ export type ObservableQueryFields = Pick< > & { refetch: (variables?: TVariables) => Promise>; fetchMore: (( - fetchMoreOptions: FetchMoreQueryOptions & - FetchMoreOptions, + fetchMoreOptions: FetchMoreQueryOptions & FetchMoreOptions, ) => Promise>) & (( - fetchMoreOptions: { query: DocumentNode } & FetchMoreQueryOptions< - TVariables2, - K - > & + fetchMoreOptions: { query: DocumentNode } & FetchMoreQueryOptions & FetchMoreOptions, ) => Promise>); updateQuery: ( - mapFn: ( - previousQueryResult: TData, - options: { variables?: TVariables }, - ) => TData, + mapFn: (previousQueryResult: TData, options: { variables?: TVariables }) => TData, ) => void; }; @@ -107,10 +100,10 @@ export interface QueryContext { client: ApolloClient; } -class Query< - TData = any, - TVariables = OperationVariables -> extends React.Component, QueryState> { +class Query extends React.Component< + QueryProps, + QueryState +> { static contextTypes = { client: PropTypes.object.isRequired, }; @@ -174,14 +167,8 @@ class Query< this.startQuerySubscription(); } - componentWillReceiveProps( - nextProps: QueryProps, - nextContext: QueryContext, - ) { - if ( - shallowEqual(this.props, nextProps) && - this.client === nextContext.client - ) { + componentWillReceiveProps(nextProps: QueryProps, nextContext: QueryContext) { + if (shallowEqual(this.props, nextProps) && this.client === nextContext.client) { return; } @@ -204,9 +191,7 @@ class Query< return children(queryResult); } - private initializeQueryObservable = ( - props: QueryProps, - ) => { + private initializeQueryObservable = (props: QueryProps) => { const { variables, pollInterval, diff --git a/src/QueryRecyclerProvider.tsx b/src/QueryRecyclerProvider.tsx index 98fefbd0e0..5e71c59c06 100644 --- a/src/QueryRecyclerProvider.tsx +++ b/src/QueryRecyclerProvider.tsx @@ -6,9 +6,7 @@ export interface QueryRecyclerProviderProps { children: React.ReactNode; } -class QueryRecyclerProvider extends React.Component< - QueryRecyclerProviderProps -> { +class QueryRecyclerProvider extends React.Component { static propTypes = { children: PropTypes.element.isRequired, }; diff --git a/src/Subscriptions.tsx b/src/Subscriptions.tsx index 578d94dbc8..a89bb72db7 100644 --- a/src/Subscriptions.tsx +++ b/src/Subscriptions.tsx @@ -16,10 +16,7 @@ export interface SubscriptionResult { error?: ApolloError; } -export interface SubscriptionProps< - TData = any, - TVariables = OperationVariables -> { +export interface SubscriptionProps { query: DocumentNode; variables?: TVariables; children: (result: SubscriptionResult) => React.ReactNode; @@ -53,10 +50,7 @@ class Subscription extends React.Component< private queryObservable: Observable; private querySubscription: ZenObservable.Subscription; - constructor( - props: SubscriptionProps, - context: SubscriptionContext, - ) { + constructor(props: SubscriptionProps, context: SubscriptionContext) { super(props, context); invariant( @@ -76,10 +70,7 @@ class Subscription extends React.Component< nextProps: SubscriptionProps, nextContext: SubscriptionContext, ) { - if ( - shallowEqual(this.props, nextProps) && - this.client === nextContext.client - ) { + if (shallowEqual(this.props, nextProps) && this.client === nextContext.client) { return; } diff --git a/src/getDataFromTree.ts b/src/getDataFromTree.ts index f187379008..07fc55aa58 100755 --- a/src/getDataFromTree.ts +++ b/src/getDataFromTree.ts @@ -31,10 +31,7 @@ interface PreactElement

{ } function getProps

(element: ReactElement

| PreactElement

): P { - return ( - (element as ReactElement

).props || - (element as PreactElement

).attributes - ); + return (element as ReactElement

).props || (element as PreactElement

).attributes; } function isReactElement( @@ -43,12 +40,8 @@ function isReactElement( return !!(element as any).type; } -function isComponentClass( - Comp: ComponentType, -): Comp is ComponentClass { - return ( - Comp.prototype && (Comp.prototype.render || Comp.prototype.isReactComponent) - ); +function isComponentClass(Comp: ComponentType): Comp is ComponentClass { + return Comp.prototype && (Comp.prototype.render || Comp.prototype.isReactComponent); } function providesChildContext( @@ -104,11 +97,7 @@ export function walkTree( // React's TS type definitions don't contain context as a third parameter for // setState's updater function. // Remove this cast to `any` when that is fixed. - newState = (newState as any)( - instance.state, - instance.props, - instance.context, - ); + newState = (newState as any)(instance.state, instance.props, instance.context); } instance.state = Object.assign({}, instance.state, newState); }; @@ -215,9 +204,7 @@ export default function getDataFromTree( // wait on each query that we found, re-rendering the subtree when it's done const mappedQueries = queries.map(({ query, element, context }) => { // we've just grabbed the query for element, so don't try and get it again - return query - .then(_ => getDataFromTree(element, context, false)) - .catch(e => errors.push(e)); + return query.then(_ => getDataFromTree(element, context, false)).catch(e => errors.push(e)); }); // Run all queries. If there are errors, still wait for all queries to execute @@ -227,11 +214,7 @@ export default function getDataFromTree( const error = errors.length === 1 ? errors[0] - : new Error( - `${ - errors.length - } errors were thrown when executing your GraphQL queries.`, - ); + : new Error(`${errors.length} errors were thrown when executing your GraphQL queries.`); error.queryErrors = errors; throw error; } diff --git a/src/graphql.tsx b/src/graphql.tsx index c24fedb7ca..3acf15b98d 100644 --- a/src/graphql.tsx +++ b/src/graphql.tsx @@ -1,10 +1,6 @@ import * as React from 'react'; import * as PropTypes from 'prop-types'; -import ApolloClient, { - ApolloError, - ObservableQuery, - ApolloQueryResult, -} from 'apollo-client'; +import ApolloClient, { ApolloError, ObservableQuery, ApolloQueryResult } from 'apollo-client'; import { ZenObservable } from 'zen-observable-ts'; import { parser, DocumentType } from './parser'; import { DocumentNode } from 'graphql'; @@ -82,12 +78,7 @@ export default function graphql< Partial> >( document: DocumentNode, - operationOptions: OperationOption< - TProps, - TData, - TGraphQLVariables, - TChildProps - > = {}, + operationOptions: OperationOption = {}, ) { // extract options const { @@ -196,10 +187,7 @@ export default function graphql< } } - componentWillReceiveProps( - nextProps: GraphqlProps, - nextContext: GraphqlContext, - ) { + componentWillReceiveProps(nextProps: GraphqlProps, nextContext: GraphqlContext) { if (this.shouldSkip(nextProps)) { if (!this.shouldSkip(this.props)) { // if this has changed, we better unsubscribe @@ -273,17 +261,13 @@ export default function graphql< this.unsubscribeFromQuery(); } - if (this.type === DocumentType.Subscription) - this.unsubscribeFromQuery(); + if (this.type === DocumentType.Subscription) this.unsubscribeFromQuery(); this.hasMounted = false; } getQueryRecycler() { - return ( - this.context.getQueryRecycler && - this.context.getQueryRecycler(GraphQL) - ); + return this.context.getQueryRecycler && this.context.getQueryRecycler(GraphQL); } getClient(props: GraphqlProps): ApolloClient { @@ -310,11 +294,7 @@ export default function graphql< let opts = mapPropsToOptions(props); if (newOpts && newOpts.variables) { - newOpts.variables = Object.assign( - {}, - opts.variables, - newOpts.variables, - ); + newOpts.variables = Object.assign({}, opts.variables, newOpts.variables); } if (newOpts) opts = Object.assign({}, opts, newOpts); @@ -340,9 +320,7 @@ export default function graphql< invariant( typeof variableProp !== 'undefined', - `The operation '${operation.name}' wrapping '${getDisplayName( - WrappedComponent, - )}' ` + + `The operation '${operation.name}' wrapping '${getDisplayName(WrappedComponent)}' ` + `is expecting a variable: '${ variable.name.value }' but it was not found in the props ` + @@ -353,9 +331,7 @@ export default function graphql< return opts; } - calculateResultProps( - result: (GraphqlQueryControls & TData) | MutationFunc, - ) { + calculateResultProps(result: (GraphqlQueryControls & TData) | MutationFunc) { let name = this.type === DocumentType.Mutation ? 'mutate' : 'data'; if (operationOptions.name) name = operationOptions.name; @@ -364,10 +340,7 @@ export default function graphql< ownProps: this.props, }; if (mapResultToProps) { - this.lastResultProps = mapResultToProps( - newResult, - this.lastResultProps, - ); + this.lastResultProps = mapResultToProps(newResult, this.lastResultProps); return this.lastResultProps; } @@ -456,10 +429,7 @@ export default function graphql< const opts = this.calculateOptions() as any; if (opts.ssr === false) return false; - if ( - opts.fetchPolicy === 'network-only' || - opts.fetchPolicy === 'cache-and-network' - ) { + if (opts.fetchPolicy === 'network-only' || opts.fetchPolicy === 'cache-and-network') { opts.fetchPolicy = 'cache-first'; // ignore force fetch in SSR; } @@ -488,9 +458,7 @@ export default function graphql< } if (results.data) { - const clashingKeys = Object.keys( - observableQueryFields(results.data), - ); + const clashingKeys = Object.keys(observableQueryFields(results.data)); invariant( clashingKeys.length === 0, `the result of the '${graphQLDisplayName}' operation contains ` + @@ -578,9 +546,7 @@ export default function graphql< if (typeof opts.variables === 'undefined') delete opts.variables; (opts as any).mutation = document; - return this.getClient(this.props).mutate(opts as any) as Promise< - ApolloQueryResult - >; + return this.getClient(this.props).mutate(opts as any) as Promise>; } dataForChild() { @@ -629,10 +595,7 @@ export default function graphql< : `${error.message}\n${error.stack}`; } - console.error( - `Unhandled (in react-apollo:${graphQLDisplayName})`, - errorMessage, - ); + console.error(`Unhandled (in react-apollo:${graphQLDisplayName})`, errorMessage); } }, 10); Object.defineProperty(data, 'error', { @@ -649,10 +612,7 @@ export default function graphql< Object.assign(data, this.previousData, currentResult.data); } else if (error) { // if there is error, use any previously cached data - Object.assign( - data, - (this.queryObservable.getLastResult() || {}).data, - ); + Object.assign(data, (this.queryObservable.getLastResult() || {}).data); } else { Object.assign(data, currentResult.data); this.previousData = currentResult.data; @@ -687,11 +647,7 @@ export default function graphql< const { shouldRerender, renderedElement, props } = this; this.shouldRerender = false; - if ( - !shouldRerender && - renderedElement && - renderedElement.type === WrappedComponent - ) { + if (!shouldRerender && renderedElement && renderedElement.type === WrappedComponent) { return renderedElement; } @@ -699,8 +655,7 @@ export default function graphql< const clientProps = this.calculateResultProps(data); const mergedPropsAndData = Object.assign({}, props, clientProps); - if (operationOptions.withRef) - (mergedPropsAndData as any).ref = this.setWrappedInstance; + if (operationOptions.withRef) (mergedPropsAndData as any).ref = this.setWrappedInstance; this.renderedElement = ; return this.renderedElement; } diff --git a/src/parser.ts b/src/parser.ts index 488a8232c6..e49c050fd9 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -42,23 +42,19 @@ export function parser(document: DocumentNode): IDocumentDefinition { ); const queries = document.definitions.filter( - (x: DefinitionNode) => - x.kind === 'OperationDefinition' && x.operation === 'query', + (x: DefinitionNode) => x.kind === 'OperationDefinition' && x.operation === 'query', ); const mutations = document.definitions.filter( - (x: DefinitionNode) => - x.kind === 'OperationDefinition' && x.operation === 'mutation', + (x: DefinitionNode) => x.kind === 'OperationDefinition' && x.operation === 'mutation', ); const subscriptions = document.definitions.filter( - (x: DefinitionNode) => - x.kind === 'OperationDefinition' && x.operation === 'subscription', + (x: DefinitionNode) => x.kind === 'OperationDefinition' && x.operation === 'subscription', ); invariant( - !fragments.length || - (queries.length || mutations.length || subscriptions.length), + !fragments.length || (queries.length || mutations.length || subscriptions.length), `Passing only a fragment to 'graphql' is not yet supported. ` + `You must include a query, subscription or mutation as well`, ); @@ -75,9 +71,7 @@ export function parser(document: DocumentNode): IDocumentDefinition { type = queries.length ? DocumentType.Query : DocumentType.Mutation; if (!queries.length && !mutations.length) type = DocumentType.Subscription; - const definitions = queries.length - ? queries - : mutations.length ? mutations : subscriptions; + const definitions = queries.length ? queries : mutations.length ? mutations : subscriptions; invariant( definitions.length === 1, diff --git a/src/queryRecycler.ts b/src/queryRecycler.ts index 40caf0898e..81f5f8bd2f 100644 --- a/src/queryRecycler.ts +++ b/src/queryRecycler.ts @@ -93,10 +93,7 @@ export class ObservableQueryRecycler { // to check accuracy of data (which it may not know) // so if there are new variables when recycling, we don't recyle and make an entirely // new observable after cleaning up the old one - if ( - !shallowEqual(modifiableOpts.variables || {}, observableQuery.variables) - ) - return null; + if (!shallowEqual(modifiableOpts.variables || {}, observableQuery.variables)) return null; // When we reuse an `ObservableQuery` then the document and component // GraphQL display name should be the same. Only the options may be diff --git a/src/renderToStringWithData.ts b/src/renderToStringWithData.ts index 458681432c..f373ff93b7 100755 --- a/src/renderToStringWithData.ts +++ b/src/renderToStringWithData.ts @@ -3,10 +3,6 @@ import * as ReactDOM from 'react-dom/server'; import { default as getDataFromTree } from './getDataFromTree'; -export function renderToStringWithData( - component: ReactElement, -): Promise { - return getDataFromTree(component).then(() => - ReactDOM.renderToString(component), - ); +export function renderToStringWithData(component: ReactElement): Promise { + return getDataFromTree(component).then(() => ReactDOM.renderToString(component)); } diff --git a/src/test-links.ts b/src/test-links.ts index a8f1f87ab7..cb5459a7ec 100644 --- a/src/test-links.ts +++ b/src/test-links.ts @@ -59,17 +59,14 @@ export class MockLink extends ApolloLink { } const original = [...this.mockedResponsesByKey[key]]; - const { result, error, delay, newData } = - this.mockedResponsesByKey[key].shift() || ({} as any); + const { result, error, delay, newData } = this.mockedResponsesByKey[key].shift() || ({} as any); if (newData) { original[0].result = newData(); this.mockedResponsesByKey[key].push(original[0]); } if (!result && !error) { - throw new Error( - `Mocked response should contain either result or error: ${key}`, - ); + throw new Error(`Mocked response should contain either result or error: ${key}`); } return new Observable(observer => { @@ -141,9 +138,7 @@ function requestToKey(request: GraphQLRequest): string { // Pass in multiple mocked responses, so that you can test flows that end up // making multiple queries to the server -export function mockSingleLink( - ...mockedResponses: MockedResponse[] -): ApolloLink { +export function mockSingleLink(...mockedResponses: MockedResponse[]): ApolloLink { return new MockLink(mockedResponses); } diff --git a/src/types.ts b/src/types.ts index 0206639f8a..31d237928e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -21,10 +21,7 @@ export type OperationVariables = { */ export type RefetchQueriesProviderFn = (...args: any[]) => string[] | PureQueryOptions[]; -export interface MutationOpts< - TData = any, - TGraphQLVariables = OperationVariables -> { +export interface MutationOpts { variables?: TGraphQLVariables; optimisticResponse?: TData; refetchQueries?: string[] | PureQueryOptions[] | RefetchQueriesProviderFn; @@ -56,22 +53,16 @@ export interface GraphqlQueryControls { startPolling: (pollInterval: number) => void; stopPolling: () => void; subscribeToMore: (options: SubscribeToMoreOptions) => () => void; - updateQuery: ( - mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any, - ) => void; + updateQuery: (mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any) => void; } -export type MutationFunc< - TData = any, - TGraphQLVariables = OperationVariables -> = ( +export type MutationFunc = ( opts?: MutationOpts, ) => Promise>; -export type DataValue< - TData, - TGraphQLVariables = OperationVariables -> = GraphqlQueryControls & +export type DataValue = GraphqlQueryControls< + TGraphQLVariables +> & // data may not yet be loaded Partial; @@ -81,18 +72,11 @@ export interface DataProps { } // export to allow usage individually for simple components -export interface MutateProps< - TData = any, - TGraphQLVariables = OperationVariables -> { +export interface MutateProps { mutate: MutationFunc; } -export type ChildProps< - TProps = {}, - TData = {}, - TGraphQLVariables = OperationVariables -> = TProps & +export type ChildProps = TProps & Partial> & Partial>; @@ -112,11 +96,7 @@ export type NamedProps = TProps & { ownProps: R; }; -export interface OptionProps< - TProps = any, - TData = any, - TGraphQLVariables = OperationVariables -> +export interface OptionProps extends Partial>, Partial> { ownProps: TProps; @@ -131,15 +111,8 @@ export interface OperationOption< options?: | QueryOpts | MutationOpts - | (( - props: TProps, - ) => - | QueryOpts - | MutationOpts); - props?: ( - props: OptionProps, - lastProps: TChildProps, - ) => TChildProps; + | ((props: TProps) => QueryOpts | MutationOpts); + props?: (props: OptionProps, lastProps: TChildProps) => TChildProps; skip?: boolean | ((props: any) => boolean); name?: string; withRef?: boolean; diff --git a/src/withApollo.tsx b/src/withApollo.tsx index e688fdacba..3f80f77950 100644 --- a/src/withApollo.tsx +++ b/src/withApollo.tsx @@ -33,8 +33,7 @@ export default function withApollo( getWrappedInstance() { invariant( operationOptions.withRef, - `To access the wrapped instance, you need to specify ` + - `{ withRef: true } in the options`, + `To access the wrapped instance, you need to specify ` + `{ withRef: true } in the options`, ); return this.wrappedInstance; @@ -50,9 +49,7 @@ export default function withApollo( {client => { const props = Object.assign({}, this.props, { client, - ref: operationOptions.withRef - ? this.setWrappedInstance - : undefined, + ref: operationOptions.withRef ? this.setWrappedInstance : undefined, }); return ; }} diff --git a/test/client/Mutation.test.tsx b/test/client/Mutation.test.tsx index 3527f283e7..10dabf7f08 100644 --- a/test/client/Mutation.test.tsx +++ b/test/client/Mutation.test.tsx @@ -243,9 +243,7 @@ it('calls the onCompleted prop as soon as the mutation is complete', done => { }); it('renders result of the children render prop', () => { - const Component = () => ( - {() =>

} - ); + const Component = () => {() =>
}; const wrapper = mount( @@ -267,9 +265,7 @@ it('renders an error state', done => { } else if (count === 1 && result) { expect(result.loading).toBeTruthy(); } else if (count === 2 && result) { - expect(result.error).toEqual( - new Error('Network error: error occurred'), - ); + expect(result.error).toEqual(new Error('Network error: error occurred')); done(); } count++; @@ -461,9 +457,7 @@ it('allows an optimistic response prop', done => { setTimeout(() => { createTodo(); const dataInStore = client.cache.extract(true); - expect(dataInStore['Todo:99']).toEqual( - optimisticResponse.createTodo, - ); + expect(dataInStore['Todo:99']).toEqual(optimisticResponse.createTodo); }); } else if (count === 1) { expect(result).toEqual({ @@ -515,9 +509,7 @@ it('allows passing an optimistic response to the mutate function', done => { setTimeout(() => { createTodo({ optimisticResponse }); const dataInStore = client.cache.extract(true); - expect(dataInStore['Todo:99']).toEqual( - optimisticResponse.createTodo, - ); + expect(dataInStore['Todo:99']).toEqual(optimisticResponse.createTodo); }); } else if (count === 1) { expect(result).toEqual({ @@ -543,7 +535,6 @@ it('allows passing an optimistic response to the mutate function', done => { ); }); - it('allows a refetchQueries prop', done => { const query = gql` query getTodo { @@ -624,7 +615,6 @@ it('allows a refetchQueries prop', done => { ); }); - it('allows refetchQueries to be passed to the mutate function', done => { const query = gql` query getTodo { @@ -769,9 +759,9 @@ it('allows for overriding the options passed in the props by passing them in the const variablesProp = { text: 'play tennis', }; - + const variablesMutateFn = { - text: "go swimming" + text: 'go swimming', }; let count = 0; @@ -808,7 +798,7 @@ it('allows for overriding the options passed in the props by passing them in the { request: { query: mutation, variables: variablesMutateFn }, result: { data: data2 }, - } + }, ]; mount( @@ -911,9 +901,7 @@ it('errors if a query is passed instead of a mutation', () => { {() => null} , ); - }).toThrowError( - 'The component requires a graphql mutation, but got a query.', - ); + }).toThrowError('The component requires a graphql mutation, but got a query.'); console.log = errorLogger; }); @@ -934,9 +922,7 @@ it('errors when changing from mutation to a query', done => { componentDidCatch(e: Error) { expect(e).toEqual( - new Error( - 'The component requires a graphql mutation, but got a query.', - ), + new Error('The component requires a graphql mutation, but got a query.'), ); done(); } diff --git a/test/client/Query.test.tsx b/test/client/Query.test.tsx index 87e0b378fd..43aef62449 100644 --- a/test/client/Query.test.tsx +++ b/test/client/Query.test.tsx @@ -67,9 +67,7 @@ describe('Query component', () => { const { client: clientResult, ...rest } = result; if (result.loading) { - expect(rest).toMatchSnapshot( - 'result in render prop while loading' - ); + expect(rest).toMatchSnapshot('result in render prop while loading'); expect(clientResult).toBe(client); } else { expect(rest).toMatchSnapshot('result in render prop'); @@ -85,19 +83,17 @@ describe('Query component', () => { wrapper = mount( - + , ); }); it('renders using the children prop', done => { - const Component = () => ( - {_ =>
} - ); + const Component = () => {_ =>
}; wrapper = mount( - + , ); catchAsyncError(done, () => { expect(wrapper!.find('div').exists()).toBeTruthy(); @@ -148,7 +144,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -167,9 +163,7 @@ describe('Query component', () => { return null; } catchAsyncError(done, () => { - expect(result.error).toEqual( - new Error('Network error: error occurred') - ); + expect(result.error).toEqual(new Error('Network error: error occurred')); done(); }); return null; @@ -180,7 +174,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -279,7 +273,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -319,10 +313,7 @@ describe('Query component', () => { fetchMoreResult ? { allPeople: { - people: [ - ...prev.allPeople.people, - ...fetchMoreResult.allPeople.people, - ], + people: [...prev.allPeople.people, ...fetchMoreResult.allPeople.people], }, } : prev, @@ -335,10 +326,7 @@ describe('Query component', () => { catchAsyncError(done, () => { expect(stripSymbols(result.data)).toEqual({ allPeople: { - people: [ - ...data1.allPeople.people, - ...data2.allPeople.people, - ], + people: [...data1.allPeople.people, ...data2.allPeople.people], }, }); @@ -355,7 +343,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -417,7 +405,7 @@ describe('Query component', () => { wrapper = mount( - + , ); jest.runTimersToTime(POLL_INTERVAL * POLL_COUNT); @@ -476,7 +464,7 @@ describe('Query component', () => { wrapper = mount( - + , ); jest.runTimersToTime(POLL_INTERVAL * POLL_COUNT); @@ -538,7 +526,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); }); @@ -562,7 +550,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -614,7 +602,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -667,7 +655,7 @@ describe('Query component', () => { wrapper = mount( - + , ); jest.runTimersToTime(POLL_INTERVAL * POLL_COUNT); @@ -696,11 +684,9 @@ describe('Query component', () => { mount( {() => null} - + , ); - }).toThrowError( - 'The component requires a graphql query, but got a mutation.' - ); + }).toThrowError('The component requires a graphql query, but got a mutation.'); console.error = errorLogger; }); @@ -722,11 +708,9 @@ describe('Query component', () => { mount( {() => null} - + , ); - }).toThrowError( - 'The component requires a graphql query, but got a subscription.' - ); + }).toThrowError('The component requires a graphql query, but got a subscription.'); console.error = errorLogger; }); @@ -808,7 +792,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -881,7 +865,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -1016,7 +1000,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); }); @@ -1041,7 +1025,7 @@ describe('Query component', () => { componentDidCatch(error: any) { catchAsyncError(done, () => { const expectedError = new Error( - 'The component requires a graphql query, but got a subscription.' + 'The component requires a graphql query, but got a subscription.', ); expect(error).toEqual(expectedError); console.error = errorLog; @@ -1067,7 +1051,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); @@ -1087,7 +1071,7 @@ describe('Query component', () => { const link = mockSingleLink( { request: { query }, result: { data } }, { request: { query }, error: new Error('This is an error!') }, - { request: { query }, result: { data: dataTwo } } + { request: { query }, result: { data: dataTwo } }, ); const client = new ApolloClient({ link, @@ -1116,9 +1100,7 @@ describe('Query component', () => { } // First result is loaded, run a refetch to get the second result // which is an error. - expect(stripSymbols(result.data.allPeople)).toEqual( - data.allPeople - ); + expect(stripSymbols(result.data.allPeople)).toEqual(data.allPeople); setTimeout(() => { result.refetch().then(() => { done.fail('Expected error value on first refetch.'); @@ -1154,9 +1136,7 @@ describe('Query component', () => { done.fail('Should have data by this point'); break; } - expect(stripSymbols(result.data.allPeople)).toEqual( - dataTwo.allPeople - ); + expect(stripSymbols(result.data.allPeople)).toEqual(dataTwo.allPeople); done(); break; default: @@ -1174,7 +1154,7 @@ describe('Query component', () => { wrapper = mount( - + , ); }); }); diff --git a/test/client/__snapshots__/Query.test.tsx.snap b/test/client/__snapshots__/Query.test.tsx.snap index df21779b67..f9c6b600da 100644 --- a/test/client/__snapshots__/Query.test.tsx.snap +++ b/test/client/__snapshots__/Query.test.tsx.snap @@ -25,9 +25,7 @@ Object { } `; -exports[ - `Query component calls the children prop: result in render prop while loading 1` -] = ` +exports[`Query component calls the children prop: result in render prop while loading 1`] = ` Object { "data": undefined, "error": undefined, diff --git a/test/client/getDataFromTree.test.tsx b/test/client/getDataFromTree.test.tsx index 2fc33fb40b..84f40c9be3 100644 --- a/test/client/getDataFromTree.test.tsx +++ b/test/client/getDataFromTree.test.tsx @@ -127,13 +127,7 @@ describe('SSR', () => { it('functional stateless components with null children', () => { let elementCount = 0; - const MyComponent = ({ - n, - children = null, - }: { - n: number; - children: React.ReactNode; - }) => ( + const MyComponent = ({ n, children = null }: { n: number; children: React.ReactNode }) => (
{_.times(n, i => )} {children} @@ -318,15 +312,11 @@ describe('SSR', () => { firstName: string; }; } - const WrappedElement = graphql(query)( - ({ data }: ChildProps) => ( -
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} -
- ), - ); + const WrappedElement = graphql(query)(({ data }: ChildProps) => ( +
+ {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName} +
+ )); const app = ( @@ -370,9 +360,7 @@ describe('SSR', () => { const WrappedElement = () => ( {({ data, loading }) => ( -
- {loading || !data ? 'loading' : data.currentUser.firstName} -
+
{loading || !data ? 'loading' : data.currentUser.firstName}
)}
); @@ -417,9 +405,7 @@ describe('SSR', () => { options: { fetchPolicy: 'network-only' }, })(({ data }: ChildProps) => (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
)); @@ -463,9 +449,7 @@ describe('SSR', () => { options: { fetchPolicy: 'cache-and-network' }, })(({ data }: ChildProps) => (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
)); @@ -506,15 +490,11 @@ describe('SSR', () => { }; } - const WrappedElement = graphql(query)( - ({ data }: ChildProps) => ( -
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} -
- ), - ); + const WrappedElement = graphql(query)(({ data }: ChildProps) => ( +
+ {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName} +
+ )); const Page = () => (
@@ -588,29 +568,15 @@ describe('SSR', () => { type WithIdChildProps = ChildProps; const withId = graphql(idQuery); - type WithUserChildProps = ChildProps< - Props, - UserQueryData, - UserQueryVariables - >; - const withUser = graphql< - WithIdChildProps, - UserQueryData, - UserQueryVariables - >(userQuery, { + type WithUserChildProps = ChildProps; + const withUser = graphql(userQuery, { skip: ({ data: { loading } }) => loading, options: ({ data }) => ({ variables: { id: data!.currentUser!.id }, }), }); - const Component: React.StatelessComponent = ({ - data, - }) => ( -
- {!data || data.loading || !data.user - ? 'loading' - : data.user.firstName} -
+ const Component: React.StatelessComponent = ({ data }) => ( +
{!data || data.loading || !data.user ? 'loading' : data.user.firstName}
); const WrappedComponent = withId(withUser(Component)); @@ -651,11 +617,9 @@ describe('SSR', () => { firstName: string; }; } - const WrappedElement = graphql(query)( - ({ data }: ChildProps) => ( -
{!data || data.loading ? 'loading' : data.error}
- ), - ); + const WrappedElement = graphql(query)(({ data }: ChildProps) => ( +
{!data || data.loading ? 'loading' : data.error}
+ )); const Page = () => (
@@ -710,9 +674,7 @@ describe('SSR', () => { } const WrappedElement = graphql(query, { skip: true, - })(({ data }: ChildProps) => ( -
{!data ? 'skipped' : 'dang'}
- )); + })(({ data }: ChildProps) =>
{!data ? 'skipped' : 'dang'}
); const app = ( @@ -761,9 +723,7 @@ describe('SSR', () => { const Element = graphql(query)( ({ data }: ChildProps) => (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
), ); @@ -777,9 +737,7 @@ describe('SSR', () => { return getDataFromTree(app).then(() => { const initialState = cache.extract(); expect(initialState).toBeTruthy(); - expect( - initialState['$ROOT_QUERY.currentUser({"id":"1"})'], - ).toBeTruthy(); + expect(initialState['$ROOT_QUERY.currentUser({"id":"1"})']).toBeTruthy(); }); }); @@ -817,10 +775,7 @@ describe('SSR', () => { id: string; } - class Element extends React.Component< - ChildProps, - { thing: number } - > { + class Element extends React.Component, { thing: number }> { state = { thing: 1 }; componentWillMount() { @@ -832,9 +787,7 @@ describe('SSR', () => { expect(this.state.thing).toBe(2); return (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
); } @@ -852,9 +805,7 @@ describe('SSR', () => { .then(() => { const initialState = cache.extract(); expect(initialState).toBeTruthy(); - expect( - initialState['$ROOT_QUERY.currentUser({"id":"1"})'], - ).toBeTruthy(); + expect(initialState['$ROOT_QUERY.currentUser({"id":"1"})']).toBeTruthy(); done(); }) .catch(console.error); @@ -933,10 +884,7 @@ describe('SSR', () => { client: null | ApolloClient; } - class Element extends React.Component< - ChildProps, - State - > { + class Element extends React.Component, State> { state: State = { thing: 1, userId: null, @@ -945,11 +893,7 @@ describe('SSR', () => { componentWillMount() { this.setState( - ( - state: State, - props: Props, - context: { client: ApolloClient }, - ) => + (state: State, props: Props, context: { client: ApolloClient }) => ({ thing: state.thing + 1, userId: props.id, @@ -965,9 +909,7 @@ describe('SSR', () => { expect(this.state.client).toBe(apolloClient); return (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
); } @@ -985,9 +927,7 @@ describe('SSR', () => { .then(() => { const initialState = apolloClient.cache.extract(); expect(initialState).toBeTruthy(); - expect( - initialState['$ROOT_QUERY.currentUser({"id":"1"})'], - ).toBeTruthy(); + expect(initialState['$ROOT_QUERY.currentUser({"id":"1"})']).toBeTruthy(); done(); }) .catch(console.error); @@ -1037,9 +977,7 @@ describe('SSR', () => { options: props => ({ variables: props, ssr: false }), })(({ data }) => (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
)); @@ -1089,9 +1027,7 @@ describe('SSR', () => { const Element = (props: { id: string }) => ( {({ data, loading }) => ( -
- {loading || !data ? 'loading' : data.currentUser.firstName} -
+
{loading || !data ? 'loading' : data.currentUser.firstName}
)}
); @@ -1182,11 +1118,7 @@ describe('SSR', () => { const Element: React.StatelessComponent< QueryChildProps & { action: (variables: {}) => Promise } > = ({ data }) => ( -
- {data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} -
+
{data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
); const WrappedElement = withQuery(withMutation(Element)); @@ -1250,10 +1182,7 @@ describe('SSR', () => { }); const withMutation = graphql(mutation); - const withQuery = graphql< - Props & ChildProps, - QueryData - >(query, { + const withQuery = graphql, QueryData>(query, { props: ({ ownProps, data }) => { expect(ownProps.mutate).toBeTruthy(); return { @@ -1266,9 +1195,7 @@ describe('SSR', () => { ChildProps, QueryData, {}> > = ({ data }) => (
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} + {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName}
); @@ -1310,15 +1237,11 @@ describe('SSR', () => { cache: new Cache({ addTypename: false }), }); - const WrappedElement = graphql<{}, Data>(query)( - ({ data }: ChildProps<{}, Data>) => ( -
- {!data || data.loading || !data.currentUser - ? 'loading' - : data.currentUser.firstName} -
- ), - ); + const WrappedElement = graphql<{}, Data>(query)(({ data }: ChildProps<{}, Data>) => ( +
+ {!data || data.loading || !data.currentUser ? 'loading' : data.currentUser.firstName} +
+ )); class MyRootContainer extends React.Component<{}, { color: string }> { constructor(props: {}) { diff --git a/test/client/graphql/client-option.test.tsx b/test/client/graphql/client-option.test.tsx index c858596308..3c81c43092 100644 --- a/test/client/graphql/client-option.test.tsx +++ b/test/client/graphql/client-option.test.tsx @@ -167,9 +167,7 @@ describe('client option', () => { const Container = graphql(query)( class extends React.Component> { - componentWillReceiveProps({ - data, - }: ChildProps) { + componentWillReceiveProps({ data }: ChildProps) { expect(data!.loading).toBeFalsy(); // first data done(); } diff --git a/test/client/graphql/fragments.test.tsx b/test/client/graphql/fragments.test.tsx index 988b058d87..94d01a732d 100644 --- a/test/client/graphql/fragments.test.tsx +++ b/test/client/graphql/fragments.test.tsx @@ -38,9 +38,7 @@ describe('fragments', () => { class extends React.Component> { componentWillReceiveProps(props: ChildProps<{}, Data>) { expect(props.data!.loading).toBeFalsy(); - expect(stripSymbols(props.data!.allPeople)).toEqual( - expectedData.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(expectedData.allPeople); } render() { return null; diff --git a/test/client/graphql/mutations/index.test.tsx b/test/client/graphql/mutations/index.test.tsx index bf9acd8136..8f26fc8354 100644 --- a/test/client/graphql/mutations/index.test.tsx +++ b/test/client/graphql/mutations/index.test.tsx @@ -65,15 +65,11 @@ describe('graphql(mutation)', () => { type InjectedProps = { [name: string]: (name: string) => void; }; - const ContainerWithData = graphql( - query, - { - props: ({ ownProps, mutate: addPerson }) => ({ - [ownProps.methodName]: (name: string) => - addPerson!({ variables: { name } }), - }), - }, - )(({ myInjectedMutationMethod }) => { + const ContainerWithData = graphql(query, { + props: ({ ownProps, mutate: addPerson }) => ({ + [ownProps.methodName]: (name: string) => addPerson!({ variables: { name } }), + }), + })(({ myInjectedMutationMethod }) => { expect(myInjectedMutationMethod).toBeTruthy(); expect(typeof myInjectedMutationMethod).toBe('function'); return null; diff --git a/test/client/graphql/mutations/queries.test.tsx b/test/client/graphql/mutations/queries.test.tsx index 02b0372d15..b704a8c2b6 100644 --- a/test/client/graphql/mutations/queries.test.tsx +++ b/test/client/graphql/mutations/queries.test.tsx @@ -54,9 +54,7 @@ describe('graphql(mutation) query integration', () => { }); const dataInStore = client.cache.extract(true); - expect(stripSymbols(dataInStore['Todo:99'])).toEqual( - optimisticResponse.createTodo, - ); + expect(stripSymbols(dataInStore['Todo:99'])).toEqual(optimisticResponse.createTodo); } render() { return null; @@ -160,21 +158,17 @@ describe('graphql(mutation) query integration', () => { }); const dataInStore = cache.extract(true); - expect( - stripSymbols(dataInStore['$ROOT_MUTATION.createTodo']), - ).toEqual(optimisticResponse.createTodo); + expect(stripSymbols(dataInStore['$ROOT_MUTATION.createTodo'])).toEqual( + optimisticResponse.createTodo, + ); return; } if (count === 0) { count++; - expect(stripSymbols(props.data.todo_list.tasks)).toEqual([ - optimisticResponse.createTodo, - ]); + expect(stripSymbols(props.data.todo_list.tasks)).toEqual([optimisticResponse.createTodo]); } else if (count === 1) { - expect(stripSymbols(props.data.todo_list.tasks)).toEqual([ - mutationData.createTodo, - ]); + expect(stripSymbols(props.data.todo_list.tasks)).toEqual([mutationData.createTodo]); done(); } } @@ -260,15 +254,9 @@ describe('graphql(mutation) query integration', () => { } let count = 0; - const MutationContainer = graphql( - mutation, - )( - class extends React.Component< - ChildProps - > { - componentWillReceiveProps( - props: ChildProps, - ) { + const MutationContainer = graphql(mutation)( + class extends React.Component> { + componentWillReceiveProps(props: ChildProps) { if (count === 1) { props.mutate!().then(result => { expect(stripSymbols(result.data)).toEqual(mutationData); @@ -294,9 +282,7 @@ describe('graphql(mutation) query integration', () => { count++; } render() { - return ( - - ); + return ; } }, ); @@ -418,12 +404,8 @@ describe('graphql(mutation) query integration', () => { } let refetched = false; - class RelatedUIComponent extends React.Component< - ChildProps<{}, QueryData, QueryVariables> - > { - componentWillReceiveProps( - props: ChildProps<{}, QueryData, QueryVariables>, - ) { + class RelatedUIComponent extends React.Component> { + componentWillReceiveProps(props: ChildProps<{}, QueryData, QueryVariables>) { if (refetched) { expect(props.data!.account!.currentPlan.name).toBe('Free'); done(); @@ -434,28 +416,19 @@ describe('graphql(mutation) query integration', () => { } } - const RelatedUIComponentWithData = graphql<{}, QueryData, QueryVariables>( - overlappingQuery, - { - options: { variables: { accountId } }, - }, - )(RelatedUIComponent); + const RelatedUIComponentWithData = graphql<{}, QueryData, QueryVariables>(overlappingQuery, { + options: { variables: { accountId } }, + })(RelatedUIComponent); const withQuery = graphql<{}, QueryData, QueryVariables>(billingInfoQuery, { options: { variables: { accountId } }, }); type WithQueryChildProps = ChildProps<{}, QueryData, QueryVariables>; - const withMutation = graphql< - WithQueryChildProps, - MutationData, - MutationVariables - >(setPlanMutation); - type WithMutationChildProps = ChildProps< - WithQueryChildProps, - MutationData, - MutationVariables - >; + const withMutation = graphql( + setPlanMutation, + ); + type WithMutationChildProps = ChildProps; let count = 0; class PaymentDetail extends React.Component { diff --git a/test/client/graphql/mutations/recycled-queries.test.tsx b/test/client/graphql/mutations/recycled-queries.test.tsx index 0d911d29f4..a4a69c2dec 100644 --- a/test/client/graphql/mutations/recycled-queries.test.tsx +++ b/test/client/graphql/mutations/recycled-queries.test.tsx @@ -4,12 +4,7 @@ import gql from 'graphql-tag'; import ApolloClient, { MutationUpdaterFn } from 'apollo-client'; import { InMemoryCache as Cache } from 'apollo-cache-inmemory'; import { mockSingleLink } from '../../../../src/test-utils'; -import { - ApolloProvider, - graphql, - ChildProps, - MutationFunc, -} from '../../../../src'; +import { ApolloProvider, graphql, ChildProps, MutationFunc } from '../../../../src'; import stripSymbols from '../../../test-utils/stripSymbols'; import { DocumentNode } from 'graphql'; @@ -357,9 +352,7 @@ describe('graphql(mutation) update queries', () => { let queryRenderCount = 0; const Query = graphql(query)( - class extends React.Component< - ChildProps - > { + class extends React.Component> { componentWillMount() { queryMountCount++; } @@ -386,16 +379,12 @@ describe('graphql(mutation) update queries', () => { case 2: expect(queryMountCount).toBe(2); expect(queryUnmountCount).toBe(1); - expect(stripSymbols(this.props.data!.todo_list)).toEqual( - updatedData.todo_list, - ); + expect(stripSymbols(this.props.data!.todo_list)).toEqual(updatedData.todo_list); break; case 3: expect(queryMountCount).toBe(2); expect(queryUnmountCount).toBe(1); - expect(stripSymbols(this.props.data!.todo_list)).toEqual( - updatedData.todo_list, - ); + expect(stripSymbols(this.props.data!.todo_list)).toEqual(updatedData.todo_list); break; default: throw new Error('Rendered too many times'); diff --git a/test/client/graphql/queries/api.test.tsx b/test/client/graphql/queries/api.test.tsx index f43f512c79..4b0b7cd25b 100644 --- a/test/client/graphql/queries/api.test.tsx +++ b/test/client/graphql/queries/api.test.tsx @@ -70,9 +70,7 @@ describe('[queries] api', () => { .refetch({ first: 2 }) // new variables .then(response => { expect(stripSymbols(response.data)).toEqual(data1); - expect(stripSymbols(data!.allPeople)).toEqual( - data1.allPeople, - ); + expect(stripSymbols(data!.allPeople)).toEqual(data1.allPeople); done(); }); }) @@ -182,9 +180,7 @@ describe('[queries] api', () => { variables: { skip: 2 }, updateQuery: (prev, { fetchMoreResult }) => ({ allPeople: { - people: prev.allPeople.people.concat( - fetchMoreResult!.allPeople.people, - ), + people: prev.allPeople.people.concat(fetchMoreResult!.allPeople.people), }, }), }) diff --git a/test/client/graphql/queries/errors.test.tsx b/test/client/graphql/queries/errors.test.tsx index 34c70bc916..4b55386911 100644 --- a/test/client/graphql/queries/errors.test.tsx +++ b/test/client/graphql/queries/errors.test.tsx @@ -5,13 +5,7 @@ import ApolloClient from 'apollo-client'; import { InMemoryCache as Cache } from 'apollo-cache-inmemory'; import { withState } from 'recompose'; import { mockSingleLink } from '../../../../src/test-utils'; -import { - ApolloProvider, - graphql, - ChildProps, - Query, - QueryResult, -} from '../../../../src'; +import { ApolloProvider, graphql, ChildProps, Query, QueryResult } from '../../../../src'; import stripSymbols from '../../../test-utils/stripSymbols'; import { DocumentNode } from 'graphql'; @@ -205,9 +199,7 @@ describe('[queries] errors', () => { // tslint:disable-line iteration += 1; if (iteration === 1) { - expect(stripSymbols(props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); props.setVar(2); } else if (iteration === 2) { expect(props.data!.loading).toBeTruthy(); @@ -268,9 +260,7 @@ describe('[queries] errors', () => { let renderCount = 0; @graphql<{}, Data>(query) - class HandledErrorComponent extends React.Component< - ChildProps<{}, Data> - > { + class HandledErrorComponent extends React.Component> { render(): React.ReactNode { try { switch (renderCount++) { @@ -278,9 +268,7 @@ describe('[queries] errors', () => { expect(this.props.data!.loading).toEqual(true); break; case 1: - expect(this.props.data!.error!.message).toEqual( - 'Network error: oops', - ); + expect(this.props.data!.error!.message).toEqual('Network error: oops'); break; default: throw new Error('Too many renders.'); @@ -344,9 +332,7 @@ describe('[queries] errors', () => { let renderCount = 0; @graphql<{}, Data>(query) - class UnhandledErrorComponent extends React.Component< - ChildProps<{}, Data> - > { + class UnhandledErrorComponent extends React.Component> { render(): React.ReactNode { try { switch (renderCount++) { @@ -419,23 +405,17 @@ describe('[queries] errors', () => { try { switch (count++) { case 0: - expect(stripSymbols(props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); props.data!.refetch().catch(() => null); break; case 1: expect(props.data!.loading).toBeTruthy(); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); break; case 2: expect(props.data!.loading).toBeFalsy(); expect(props.data!.error).toBeTruthy(); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); done(); break; default: @@ -521,9 +501,7 @@ describe('[queries] errors', () => { case 3: expect(props.data!.loading).toBeFalsy(); expect(props.data!.error).toBeFalsy(); - expect(stripSymbols(props.data!.allPeople)).toEqual( - dataTwo.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(dataTwo.allPeople); done(); break; default: @@ -580,9 +558,7 @@ describe('[queries] errors', () => { class extends React.Component { componentWillReceiveProps({ data }: ChildProps) { expect(data!.error).toBeTruthy(); - expect(data!.error!.graphQLErrors[0].message).toEqual( - 'this is an error', - ); + expect(data!.error!.graphQLErrors[0].message).toEqual('this is an error'); expect(data).toMatchObject({ allPeople: { people: null } }); done(); } @@ -628,9 +604,7 @@ describe('[queries] errors', () => { class ErrorContainer extends React.Component { componentWillReceiveProps(props: QueryResult) { expect(props.error).toBeTruthy(); - expect(props.error!.graphQLErrors[0].message).toEqual( - 'this is an error', - ); + expect(props.error!.graphQLErrors[0].message).toEqual('this is an error'); expect(props.data!.allPeople!).toMatchObject({ people: null }); done(); } diff --git a/test/client/graphql/queries/index.test.tsx b/test/client/graphql/queries/index.test.tsx index c65633f59b..0e3dca0748 100644 --- a/test/client/graphql/queries/index.test.tsx +++ b/test/client/graphql/queries/index.test.tsx @@ -5,12 +5,7 @@ import gql from 'graphql-tag'; import ApolloClient from 'apollo-client'; import { InMemoryCache as Cache } from 'apollo-cache-inmemory'; import { mockSingleLink } from '../../../../src/test-utils'; -import { - ApolloProvider, - graphql, - DataProps, - ChildProps, -} from '../../../../src'; +import { ApolloProvider, graphql, DataProps, ChildProps } from '../../../../src'; import stripSymbols from '../../../test-utils/stripSymbols'; import catchAsyncError from '../../../test-utils/catchAsyncError'; @@ -52,13 +47,11 @@ describe('queries', () => { }; } - const ContainerWithData = graphql(query)( - ({ data }: DataProps) => { - expect(data).toBeTruthy(); - expect(data.loading).toBeTruthy(); - return null; - }, - ); + const ContainerWithData = graphql(query)(({ data }: DataProps) => { + expect(data).toBeTruthy(); + expect(data.loading).toBeTruthy(); + return null; + }); const output = renderer.create( @@ -214,9 +207,7 @@ describe('queries', () => { componentWillReceiveProps(props: ChildProps<{}, Data>) { expect(props.data!.loading).toBeFalsy(); expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); - expect(stripSymbols(props.data!.otherPeople)).toEqual( - data.otherPeople, - ); + expect(stripSymbols(props.data!.otherPeople)).toEqual(data.otherPeople); done(); } render() { @@ -262,9 +253,7 @@ describe('queries', () => { componentWillReceiveProps(props: ChildProps) { expect(props.data!.loading).toBeFalsy(); expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); - expect(stripSymbols(props.data!.variables)).toEqual( - this.props.data!.variables, - ); + expect(stripSymbols(props.data!.variables)).toEqual(this.props.data!.variables); done(); } render() { @@ -369,9 +358,7 @@ describe('queries', () => { const Container = graphql, Data, Vars>(query)( class extends React.Component, Data, Vars>> { - componentWillReceiveProps( - props: ChildProps, Data, Vars>, - ) { + componentWillReceiveProps(props: ChildProps, Data, Vars>) { expect(props.data!.loading).toBeFalsy(); expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); done(); diff --git a/test/client/graphql/queries/lifecycle.test.tsx b/test/client/graphql/queries/lifecycle.test.tsx index d98377c418..36964410fb 100644 --- a/test/client/graphql/queries/lifecycle.test.tsx +++ b/test/client/graphql/queries/lifecycle.test.tsx @@ -333,23 +333,17 @@ describe('[queries] lifecycle', () => { if (count === 1) { expect(props.foo).toEqual(42); expect(props.data!.loading).toEqual(false); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data1.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data1.allPeople); props.changeState(); } else if (count === 2) { expect(props.foo).toEqual(43); expect(props.data!.loading).toEqual(false); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data1.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data1.allPeople); props.data!.refetch(); } else if (count === 3) { expect(props.foo).toEqual(43); expect(props.data!.loading).toEqual(false); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data2.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data2.allPeople); done(); } } catch (e) { @@ -365,12 +359,7 @@ describe('[queries] lifecycle', () => { class Parent extends React.Component { state = { foo: 42 }; render() { - return ( - this.setState({ foo: 43 })} - /> - ); + return this.setState({ foo: 43 })} />; } } diff --git a/test/client/graphql/queries/loading.test.tsx b/test/client/graphql/queries/loading.test.tsx index 32ea63531e..d57e41017c 100644 --- a/test/client/graphql/queries/loading.test.tsx +++ b/test/client/graphql/queries/loading.test.tsx @@ -178,20 +178,12 @@ describe('[queries] loading', () => { // variables changed, new query is loading, but old data is still there if (count === 1 && nextProps.data!.loading) { expect(nextProps.data!.networkStatus).toBe(2); - expect(stripSymbols(nextProps.data!.allPeople)).toEqual( - data1.allPeople, - ); + expect(stripSymbols(nextProps.data!.allPeople)).toEqual(data1.allPeople); } // query with new variables is loaded - if ( - count === 1 && - !nextProps.data!.loading && - this.props.data!.loading - ) { + if (count === 1 && !nextProps.data!.loading && this.props.data!.loading) { expect(nextProps.data!.networkStatus).toBe(7); - expect(stripSymbols(nextProps.data!.allPeople)).toEqual( - data2.allPeople, - ); + expect(stripSymbols(nextProps.data!.allPeople)).toEqual(data2.allPeople); done(); } } @@ -263,16 +255,12 @@ describe('[queries] loading', () => { case 1: expect(props.data!.loading).toBeTruthy(); expect(props.data!.networkStatus).toBe(4); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); break; case 2: expect(props.data!.loading).toBeFalsy(); expect(props.data!.networkStatus).toBe(7); - expect(stripSymbols(props.data!.allPeople)).toEqual( - data2.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data2.allPeople); resolve(); break; default: @@ -348,9 +336,7 @@ describe('[queries] loading', () => { if (count === 3) { // remounted data after fetch expect(props.data!.loading).toBeFalsy(); - expect(props.data!.allPeople!.people[0].name).toMatch( - /Darth Skywalker - /, - ); + expect(props.data!.allPeople!.people[0].name).toMatch(/Darth Skywalker - /); done(); } } catch (e) { @@ -566,9 +552,7 @@ describe('[queries] loading', () => { setFirst: (first: number) => void; } - const connect = ( - component: React.ComponentType, - ): React.ComponentType<{}> => { + const connect = (component: React.ComponentType): React.ComponentType<{}> => { return class extends React.Component<{}, { first: number }> { constructor(props: {}) { super(props); diff --git a/test/client/graphql/queries/observableQuery.test.tsx b/test/client/graphql/queries/observableQuery.test.tsx index f49a0fbf44..653801cacf 100644 --- a/test/client/graphql/queries/observableQuery.test.tsx +++ b/test/client/graphql/queries/observableQuery.test.tsx @@ -69,9 +69,7 @@ describe('[queries] observableQuery', () => { // be present; if (count === 3) { expect(this.props.data!.loading).toBeFalsy(); - expect(stripSymbols(this.props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(this.props.data!.allPeople)).toEqual(data.allPeople); } } @@ -86,9 +84,7 @@ describe('[queries] observableQuery', () => { if (count === 3) { expect(prevProps.data!.loading).toBeTruthy(); expect(this.props.data!.loading).toBeFalsy(); - expect(stripSymbols(this.props.data!.allPeople)).toEqual( - data.allPeople, - ); + expect(stripSymbols(this.props.data!.allPeople)).toEqual(data.allPeople); // ensure first assertion and umount tree assert1(); @@ -208,8 +204,7 @@ describe('[queries] observableQuery', () => { let keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1']); - const queryObservable1 = (client.queryManager as any).queries.get('1') - .observableQuery; + const queryObservable1 = (client.queryManager as any).queries.get('1').observableQuery; // The query should only have been invoked when first mounting and not when resetting store expect(called).toBe(1); @@ -218,8 +213,7 @@ describe('[queries] observableQuery', () => { keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1']); - const queryObservable2 = (client.queryManager as any).queries.get('1') - .observableQuery; + const queryObservable2 = (client.queryManager as any).queries.get('1').observableQuery; expect(queryObservable1).toBe(queryObservable2); }); @@ -284,16 +278,14 @@ describe('[queries] observableQuery', () => { let keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1']); - const queryObservable1 = (client.queryManager as any).queries.get('1') - .observableQuery; + const queryObservable1 = (client.queryManager as any).queries.get('1').observableQuery; remount(); setTimeout(() => { keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1']); - const queryObservable2 = (client.queryManager as any).queries.get('1') - .observableQuery; + const queryObservable2 = (client.queryManager as any).queries.get('1').observableQuery; expect(queryObservable1).toBe(queryObservable2); remount(); @@ -301,8 +293,7 @@ describe('[queries] observableQuery', () => { setTimeout(() => { keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1']); - const queryObservable3 = (client.queryManager as any).queries.get('1') - .observableQuery; + const queryObservable3 = (client.queryManager as any).queries.get('1').observableQuery; expect(queryObservable1).toBe(queryObservable3); wrapper.unmount(); @@ -373,10 +364,8 @@ describe('[queries] observableQuery', () => { let keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1', '2']); - const queryObservable1 = (client.queryManager as any).queries.get('1') - .observableQuery; - const queryObservable2 = (client.queryManager as any).queries.get('2') - .observableQuery; + const queryObservable1 = (client.queryManager as any).queries.get('1').observableQuery; + const queryObservable2 = (client.queryManager as any).queries.get('2').observableQuery; expect(queryObservable1).not.toBe(queryObservable2); remount(); @@ -384,10 +373,8 @@ describe('[queries] observableQuery', () => { setTimeout(() => { keys = Array.from((client.queryManager as any).queries.keys()); expect(keys).toEqual(['1', '2']); - const queryObservable3 = (client.queryManager as any).queries.get('1') - .observableQuery; - const queryObservable4 = (client.queryManager as any).queries.get('2') - .observableQuery; + const queryObservable3 = (client.queryManager as any).queries.get('1').observableQuery; + const queryObservable4 = (client.queryManager as any).queries.get('2').observableQuery; expect(queryObservable1).not.toBe(queryObservable2); // What we really want to test here is if the `queryObservable` on @@ -459,8 +446,7 @@ describe('[queries] observableQuery', () => { if (variables.first === 2) { // second variables render if (loading) expect(allPeople).toBeUndefined(); - if (!loading) - expect(stripSymbols(allPeople)).toEqual(data2.allPeople); + if (!loading) expect(stripSymbols(allPeople)).toEqual(data2.allPeople); } } catch (e) { done.fail(e); diff --git a/test/client/graphql/queries/reducer.test.tsx b/test/client/graphql/queries/reducer.test.tsx index 88402e4c06..538b62c720 100644 --- a/test/client/graphql/queries/reducer.test.tsx +++ b/test/client/graphql/queries/reducer.test.tsx @@ -194,9 +194,7 @@ describe('[queries] reducer', () => { let counter = 0; class Container extends React.Component { componentWillReceiveProps(nextProps: FinalProps) { - expect(stripSymbols(nextProps.wrapper.thingy)).toEqual( - expectedData.getThing, - ); + expect(stripSymbols(nextProps.wrapper.thingy)).toEqual(expectedData.getThing); if (counter === 1) { expect(nextProps.wrapper).toEqual(this.props.wrapper); done(); diff --git a/test/client/graphql/queries/skip.test.tsx b/test/client/graphql/queries/skip.test.tsx index 17750515d6..af17a29381 100644 --- a/test/client/graphql/queries/skip.test.tsx +++ b/test/client/graphql/queries/skip.test.tsx @@ -167,8 +167,7 @@ describe('[queries] skip', () => { componentWillReceiveProps(props: ChildProps) { count++; if (count === 1) expect(props.data!.loading).toBeTruthy(); - if (count === 2) - expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); + if (count === 2) expect(stripSymbols(props.data!.allPeople)).toEqual(data.allPeople); if (count === 2) { expect(renderCount).toBe(2); done(); @@ -181,10 +180,7 @@ describe('[queries] skip', () => { }, ); - class Parent extends React.Component< - {}, - { person: { id: number } | null } - > { + class Parent extends React.Component<{}, { person: { id: number } | null }> { state = { person: null }; componentDidMount() { @@ -443,12 +439,7 @@ describe('[queries] skip', () => { class Parent extends React.Component { state = { skip: false }; render() { - return ( - this.setState({ skip })} - /> - ); + return this.setState({ skip })} />; } } @@ -515,15 +506,11 @@ describe('[queries] skip', () => { } else { if (hasSkipped) { if (!newProps.data!.loading) { - expect(stripSymbols(newProps.data!.allPeople)).toEqual( - dataTwo.allPeople, - ); + expect(stripSymbols(newProps.data!.allPeople)).toEqual(dataTwo.allPeople); done(); } } else { - expect(stripSymbols(newProps.data!.allPeople)).toEqual( - dataOne.allPeople, - ); + expect(stripSymbols(newProps.data!.allPeople)).toEqual(dataOne.allPeople); this.props.setState({ skip: true }); } } @@ -625,12 +612,7 @@ describe('[queries] skip', () => { class Parent extends React.Component<{}, { skip: boolean }> { state = { skip: false }; render() { - return ( - this.setState({ skip })} - /> - ); + return this.setState({ skip })} />; } } @@ -683,8 +665,7 @@ describe('[queries] skip', () => { componentWillReceiveProps({ data }: ChildProps) { catchAsyncError(done, () => { // loading is true, but data still there - if (count === 0) - expect(stripSymbols(data!.allPeople)).toEqual(data1.allPeople); + if (count === 0) expect(stripSymbols(data!.allPeople)).toEqual(data1.allPeople); if (count === 1) expect(data).toBeUndefined(); if (count === 2 && !data!.loading) { expect(stripSymbols(data!.allPeople)).toEqual(data3.allPeople); diff --git a/test/client/graphql/queries/updateQuery.test.tsx b/test/client/graphql/queries/updateQuery.test.tsx index a42595a124..f382d0ce86 100644 --- a/test/client/graphql/queries/updateQuery.test.tsx +++ b/test/client/graphql/queries/updateQuery.test.tsx @@ -121,9 +121,7 @@ describe('[queries] updateQuery', () => { this.props.data!.updateQuery(p => p); done(); } catch (e) { - expect(e.toString()).toMatch( - /ObservableQuery with this id doesn't exist:/, - ); + expect(e.toString()).toMatch(/ObservableQuery with this id doesn't exist:/); done(); } } @@ -171,9 +169,7 @@ describe('[queries] updateQuery', () => { } componentWillReceiveProps(props: ChildProps<{}, Data>) { if (isUpdated) { - expect(stripSymbols(props.data!.allPeople)).toEqual( - data2.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data2.allPeople); done(); return; } else { @@ -224,9 +220,7 @@ describe('[queries] updateQuery', () => { class extends React.Component> { componentWillReceiveProps(props: ChildProps<{}, Data>) { if (isUpdated) { - expect(stripSymbols(props.data!.allPeople)).toEqual( - data2.allPeople, - ); + expect(stripSymbols(props.data!.allPeople)).toEqual(data2.allPeople); done(); return; } else { diff --git a/test/client/graphql/shared-operations.test.tsx b/test/client/graphql/shared-operations.test.tsx index a28ffdfd19..a6621cd757 100644 --- a/test/client/graphql/shared-operations.test.tsx +++ b/test/client/graphql/shared-operations.test.tsx @@ -5,13 +5,7 @@ import ApolloClient from 'apollo-client'; import { InMemoryCache as Cache } from 'apollo-cache-inmemory'; import { ApolloLink } from 'apollo-link'; import { mockSingleLink } from '../../../src/test-utils'; -import { - ApolloProvider, - ChildProps, - DataValue, - graphql, - withApollo, -} from '../../../src'; +import { ApolloProvider, ChildProps, DataValue, graphql, withApollo } from '../../../src'; import * as TestUtils from 'react-dom/test-utils'; import { DocumentNode } from 'graphql'; @@ -66,15 +60,10 @@ describe('shared operations', () => { , ) as any; - const decorated = TestUtils.findRenderedComponentWithType( - tree, - Decorated, - ); + const decorated = TestUtils.findRenderedComponentWithType(tree, Decorated); expect(() => (decorated as any).someMethod()).toThrow(); - expect((decorated as any).getWrappedInstance().someMethod()).toEqual( - testData, - ); + expect((decorated as any).getWrappedInstance().someMethod()).toEqual(testData); expect((decorated as any).wrappedInstance.someMethod()).toEqual(testData); const DecoratedWithSkip = withApollo(Container, { @@ -94,12 +83,8 @@ describe('shared operations', () => { ); expect(() => (decoratedWithSkip as any).someMethod()).toThrow(); - expect( - (decoratedWithSkip as any).getWrappedInstance().someMethod(), - ).toEqual(testData); - expect((decoratedWithSkip as any).wrappedInstance.someMethod()).toEqual( - testData, - ); + expect((decoratedWithSkip as any).getWrappedInstance().someMethod()).toEqual(testData); + expect((decoratedWithSkip as any).wrappedInstance.someMethod()).toEqual(testData); }); }); @@ -147,22 +132,16 @@ describe('shared operations', () => { // Since we want to test decorators usage, and this does not play well with Typescript, // we resort to setting everything as any to avoid type checking. - const withPeople: any = graphql<{}, PeopleData, {}, PeopleChildProps>( - peopleQuery, - { - name: 'people', - }, - ); + const withPeople: any = graphql<{}, PeopleData, {}, PeopleChildProps>(peopleQuery, { + name: 'people', + }); interface ShipsChildProps { ships: DataValue; } - const withShips: any = graphql<{}, ShipsData, {}, ShipsChildProps>( - shipsQuery, - { - name: 'ships', - }, - ); + const withShips: any = graphql<{}, ShipsData, {}, ShipsChildProps>(shipsQuery, { + name: 'ships', + }); @withPeople @withShips @@ -227,24 +206,19 @@ describe('shared operations', () => { people: DataValue; } - const withPeople = graphql<{}, PeopleData, {}, PeopleChildProps>( - peopleQuery, - { - name: 'people', - }, - ); + const withPeople = graphql<{}, PeopleData, {}, PeopleChildProps>(peopleQuery, { + name: 'people', + }); interface ShipsAndPeopleChildProps extends PeopleChildProps { ships: DataValue; } - const withShips = graphql< - PeopleChildProps, - ShipsData, - {}, - ShipsAndPeopleChildProps - >(shipsQuery, { - name: 'ships', - }); + const withShips = graphql( + shipsQuery, + { + name: 'ships', + }, + ); const ContainerWithData = withPeople( withShips((props: ShipsAndPeopleChildProps) => { @@ -372,14 +346,10 @@ describe('shared operations', () => { const decorated = TestUtils.findRenderedComponentWithType(tree, Decorated); expect(() => (decorated as any).someMethod()).toThrow(); - expect((decorated as any).getWrappedInstance().someMethod()).toEqual( - testData, - ); + expect((decorated as any).getWrappedInstance().someMethod()).toEqual(testData); expect((decorated as any).wrappedInstance.someMethod()).toEqual(testData); - const DecoratedWithSkip = graphql(query, { withRef: true, skip: true })( - Container, - ); + const DecoratedWithSkip = graphql(query, { withRef: true, skip: true })(Container); const treeWithSkip = TestUtils.renderIntoDocument( @@ -393,12 +363,8 @@ describe('shared operations', () => { ); expect(() => (decoratedWithSkip as any).someMethod()).toThrow(); - expect( - (decoratedWithSkip as any).getWrappedInstance().someMethod(), - ).toEqual(testData); - expect((decoratedWithSkip as any).wrappedInstance.someMethod()).toEqual( - testData, - ); + expect((decoratedWithSkip as any).getWrappedInstance().someMethod()).toEqual(testData); + expect((decoratedWithSkip as any).wrappedInstance.someMethod()).toEqual(testData); }); it('allows options to take an object', done => { @@ -503,10 +469,9 @@ describe('shared operations', () => { graphql<{}, PeopleData, {}, PeopleChildProps>(peopleQuery, { name: 'people', }), - graphql( - shipsQuery, - { name: 'ships' }, - ), + graphql(shipsQuery, { + name: 'ships', + }), ); const ContainerWithData = enhanced((props: ShipsAndPeopleChildProps) => { diff --git a/test/client/graphql/statics.test.tsx b/test/client/graphql/statics.test.tsx index bf2c5d81cf..f4d14c291f 100644 --- a/test/client/graphql/statics.test.tsx +++ b/test/client/graphql/statics.test.tsx @@ -25,9 +25,7 @@ describe('statics', () => { @graphql(sampleOperation) class ApolloContainer extends React.Component {} - expect((ApolloContainer as any).displayName).toBe( - 'Apollo(ApolloContainer)', - ); + expect((ApolloContainer as any).displayName).toBe('Apollo(ApolloContainer)'); }); it('honors custom display names', () => { diff --git a/test/client/graphql/subscriptions.test.tsx b/test/client/graphql/subscriptions.test.tsx index 146622eda1..1735ceb5e2 100644 --- a/test/client/graphql/subscriptions.test.tsx +++ b/test/client/graphql/subscriptions.test.tsx @@ -25,12 +25,7 @@ describe('subscriptions', () => { } }); - const results = [ - 'James Baxley', - 'John Pinkerton', - 'Sam Claridge', - 'Ben Coleman', - ].map(name => ({ + const results = ['James Baxley', 'John Pinkerton', 'Sam Claridge', 'Ben Coleman'].map(name => ({ result: { data: { user: { name } } }, delay: 10, })); @@ -54,14 +49,12 @@ describe('subscriptions', () => { user: { name: string }; } - const ContainerWithData = graphql(query)( - ({ data }: ChildProps) => { - expect(data).toBeTruthy(); - expect(data!.user).toBeFalsy(); - expect(data!.loading).toBeTruthy(); - return null; - }, - ); + const ContainerWithData = graphql(query)(({ data }: ChildProps) => { + expect(data).toBeTruthy(); + expect(data!.user).toBeFalsy(); + expect(data!.loading).toBeTruthy(); + return null; + }); wrapper = renderer.create( @@ -179,12 +172,9 @@ describe('subscriptions', () => { const { loading, user } = props.data!; expect(loading).toBeFalsy(); - if (count === 0) - expect(stripSymbols(user)).toEqual(results[0].result.data.user); - if (count === 1) - expect(stripSymbols(user)).toEqual(results[1].result.data.user); - if (count === 2) - expect(stripSymbols(user)).toEqual(results[2].result.data.user); + if (count === 0) expect(stripSymbols(user)).toEqual(results[0].result.data.user); + if (count === 1) expect(stripSymbols(user)).toEqual(results[1].result.data.user); + if (count === 2) expect(stripSymbols(user)).toEqual(results[2].result.data.user); if (count === 3) { expect(stripSymbols(user)).toEqual(results[3].result.data.user); done(); @@ -213,26 +203,13 @@ describe('subscriptions', () => { it('resubscribes to a subscription', done => { //we make an extra Hoc which will trigger the inner HoC to resubscribe //these are the results for the outer subscription - const triggerResults = [ - '0', - 'trigger resubscribe', - '3', - '4', - '5', - '6', - '7', - ].map(trigger => ({ + const triggerResults = ['0', 'trigger resubscribe', '3', '4', '5', '6', '7'].map(trigger => ({ result: { data: { trigger } }, delay: 10, })); //These are the results from the resubscription - const results3 = [ - 'NewUser: 1', - 'NewUser: 2', - 'NewUser: 3', - 'NewUser: 4', - ].map(name => ({ + const results3 = ['NewUser: 1', 'NewUser: 2', 'NewUser: 3', 'NewUser: 4'].map(name => ({ result: { data: { user: { name } } }, delay: 10, })); @@ -290,22 +267,13 @@ describe('subscriptions', () => { try { // odd counts will be outer wrapper getting subscriptions - ie unchanged expect(loading).toBeFalsy(); - if (count === 0) - expect(stripSymbols(user)).toEqual(results[0].result.data.user); - if (count === 1) - expect(stripSymbols(user)).toEqual(results[0].result.data.user); - if (count === 2) - expect(stripSymbols(user)).toEqual(results[2].result.data.user); - if (count === 3) - expect(stripSymbols(user)).toEqual(results[2].result.data.user); - if (count === 4) - expect(stripSymbols(user)).toEqual( - results3[2].result.data.user, - ); + if (count === 0) expect(stripSymbols(user)).toEqual(results[0].result.data.user); + if (count === 1) expect(stripSymbols(user)).toEqual(results[0].result.data.user); + if (count === 2) expect(stripSymbols(user)).toEqual(results[2].result.data.user); + if (count === 3) expect(stripSymbols(user)).toEqual(results[2].result.data.user); + if (count === 4) expect(stripSymbols(user)).toEqual(results3[2].result.data.user); if (count === 5) { - expect(stripSymbols(user)).toEqual( - results3[2].result.data.user, - ); + expect(stripSymbols(user)).toEqual(results3[2].result.data.user); done(); } } catch (e) { diff --git a/test/flow-usage.js b/test/flow-usage.js index 05787ee8bc..06e44b8fa6 100644 --- a/test/flow-usage.js +++ b/test/flow-usage.js @@ -13,12 +13,7 @@ import gql from 'graphql-tag'; import * as React from 'react'; import { withApollo, graphql } from '../src'; -import type { - OperationComponent, - GraphqlQueryControls, - ChildProps, - GraphqlData, -} from '../src'; +import type { OperationComponent, GraphqlQueryControls, ChildProps, GraphqlData } from '../src'; const query = gql` { @@ -110,11 +105,9 @@ class Cmplx2Component extends React.Component { ); } } -const withFancyData2: OperationComponent< - IQuery, - Cmplx2OwnProps, - Cmplx2ComponentProps, -> = graphql(query); +const withFancyData2: OperationComponent = graphql( + query, +); const Cmplx2WithData = withFancyData2(Cmplx2Component); const HERO_QUERY = gql` @@ -154,30 +147,28 @@ type Props = GraphqlData & { someProp: string, }; -const withCharacter: OperationComponent< - Response, - InputProps, - Props, - Variables, -> = graphql(HERO_QUERY, { - options: ({ episode }) => { - // $ExpectError [string] The operand of an arithmetic operation must be a number - episode * 10; - return { - // $ExpectError [number] This type is incompatible with string - variables: { episode: 10 }, - }; +const withCharacter: OperationComponent = graphql( + HERO_QUERY, + { + options: ({ episode }) => { + // $ExpectError [string] The operand of an arithmetic operation must be a number + episode * 10; + return { + // $ExpectError [number] This type is incompatible with string + variables: { episode: 10 }, + }; + }, + props: ({ data, ownProps }) => ({ + ...data, + // $ExpectError [string] This type cannot be compared to number + episode: ownProps.episode > 1, + // $ExpectError property `isHero`. Property not found on object type + isHero: data && data.hero && data.hero.isHero, + // $ExpectError Property `someProp`. This type is incompatible with string + someProp: 1, + }), }, - props: ({ data, ownProps }) => ({ - ...data, - // $ExpectError [string] This type cannot be compared to number - episode: ownProps.episode > 1, - // $ExpectError property `isHero`. Property not found on object type - isHero: data && data.hero && data.hero.isHero, - // $ExpectError Property `someProp`. This type is incompatible with string - someProp: 1, - }), -}); +); export default withCharacter(({ loading, hero, error }) => { if (loading) return
Loading
; diff --git a/test/internal-api/Subscription.test.tsx b/test/internal-api/Subscription.test.tsx index 75633d56d2..ece54fcee1 100644 --- a/test/internal-api/Subscription.test.tsx +++ b/test/internal-api/Subscription.test.tsx @@ -11,12 +11,7 @@ import { ApolloProvider } from '../../src'; import catchAsyncError from '../test-utils/catchAsyncError'; import Subscription from '../../src/Subscriptions'; -const results = [ - 'Luke Skywalker', - 'Han Solo', - 'Darth Vader', - 'Leia Skywalker', -].map(name => ({ +const results = ['Luke Skywalker', 'Han Solo', 'Darth Vader', 'Leia Skywalker'].map(name => ({ result: { data: { user: { name } } }, })); @@ -426,10 +421,7 @@ describe('should update', () => { render() { return ( - + {result => { const { loading, data } = result; catchAsyncError(done, () => { diff --git a/test/internal-api/parser.test.ts b/test/internal-api/parser.test.ts index 502aab3499..731a331421 100644 --- a/test/internal-api/parser.test.ts +++ b/test/internal-api/parser.test.ts @@ -53,9 +53,7 @@ describe('parser', () => { query One { user { name } } `; - expect(parser.bind(null, query)).toThrowError( - /not a valid GraphQL DocumentNode/, - ); + expect(parser.bind(null, query)).toThrowError(/not a valid GraphQL DocumentNode/); }); it('should return the name of the operation', () => { @@ -192,9 +190,7 @@ describe('parser', () => { } `; definition = subscription.definitions[0] as OperationDefinition; - expect(parser(subscription).variables).toEqual( - definition.variableDefinitions, - ); + expect(parser(subscription).variables).toEqual(definition.variableDefinitions); }); it('should not error if the operation has no variables', () => { @@ -226,8 +222,6 @@ describe('parser', () => { } `; definition = subscription.definitions[0] as OperationDefinition; - expect(parser(subscription).variables).toEqual( - definition.variableDefinitions, - ); + expect(parser(subscription).variables).toEqual(definition.variableDefinitions); }); }); diff --git a/test/server/server.test.tsx b/test/server/server.test.tsx index f5a5c8b5a4..2ad77ac12c 100644 --- a/test/server/server.test.tsx +++ b/test/server/server.test.tsx @@ -2,7 +2,8 @@ import * as React from 'react'; import ApolloClient from 'apollo-client'; import { ApolloLink, Observable } from 'apollo-link'; import { - execute, + print, + graphql as execute, GraphQLSchema, GraphQLObjectType, GraphQLList, @@ -10,45 +11,16 @@ import { GraphQLID, DocumentNode, } from 'graphql'; -import { - graphql, - ApolloProvider, - renderToStringWithData, - ChildProps, -} from '../../src'; +import { graphql, ApolloProvider, renderToStringWithData, ChildProps } from '../../src'; import gql from 'graphql-tag'; import { InMemoryCache as Cache } from 'apollo-cache-inmemory'; describe('SSR', () => { - // it('should render the expected markup', (done) => { - - // const query = gql`query ssr { allPeople(first: 1) { people { name } } }`; - // const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; - // const link = mockSingleLink({ request: { query }, result: { data } }); - // const client = new ApolloClient({ link }); - - // const Element = ({ ssr }) => (
{ssr.loading ? 'loading' : 'loaded'}
); - // const WrappedElement = graphql(query)(Element); - // const component = (); - - // try { - // const markup = ReactDOM.renderToString(component); - // expect(markup).to.match(/loading/); - // // We do a timeout to ensure the rest of the application does not fail - // // after the render - // setTimeout(() => done(), 10); - // } catch (e) { - // done(e); - // } - // }); - describe('`renderToStringWithData`', () => { // XXX break into smaller tests // XXX mock all queries it('should work on a non trivial example', function() { - const planetMap = new Map([ - ['Planet:1', { id: 'Planet:1', name: 'Tatooine' }], - ]); + const planetMap = new Map([['Planet:1', { id: 'Planet:1', name: 'Tatooine' }]]); const shipMap = new Map([ [ @@ -133,14 +105,7 @@ describe('SSR', () => { const apolloClient = new ApolloClient({ link: new ApolloLink(config => { return new Observable(observer => { - execute( - Schema, - config.query, - null, - null, - config.variables, - config.operationName, - ) + execute(Schema, print(config.query), null, null, config.variables, config.operationName) .then(result => { observer.next(result); observer.complete(); @@ -190,9 +155,7 @@ describe('SSR', () => { } } ` as DocumentNode) - class Starship extends React.Component< - ChildProps - > { + class Starship extends React.Component> { render(): React.ReactNode { const { data } = this.props; if (!data || data.loading || !data.ship) return null; @@ -260,9 +223,7 @@ describe('SSR', () => { return (

Planets

- {(data.allPlanets || []).map((planet, key) => ( -
{planet.name}
- ))} + {(data.allPlanets || []).map((planet, key) =>
{planet.name}
)}
); } diff --git a/test/test-utils.test.tsx b/test/test-utils.test.tsx index e676f56bed..4fdd5b2ca1 100644 --- a/test/test-utils.test.tsx +++ b/test/test-utils.test.tsx @@ -54,12 +54,8 @@ const withUser = graphql(queryWithoutTypename, { }); it('mocks the data and adds the typename to the query', done => { - class Container extends React.Component< - ChildProps - > { - componentWillReceiveProps( - nextProps: ChildProps, - ) { + class Container extends React.Component> { + componentWillReceiveProps(nextProps: ChildProps) { try { expect(nextProps.data!.user).toMatchSnapshot(); done(); @@ -93,12 +89,8 @@ it('mocks the data and adds the typename to the query', done => { }); it('errors if the variables in the mock and component do not match', done => { - class Container extends React.Component< - ChildProps - > { - componentWillReceiveProps( - nextProps: ChildProps, - ) { + class Container extends React.Component> { + componentWillReceiveProps(nextProps: ChildProps) { try { expect(nextProps.data!.user).toBeUndefined(); expect(nextProps.data!.error).toMatchSnapshot(); @@ -137,16 +129,10 @@ it('errors if the variables in the mock and component do not match', done => { }); it('mocks a network error', done => { - class Container extends React.Component< - ChildProps - > { - componentWillReceiveProps( - nextProps: ChildProps, - ) { + class Container extends React.Component> { + componentWillReceiveProps(nextProps: ChildProps) { try { - expect(nextProps.data!.error).toEqual( - new Error('Network error: something went wrong'), - ); + expect(nextProps.data!.error).toEqual(new Error('Network error: something went wrong')); done(); } catch (e) { done.fail(e); @@ -178,12 +164,8 @@ it('mocks a network error', done => { }); it('mocks the data without adding the typename', done => { - class Container extends React.Component< - ChildProps - > { - componentWillReceiveProps( - nextProps: ChildProps, - ) { + class Container extends React.Component> { + componentWillReceiveProps(nextProps: ChildProps) { try { expect(nextProps.data!.user).toMatchSnapshot(); done(); @@ -229,12 +211,8 @@ it('allows for passing a custom client', done => { cache: new InMemoryCache(), }); - class Container extends React.Component< - ChildProps - > { - componentWillReceiveProps( - nextProps: ChildProps, - ) { + class Container extends React.Component> { + componentWillReceiveProps(nextProps: ChildProps) { try { expect(nextProps.data!.user).toMatchSnapshot(); done(); diff --git a/test/test-utils/wrap.ts b/test/test-utils/wrap.ts index fe7c9abe17..ee959d4902 100644 --- a/test/test-utils/wrap.ts +++ b/test/test-utils/wrap.ts @@ -1,10 +1,9 @@ // XXX: this is also defined in apollo-client // I'm not sure why mocha doesn't provide something like this, you can't // always use promises -const wrap = ( - done: jest.DoneCallback, - cb: (...args: TArgs[]) => void, -) => (...args: TArgs[]) => { +const wrap = (done: jest.DoneCallback, cb: (...args: TArgs[]) => void) => ( + ...args: TArgs[] +) => { try { return cb(...args); } catch (e) { diff --git a/test/typescript-usage.tsx b/test/typescript-usage.tsx index 14bac2e307..7c0ab19b73 100644 --- a/test/typescript-usage.tsx +++ b/test/typescript-usage.tsx @@ -65,11 +65,7 @@ const withHistory = graphql(historyQuery, { class HistoryView extends React.Component> { render() { - if ( - this.props.data && - this.props.data.history && - this.props.data.history.length > 0 - ) { + if (this.props.data && this.props.data.history && this.props.data.history.length > 0) { return
yay type checking works
; } else { return null; @@ -103,11 +99,7 @@ const HistoryViewSFC = graphql(historyQuery, { @graphql(historyQuery) class DecoratedHistoryView extends React.Component> { render(): React.ReactNode { - if ( - this.props.data && - this.props.data.history && - this.props.data.history.length > 0 - ) { + if (this.props.data && this.props.data.history && this.props.data.history.length > 0) { return
yay type checking works
; } else { return null; @@ -119,20 +111,16 @@ class DecoratedHistoryView extends React.Component> { // -------------------------- // with custom props -const withProps = graphql< - Props, - Data, - {}, - { organisationData: DataValue | undefined } ->(historyQuery, { - props: ({ data }) => ({ - organisationData: data, - }), -}); - -const Foo = withProps(props => ( -
Woot {props.organisationData!.history}
-)); +const withProps = graphql | undefined }>( + historyQuery, + { + props: ({ data }) => ({ + organisationData: data, + }), + }, +); + +const Foo = withProps(props =>
Woot {props.organisationData!.history}
); ; // tslint:disable-line diff --git a/tslint.json b/tslint.json index cb36d664ca..75b9184bd8 100644 --- a/tslint.json +++ b/tslint.json @@ -48,11 +48,6 @@ "variable-declaration", "member-variable-declaration" ], - "variable-name": [ - false, - "check-format", - "allow-leading-underscore", - "ban-keywords" - ] + "variable-name": [false, "check-format", "allow-leading-underscore", "ban-keywords"] } }