From 5fafd1a75bd931ea8487033be750350ca88af30b Mon Sep 17 00:00:00 2001 From: Soichi Takamura Date: Thu, 9 Jan 2020 03:39:00 +0900 Subject: [PATCH] Proposing a new example "with-typescript-graphql" (#9803) * New example with-typescript-graphql * Update newer graphql-let * Apply @lfades 's suggestions * Use "lib" for tools directory * Move config decorator to next.config.js * Apply stricter tsconfig * mod: hide the word "apollo" from users * mod: Use variable name `withApollo` * Use the later version of graphql-let * Only pages can be in pages * Life improvements * fix: .grpahql-let.yml point to the wrong document path * Use a wider glob for less pitfalls * Add a note about it in README.md Co-authored-by: Luis Alvarez D. --- examples/with-typescript-graphql/.gitignore | 1 + .../with-typescript-graphql/.graphql-let.yml | 7 + examples/with-typescript-graphql/README.md | 65 +++++++ .../with-typescript-graphql/lib/resolvers.ts | 9 + .../with-typescript-graphql/lib/schema.ts | 10 ++ .../lib/type-defs.graphqls | 9 + .../lib/viewer.graphql | 7 + .../lib/with-apollo.tsx | 164 ++++++++++++++++++ .../with-typescript-graphql/next-env.d.ts | 7 + .../with-typescript-graphql/next.config.js | 17 ++ examples/with-typescript-graphql/package.json | 37 ++++ .../with-typescript-graphql/pages/about.tsx | 11 ++ .../pages/api/graphql.ts | 12 ++ .../with-typescript-graphql/pages/index.tsx | 24 +++ .../with-typescript-graphql/tsconfig.json | 23 +++ 15 files changed, 403 insertions(+) create mode 100644 examples/with-typescript-graphql/.gitignore create mode 100644 examples/with-typescript-graphql/.graphql-let.yml create mode 100644 examples/with-typescript-graphql/README.md create mode 100644 examples/with-typescript-graphql/lib/resolvers.ts create mode 100644 examples/with-typescript-graphql/lib/schema.ts create mode 100644 examples/with-typescript-graphql/lib/type-defs.graphqls create mode 100644 examples/with-typescript-graphql/lib/viewer.graphql create mode 100644 examples/with-typescript-graphql/lib/with-apollo.tsx create mode 100644 examples/with-typescript-graphql/next-env.d.ts create mode 100644 examples/with-typescript-graphql/next.config.js create mode 100644 examples/with-typescript-graphql/package.json create mode 100644 examples/with-typescript-graphql/pages/about.tsx create mode 100644 examples/with-typescript-graphql/pages/api/graphql.ts create mode 100644 examples/with-typescript-graphql/pages/index.tsx create mode 100644 examples/with-typescript-graphql/tsconfig.json diff --git a/examples/with-typescript-graphql/.gitignore b/examples/with-typescript-graphql/.gitignore new file mode 100644 index 000000000000..764f8b238767 --- /dev/null +++ b/examples/with-typescript-graphql/.gitignore @@ -0,0 +1 @@ +__generated__ diff --git a/examples/with-typescript-graphql/.graphql-let.yml b/examples/with-typescript-graphql/.graphql-let.yml new file mode 100644 index 000000000000..12ab765d5784 --- /dev/null +++ b/examples/with-typescript-graphql/.graphql-let.yml @@ -0,0 +1,7 @@ +generateDir: __generated__ +schema: '**/*.graphqls' +documents: '**/*.graphql' +plugins: + - typescript + - typescript-operations + - typescript-react-apollo diff --git a/examples/with-typescript-graphql/README.md b/examples/with-typescript-graphql/README.md new file mode 100644 index 000000000000..de77eef4f0e0 --- /dev/null +++ b/examples/with-typescript-graphql/README.md @@ -0,0 +1,65 @@ +# GraphQL and TypeScript Example + +## Deploy your own + +Deploy the example using [ZEIT Now](https://zeit.co/now): + +[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/new/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-typescript-graphql) + +## How to use + +### Using `create-next-app` + +Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example: + +```bash +npx create-next-app --example with-typescript-graphql with-typescript-graphql-app +# or +yarn create next-app --example with-typescript-graphql with-typescript-graphql-app +``` + +### Download manually + +Download the example: + +```bash +curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-typescript-graphql +cd with-typescript-graphql +``` + +Install it and run: + +```bash +npm install +npm run dev +# or +yarn +yarn dev +``` + +Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)): + +```bash +now +``` + +## The idea behind the example + +One of the strengths of GraphQL is [enforcing data types on runtime](https://graphql.github.io/graphql-spec/June2018/#sec-Value-Completion). Further, TypeScript and [GraphQL Code Generator](https://graphql-code-generator.com/) (graphql-codegen) make it safer by typing data statically, so you can write truly type-protected code with rich IDE assists. + +This template extends [Apollo Server and Client Example](https://github.com/zeit/next.js/tree/canary/examples/api-routes-apollo-server-and-client#readme) by rewriting in TypeScript and integrating [graphql-let](https://github.com/piglovesyou/graphql-let#readme), which runs [TypeScript React Apollo](https://graphql-code-generator.com/docs/plugins/typescript-react-apollo) in [graphql-codegen](https://github.com/dotansimha/graphql-code-generator#readme) under the hood. It enhances the typed GraphQL use as below. + +```typescript jsx +import { useNewsQuery } from './news.grpahql' + +const News: React.FC = () => { + // Typed already️⚡️ + const { data: { news } } = useNewsQuery() + if (news)
{news.map(...)}
+} +``` + +By default `**/*.graphqls` is recognized as GraphQL schema and `**/*.graphql` as GraphQL documents. If you prefer the other extensions, make sure the settings of the webpack loader in `next.config.js` and `.graphql-let.yml` point to the same files. + +Note: Do not be alarmed that you see two renders being executed. Apollo recursively traverses the React render tree looking for Apollo query components. When it has done that, it fetches all these queries and then passes the result to a cache. This cache is then used to render the data on the server side (another React render). +https://www.apollographql.com/docs/react/api/react-ssr/#getdatafromtree diff --git a/examples/with-typescript-graphql/lib/resolvers.ts b/examples/with-typescript-graphql/lib/resolvers.ts new file mode 100644 index 000000000000..b408e6353a9a --- /dev/null +++ b/examples/with-typescript-graphql/lib/resolvers.ts @@ -0,0 +1,9 @@ +const resolvers = { + Query: { + viewer(_parent, _args, _context, _info) { + return { id: 1, name: 'John Smith', status: 'cached' } + }, + }, +} + +export default resolvers diff --git a/examples/with-typescript-graphql/lib/schema.ts b/examples/with-typescript-graphql/lib/schema.ts new file mode 100644 index 000000000000..ed11df67f14b --- /dev/null +++ b/examples/with-typescript-graphql/lib/schema.ts @@ -0,0 +1,10 @@ +import { makeExecutableSchema } from 'graphql-tools' +import typeDefs from './type-defs.graphqls' +import resolvers from './resolvers' + +const schema = makeExecutableSchema({ + typeDefs, + resolvers, +}) + +export default schema diff --git a/examples/with-typescript-graphql/lib/type-defs.graphqls b/examples/with-typescript-graphql/lib/type-defs.graphqls new file mode 100644 index 000000000000..f198c8c143a4 --- /dev/null +++ b/examples/with-typescript-graphql/lib/type-defs.graphqls @@ -0,0 +1,9 @@ +type User { + id: ID! + name: String! + status: String! +} + +type Query { + viewer: User! +} diff --git a/examples/with-typescript-graphql/lib/viewer.graphql b/examples/with-typescript-graphql/lib/viewer.graphql new file mode 100644 index 000000000000..7f2a5b4faa79 --- /dev/null +++ b/examples/with-typescript-graphql/lib/viewer.graphql @@ -0,0 +1,7 @@ +query Viewer { + viewer { + id + name + status + } +} diff --git a/examples/with-typescript-graphql/lib/with-apollo.tsx b/examples/with-typescript-graphql/lib/with-apollo.tsx new file mode 100644 index 000000000000..2563f0c11af7 --- /dev/null +++ b/examples/with-typescript-graphql/lib/with-apollo.tsx @@ -0,0 +1,164 @@ +import { NextPage, NextPageContext } from 'next' +import React from 'react' +import Head from 'next/head' +import { ApolloProvider } from '@apollo/react-hooks' +import { ApolloClient } from 'apollo-client' +import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory' + +type TApolloClient = ApolloClient + +type InitialProps = { + apolloClient: TApolloClient + apolloState: any +} & Record + +type WithApolloPageContext = { + apolloClient: TApolloClient +} & NextPageContext + +let globalApolloClient: TApolloClient + +/** + * Creates and provides the apolloContext + * to a next.js PageTree. Use it by wrapping + * your PageComponent via HOC pattern. + */ +export default function withApolo( + PageComponent: NextPage, + { ssr = true } = {} +) { + const WithApollo = ({ + apolloClient, + apolloState, + ...pageProps + }: InitialProps) => { + const client = apolloClient || initApolloClient(apolloState) + return ( + + + + ) + } + + // Set the correct displayName in development + if (process.env.NODE_ENV !== 'production') { + const displayName = + PageComponent.displayName || PageComponent.name || 'Component' + + if (displayName === 'App') { + console.warn('This withApollo HOC only works with PageComponents.') + } + + WithApollo.displayName = `withApollo(${displayName})` + } + + if (ssr || PageComponent.getInitialProps) { + WithApollo.getInitialProps = async (ctx: WithApolloPageContext) => { + const { AppTree } = ctx + + // Initialize ApolloClient, add it to the ctx object so + // we can use it in `PageComponent.getInitialProp`. + const apolloClient = (ctx.apolloClient = initApolloClient()) + + // Run wrapped getInitialProps methods + let pageProps = {} + if (PageComponent.getInitialProps) { + pageProps = await PageComponent.getInitialProps(ctx) + } + + // Only on the server: + if (typeof window === 'undefined') { + // When redirecting, the response is finished. + // No point in continuing to render + if (ctx.res && ctx.res.finished) { + return pageProps + } + + // Only if ssr is enabled + if (ssr) { + try { + // Run all GraphQL queries + const { getDataFromTree } = await import('@apollo/react-ssr') + await getDataFromTree( + + ) + } catch (error) { + // Prevent Apollo Client GraphQL errors from crashing SSR. + // Handle them in components via the data.error prop: + // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error + console.error('Error while running `getDataFromTree`', error) + } + + // getDataFromTree does not call componentWillUnmount + // head side effect therefore need to be cleared manually + Head.rewind() + } + } + + // Extract query data from the Apollo store + const apolloState = apolloClient.cache.extract() + + return { + ...pageProps, + apolloState, + } + } + } + + return WithApollo +} + +/** + * Always creates a new apollo client on the server + * Creates or reuses apollo client in the browser. + * @param {Object} initialState + */ +function initApolloClient(initialState?: any) { + // Make sure to create a new client for every server-side request so that data + // isn't shared between connections (which would be bad) + if (typeof window === 'undefined') { + return createApolloClient(initialState) + } + + // Reuse client on the client-side + if (!globalApolloClient) { + globalApolloClient = createApolloClient(initialState) + } + + return globalApolloClient +} + +/** + * Creates and configures the ApolloClient + * @param {Object} [initialState={}] + */ +function createApolloClient(initialState = {}) { + const ssrMode = typeof window === 'undefined' + const cache = new InMemoryCache().restore(initialState) + + // Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient + return new ApolloClient({ + ssrMode, + link: createIsomorphLink(), + cache, + }) +} + +function createIsomorphLink() { + if (typeof window === 'undefined') { + const { SchemaLink } = require('apollo-link-schema') + const schema = require('./schema').default + return new SchemaLink({ schema }) + } else { + const { HttpLink } = require('apollo-link-http') + return new HttpLink({ + uri: '/api/graphql', + credentials: 'same-origin', + }) + } +} diff --git a/examples/with-typescript-graphql/next-env.d.ts b/examples/with-typescript-graphql/next-env.d.ts new file mode 100644 index 000000000000..aad42ee7ed71 --- /dev/null +++ b/examples/with-typescript-graphql/next-env.d.ts @@ -0,0 +1,7 @@ +/// +/// + +declare module '*.graphqls' { + import { DocumentNode } from 'graphql' + export default typeof DocumentNode +} diff --git a/examples/with-typescript-graphql/next.config.js b/examples/with-typescript-graphql/next.config.js new file mode 100644 index 000000000000..7d0d20fac74d --- /dev/null +++ b/examples/with-typescript-graphql/next.config.js @@ -0,0 +1,17 @@ +module.exports = { + webpack(config, options) { + config.module.rules.push({ + test: /\.graphql$/, + exclude: /node_modules/, + use: [options.defaultLoaders.babel, { loader: 'graphql-let/loader' }], + }) + + config.module.rules.push({ + test: /\.graphqls$/, + exclude: /node_modules/, + loader: 'graphql-tag/loader', + }) + + return config + }, +} diff --git a/examples/with-typescript-graphql/package.json b/examples/with-typescript-graphql/package.json new file mode 100644 index 000000000000..17a3e19e3c0b --- /dev/null +++ b/examples/with-typescript-graphql/package.json @@ -0,0 +1,37 @@ +{ + "name": "with-typescript-graphql", + "version": "0.1.0", + "author": "", + "license": "ISC", + "scripts": { + "codegen": "graphql-let", + "dev": "yarn codegen && next", + "build": "yarn codegen && next build", + "start": "next start" + }, + "dependencies": { + "@apollo/react-common": "3.1.3", + "@apollo/react-components": "^3.1.3", + "@apollo/react-hooks": "3.1.3", + "@apollo/react-ssr": "3.1.3", + "apollo-cache-inmemory": "1.6.5", + "apollo-client": "2.6.8", + "apollo-link-http": "1.5.16", + "apollo-link-schema": "1.2.4", + "apollo-server-micro": "2.9.14", + "apollo-utilities": "^1.3.3", + "graphql": "^14.5.8", + "graphql-tag": "^2.10.1", + "next": "latest", + "react": "^16.12.0", + "react-dom": "^16.12.0" + }, + "devDependencies": { + "@graphql-codegen/typescript": "^1.9.1", + "@graphql-codegen/typescript-operations": "^1.9.1", + "@graphql-codegen/typescript-react-apollo": "^1.9.1", + "@types/react": "^16.9.17", + "graphql-let": "0.x", + "typescript": "^3.7.4" + } +} diff --git a/examples/with-typescript-graphql/pages/about.tsx b/examples/with-typescript-graphql/pages/about.tsx new file mode 100644 index 000000000000..37a11a9e0965 --- /dev/null +++ b/examples/with-typescript-graphql/pages/about.tsx @@ -0,0 +1,11 @@ +import Link from 'next/link' + +export default () => ( +
+ This is a static page goto{' '} + + dynamic + {' '} + page. +
+) diff --git a/examples/with-typescript-graphql/pages/api/graphql.ts b/examples/with-typescript-graphql/pages/api/graphql.ts new file mode 100644 index 000000000000..1ddbcc818ab6 --- /dev/null +++ b/examples/with-typescript-graphql/pages/api/graphql.ts @@ -0,0 +1,12 @@ +import { ApolloServer } from 'apollo-server-micro' +import schema from '../../lib/schema' + +const apolloServer = new ApolloServer({ schema }) + +export const config = { + api: { + bodyParser: false, + }, +} + +export default apolloServer.createHandler({ path: '/api/graphql' }) diff --git a/examples/with-typescript-graphql/pages/index.tsx b/examples/with-typescript-graphql/pages/index.tsx new file mode 100644 index 000000000000..de65953a143b --- /dev/null +++ b/examples/with-typescript-graphql/pages/index.tsx @@ -0,0 +1,24 @@ +import withApollo from '../lib/with-apollo' +import Link from 'next/link' +import { useViewerQuery } from '../lib/viewer.graphql' + +const Index = () => { + const { data } = useViewerQuery() + + if (data) { + const { viewer } = data + return ( +
+ You're signed in as {viewer.name} and you're {viewer.status} goto{' '} + + static + {' '} + page. +
+ ) + } + + return
...
+} + +export default withApollo(Index) diff --git a/examples/with-typescript-graphql/tsconfig.json b/examples/with-typescript-graphql/tsconfig.json new file mode 100644 index 000000000000..c65399cb28e5 --- /dev/null +++ b/examples/with-typescript-graphql/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "allowJs": true, + "alwaysStrict": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "isolatedModules": true, + "jsx": "preserve", + "lib": ["dom", "es2017"], + "module": "esnext", + "moduleResolution": "node", + "noEmit": true, + "noFallthroughCasesInSwitch": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "strict": true, + "target": "esnext" + }, + "exclude": ["node_modules"], + "include": ["**/*.ts", "**/*.tsx"] +}