Unverified Commit 4faf579c authored by Michael Webb's avatar Michael Webb Committed by GitHub

[EXAMPLES] Update with-apollo-neo4j-graphql (#44570)

We replace neo4j-graphql-js with @neo4j/graphql and update Apollo server to version 4.

This refactor also changes the code from Javascript to Typescript.



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm build && pnpm lint`
- [x] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent d070b026
# Neo4j Example with GraphQL and Apollo
This is a simple set up for Next using Neo4j Database with GraphQL and Apollo. Neo4j's Movies dataset example is used to run the example.
This is a simple setup for Next using Neo4j Database with GraphQL and Apollo. Neo4j's Movies dataset example is used to run the example.
## Deploy your own
......@@ -28,7 +28,7 @@ pnpm create next-app --example with-apollo-neo4j-graphql with-apollo-neo4j-graph
### Step 1. Create a Neo4j database
First, you'll need a Neo4j database. [Neo4j Desktop](https://neo4j.com/download/) and [Neo4j Online Sandbox](https://neo4j.com/sandbox/) are good and free to use options.
First, you'll need a Neo4j database. [Neo4j Desktop](https://neo4j.com/download/) and [Neo4j Online Sandbox](https://neo4j.com/sandbox/) are good and free-to-use options.
### Step 2. Add the movie graph model to the database
......@@ -48,7 +48,7 @@ Next, copy the `.env.local.example` file in this directory to `.env.local` (whic
cp .env.local.example .env.local
```
Then set each variable on `.env.local` to match your database uri and credentials.
Then set each variable on `.env.local` to match your database URI and credentials.
## Deploy on Vercel
......@@ -65,3 +65,7 @@ To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [
Alternatively, you can deploy using our template by clicking on the Deploy button below.
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-apollo-neo4j-graphql&project-name=with-apollo-neo4j-graphql&repository-name=with-apollo-neo4j-graphql&env=NEO4J_URI,NEO4J_USER,NEO4J_PASSWORD&envDescription=Required%20to%20connect%20the%20app%20with%20a%20Neo4j%20database&envLink=https://github.com/vercel/next.js/tree/canary/examples/with-apollo-neo4j-graphql%23step-3-set-up-environment-variables)
## Notes
To learn more about how to use the Neo4j GraphQL Library, you can [take a look at the documentation](https://neo4j.com/docs/graphql-manual/current/) or [check out the GitHub repository](https://github.com/neo4j/graphql/).
import { useMemo } from 'react'
import { ApolloClient, InMemoryCache } from '@apollo/client'
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'
import { SchemaLink } from '@apollo/client/link/schema'
import merge from 'deepmerge'
let apolloClient
function createIsomorphLink() {
if (typeof window === 'undefined') {
const { SchemaLink } = require('@apollo/client/link/schema')
const schema = require('./schema')
return new SchemaLink({ schema })
} else {
const { HttpLink } = require('@apollo/client/link/http')
return new HttpLink({
return createHttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
......
import { neo4jgraphql } from 'neo4j-graphql-js'
export default {
Query: {
getMovies: (parent, args, context, resolveInfo) => {
return neo4jgraphql(parent, args, context, resolveInfo)
},
getMovie: (parent, args, context, resolveInfo) => {
return neo4jgraphql(parent, args, context, resolveInfo)
},
getActor: (parent, args, context, resolveInfo) => {
return neo4jgraphql(parent, args, context, resolveInfo)
},
},
}
import { makeAugmentedSchema } from 'neo4j-graphql-js'
import typeDefs from './type-defs'
import resolvers from './resolvers'
export default makeAugmentedSchema({
typeDefs,
resolvers,
config: {
mutation: false,
},
})
import { Neo4jGraphQL } from '@neo4j/graphql'
import typeDefs from './type-defs'
import getDriver from '../util/neo4j'
const driver = getDriver()
export const neoSchema = new Neo4jGraphQL({
typeDefs,
driver,
})
......@@ -4,20 +4,14 @@ export default gql`
type Movie {
title: String
tagline: String
released: String
actors: [Person] @relation(name: "ACTED_IN", direction: "IN")
directors: [Person] @relation(name: "DIRECTED", direction: "IN")
released: Int
actors: [Person!]! @relationship(type: "ACTED_IN", direction: IN)
directors: [Person!]! @relationship(type: "DIRECTED", direction: IN)
}
type Person {
name: String
born: Int
movies: [Movie] @relation(name: "ACTED_IN", direction: "OUT")
}
type Query {
getMovies: [Movie]
getMovie: Movie
getActor: Person
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
}
`
export default function Header({ title }) {
export default function Header({ title }: { title?: string | string[] }) {
return (
<header>
<h1 className="title">
......
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
webpack: (config) => {
// this will override the experiments
config.experiments = { ...config.experiments, topLevelAwait: true }
// this will just update topLevelAwait property of config.experiments
// config.experiments.topLevelAwait = true
return config
},
}
module.exports = nextConfig
......@@ -6,12 +6,13 @@
"start": "next start"
},
"dependencies": {
"@apollo/client": "^3.2.7",
"apollo-server-micro": "^2.19.0",
"deepmerge": "4.2.2",
"graphql": "14.2.1",
"neo4j-driver": "^4.2.1",
"neo4j-graphql-js": "^2.17.1",
"@apollo/client": "^3.7.3",
"@apollo/server": "^4.3.0",
"@as-integrations/next": "^1.2.0",
"@neo4j/graphql": "^3.14.1",
"deepmerge": "^4.2.2",
"graphql": "^16.6.0",
"neo4j-driver": "^5.3.0",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
......
import '../styles/globals.css'
import { ApolloProvider } from '@apollo/client'
import { useApollo } from '../apollo/client'
import globalStyles from '../styles/global'
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }) {
export default function MyApp({ Component, pageProps }: AppProps) {
const apolloClient = useApollo(pageProps.initialApolloState)
return (
<ApolloProvider client={apolloClient}>
<Component {...pageProps} />
<style jsx global>
{globalStyles}
</style>
</ApolloProvider>
)
}
......@@ -4,10 +4,11 @@ import { useRouter } from 'next/router'
import { gql, useQuery } from '@apollo/client'
import Header from '../../components/header'
import Footer from '../../components/footer'
import { Actors } from '../../types'
const GET_ACTOR = gql`
query GetActor($actorName: String) {
getActor(filter: { name: $actorName }) {
people(where: { name: $actorName }) {
name
born
movies {
......@@ -20,8 +21,8 @@ const GET_ACTOR = gql`
export default function Actor() {
const router = useRouter()
const { name } = router.query
const { loading, error, data } = useQuery(GET_ACTOR, {
actorName: name,
const { loading, error, data } = useQuery<{ people: Actors }>(GET_ACTOR, {
variables: { actorName: name },
})
if (loading) return 'Loading...'
......@@ -42,12 +43,12 @@ export default function Actor() {
<h2>Information</h2>
<div>
<strong>Born: </strong>
{data.getActor.born}
{data.people[0].born}
</div>
</div>
<div className="movies">
<h2>Movies</h2>
{data.getActor.movies.map((movie) => (
{data.people[0].movies.map((movie) => (
<div key={movie.title}>
<Link
href="/movie/[title]"
......
import { ApolloServer } from 'apollo-server-micro'
import schema from '../../apollo/schema'
import getDriver from '../../util/neo4j'
const driver = getDriver()
const apolloServer = new ApolloServer({
schema,
introspection: true,
playground: true,
context: async (ctx) => {
return {
driver,
...ctx,
}
},
})
export const config = {
api: {
bodyParser: false,
},
}
export default apolloServer.createHandler({ path: '/api/graphql' })
import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { neoSchema } from '../../apollo/schema'
const server = async (): Promise<ApolloServer> => {
const schema = await neoSchema.getSchema()
return new ApolloServer({ schema })
}
export default startServerAndCreateNextHandler(await server())
......@@ -3,10 +3,11 @@ import Link from 'next/link'
import { gql, useQuery } from '@apollo/client'
import Header from '../components/header'
import Footer from '../components/footer'
import type { Movies } from '../types'
const GET_MOVIES = gql`
query GetMovies {
getMovies {
movies {
title
tagline
released
......@@ -21,7 +22,7 @@ const GET_MOVIES = gql`
`
export default function Home() {
const { loading, error, data } = useQuery(GET_MOVIES)
const { loading, error, data } = useQuery<{ movies: Movies }>(GET_MOVIES)
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
......@@ -53,7 +54,7 @@ export default function Home() {
</tr>
</thead>
<tbody>
{data.getMovies.map((movie, index) => (
{data.movies.map((movie, index) => (
<tr className="movie" key={movie.title}>
<th>{index + 1}</th>
<td>
......
......@@ -4,10 +4,11 @@ import { useRouter } from 'next/router'
import { gql, useQuery } from '@apollo/client'
import Header from '../../components/header'
import Footer from '../../components/footer'
import type { Movies } from '../../types'
const GET_MOVIE = gql`
query GetMovie($movieTitle: String) {
getMovie(filter: { title: $movieTitle }) {
movies(where: { title: $movieTitle }) {
title
tagline
released
......@@ -24,8 +25,8 @@ const GET_MOVIE = gql`
export default function Movie() {
const router = useRouter()
const { title } = router.query
const { loading, error, data } = useQuery(GET_MOVIE, {
movieTitle: title,
const { loading, error, data } = useQuery<{ movies: Movies }>(GET_MOVIE, {
variables: { movieTitle: title },
})
if (loading) return 'Loading...'
......@@ -46,22 +47,22 @@ export default function Movie() {
<h2>Information</h2>
<div>
<strong>Tagline: </strong>
{data.getMovie.tagline}
{data.movies[0].tagline}
</div>
<div>
<strong>Released: </strong>
{data.getMovie.released}
{data.movies[0].released}
</div>
</div>
<div className="actors">
<h2>Actors</h2>
{data.getMovie.actors.map((actor) => (
{data.movies[0].actors.map((actor) => (
<div key={actor.name}>{actor.name}</div>
))}
</div>
<div className="directors">
<h2>Directors</h2>
{data.getMovie.directors.map((director) => (
{data.movies[0].directors.map((director) => (
<div key={director.name}>{director.name}</div>
))}
</div>
......
import css from 'styled-jsx/css'
export default css.global`
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
* {
box-sizing: border-box;
}
a {
color: inherit;
text-decoration: none;
}
`
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
interface Person {
name: string
born: number
movies: Movies
}
interface Movie {
title: string
tagline: string
released: number
actors: Actors
directors: Directors
}
export type Movies = Partial<Movie>[]
export type Actors = Partial<Person>[]
export type Directors = Partial<Person>[]
import neo4j from 'neo4j-driver'
import type { Driver } from 'neo4j-driver'
let driver
let driver: Driver
const defaultOptions = {
uri: process.env.NEO4J_URI,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment