Unverified Commit 4bbdd090 authored by Nikolas Santis's avatar Nikolas Santis Committed by GitHub

[ EXAMPLES ] Added with-apollo-neo4j-graphql (#16560)

Adding a example with **Neo4j** native graph database.

- with-apollo-neo4j-graphql: basic apollo configuration with neo4j driver and neo4j-graphql-js.

:)
parent 2790ea41
import { useMemo } from 'react'
import { ApolloClient, InMemoryCache } from '@apollo/client'
import merge from 'deepmerge'
let apolloClient
......@@ -31,7 +32,14 @@ export function initializeApollo(initialState = null) {
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState)
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract()
// Merge the existing cache into data passed from getStaticProps/getServerSideProps
const data = merge(initialState, existingCache)
// Restore the cache with the merged data
_apolloClient.cache.restore(data)
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
......
......@@ -11,6 +11,7 @@
"@hapi/iron": "6.0.0",
"apollo-server-micro": "^2.14.2",
"cookie": "^0.4.1",
"deepmerge": "4.2.2",
"graphql": "^14.0.2",
"next": "latest",
"prop-types": "^15.6.2",
......
// Environment variables required to connect the app with your Neo4j database
NEO4J_URI=
NEO4J_USER=
NEO4J_PASSWORD=
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# 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.
## Deploy your own
Once you have access to [the environment variables you'll need](#step-3-set-up-environment-variables), deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?c=1&s=https://github.com/vercel/next.js/tree/canary/examples/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)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example with-apollo-neo4j-graphql with-apollo-neo4j-graphql-app
# or
yarn create next-app --example with-apollo-neo4j-graphql with-apollo-neo4j-graphql-app
```
## Configuration
### 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.
### Step 2. Add the movie graph model to the database
This example uses a database containing _Movies_, you can add it like so:
```bash
:play movie-graph
```
Also included is a Cypher [movie sample](./movie-sample.md) query if needed.
### Step 3. Set up environment variables
Next, copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):
```bash
cp .env.local.example .env.local
```
Then set each variable on `.env.local` to match your database uri and credentials.
## Deploy on Vercel
You can deploy this app to the cloud with [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
### Deploy Your Local Project
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/import/git?utm_source=github&utm_medium=readme&utm_campaign=next-example).
**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file.
### Deploy from Our Template
Alternatively, you can deploy using our template by clicking on the Deploy button below.
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?c=1&s=https://github.com/vercel/next.js/tree/canary/examples/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)
import { useMemo } from 'react'
import { ApolloClient, InMemoryCache } from '@apollo/client'
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({
uri: '/api/graphql',
credentials: 'same-origin',
})
}
}
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(),
cache: new InMemoryCache(),
})
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract()
// Merge the existing cache into data passed from getStaticProps/getServerSideProps
const data = merge(initialState, existingCache)
// Restore the cache with the merged data
_apolloClient.cache.restore(data)
}
if (typeof window === 'undefined') return _apolloClient
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}
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 { gql } from '@apollo/client'
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")
}
type Person {
name: String
born: Int
movies: [Movie] @relation(name: "ACTED_IN", direction: "OUT")
}
type Query {
getMovies: [Movie]
getMovie: Movie
getActor: Person
}
`
export default function Footer() {
return (
<footer>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by <img src="/vercel.svg" alt="Vercel Logo" className="logo" />
</a>
<style jsx>
{`
footer {
width: 100%;
height: 100px;
border-top: 1px solid #eaeaea;
display: flex;
justify-content: center;
align-items: center;
}
footer img {
margin-left: 0.5rem;
}
footer a {
display: flex;
justify-content: center;
align-items: center;
}
.logo {
height: 1em;
}
`}
</style>
</footer>
)
}
export default function Header({ title }) {
return (
<header>
<h1 className="title">
{title ? (
<span>{title}</span>
) : (
<span>
Welcome to <a href="https://nextjs.org">Next.js with Neo4j!</a>
</span>
)}
</h1>
<style jsx>{`
.title a {
color: #0070f3;
text-decoration: none;
}
.title a:hover,
.title a:focus,
.title a:active {
text-decoration: underline;
}
.title {
font-size: 3rem;
margin-bottom: 25px;
}
.title,
.description {
text-align: center;
}
`}</style>
</header>
)
}
This diff is collapsed.
{
"name": "with-apollo-neo4j-graphql",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build",
"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",
"next": "latest",
"react": "16.13.1",
"react-dom": "16.13.1"
},
"license": "MIT"
}
import { ApolloProvider } from '@apollo/client'
import { useApollo } from '../apollo/client'
import globalStyles from '../styles/global'
export default function MyApp({ Component, pageProps }) {
const apolloClient = useApollo(pageProps.initialApolloState)
return (
<ApolloProvider client={apolloClient}>
<Component {...pageProps} />
<style jsx global>
{globalStyles}
</style>
</ApolloProvider>
)
}
import Head from 'next/head'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { gql, useQuery } from '@apollo/client'
import Header from '../../components/header'
import Footer from '../../components/footer'
const GET_ACTOR = gql`
query GetActor($actorName: String) {
getActor(filter: { name: $actorName }) {
name
born
movies {
title
}
}
}
`
export default function Actor() {
const router = useRouter()
const { name } = router.query
const { loading, error, data } = useQuery(GET_ACTOR, {
actorName: name,
})
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
return (
<div className="container">
<Head>
<title>Next with Neo4j</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header title={name} />
<main>
<div className="actor">
<div className="info">
<h2>Information</h2>
<div>
<strong>Born: </strong>
{data.getActor.born}
</div>
</div>
<div className="movies">
<h2>Movies</h2>
{data.getActor.movies.map((movie) => (
<div key={movie.title}>
<Link
href="/movie/[title]"
as={{
pathname: `/movie/${encodeURIComponent(movie.title)}`,
}}
>
<a>{movie.title}</a>
</Link>
</div>
))}
</div>
</div>
<div className="back">
<Link href="/">
<a>🔙 Go Back</a>
</Link>
</div>
</main>
<Footer />
<style jsx>
{`
.container {
width: 100vw;
min-height: 100vh;
padding: 0 0.5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
main {
display: flex;
width: 100%;
justify-content: center;
padding: 2rem 0;
text-align: center;
flex-direction: column;
}
.actor {
margin-bottom: 2rem;
}
.movies div {
margin-bottom: 5px;
}
.movies a {
text-decoration: underline;
}
.back {
padding: 1rem 0;
}
.back a {
font-weight: bold;
}
`}
</style>
</div>
)
}
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 Head from 'next/head'
import Link from 'next/link'
import { gql, useQuery } from '@apollo/client'
import Header from '../components/header'
import Footer from '../components/footer'
const GET_MOVIES = gql`
query GetMovies {
getMovies {
title
tagline
released
actors {
name
}
directors {
name
}
}
}
`
export default function Home() {
const { loading, error, data } = useQuery(GET_MOVIES)
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
return (
<div className="container">
<Head>
<title>Next with Neo4j</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<main>
<div className="movies">
<div className="subtitle">
<p>
<strong>"Movies"</strong> Neo4j example dataset.
</p>
</div>
<table>
<thead>
<tr>
<th>#</th>
<th>Movie Title</th>
<th>Released</th>
<th>Tagline</th>
<th>Directed</th>
<th>Actors</th>
</tr>
</thead>
<tbody>
{data.getMovies.map((movie, index) => (
<tr className="movie" key={movie.title}>
<th>{index + 1}</th>
<td>
<Link
href="/movie/[title]"
as={{
pathname: `/movie/${encodeURIComponent(movie.title)}`,
}}
>
<a className="link">{movie.title}</a>
</Link>
</td>
<td>{movie.released}</td>
<td>{movie.tagline}</td>
<td>
<ul>
{movie.directors.map((director) => (
<li key={director.name}>{director.name}</li>
))}
</ul>
</td>
<td>
<ul>
{movie.actors.map((actor) => (
<li key={actor.name}>
<Link
href="/actor/[name]"
as={{
pathname: `/actor/${encodeURIComponent(
actor.name
)}`,
}}
>
<a className="link">{actor.name}</a>
</Link>
</li>
))}
</ul>
</td>
</tr>
))}
</tbody>
</table>
</div>
</main>
<Footer />
<style jsx>{`
.container {
width: 100vw;
min-height: 100vh;
padding: 0 0.5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
main {
display: flex;
width: 100%;
}
.subtitle {
margin-bottom: 25px;
text-align: center;
}
.movies {
flex: 1;
padding: 0 5rem;
}
table {
width: 100%;
border: 1px solid #dee2e6;
border-collapse: collapse;
border-spacing: 2px;
}
table thead th {
vertical-align: middle;
border-bottom: 2px solid #dee2e6;
border: 1px solid #dee2e6;
border-bottom-width: 2px;
padding: 0.75rem;
}
table tbody th,
table tbody td {
border: 1px solid #dee2e6;
padding: 0.75rem;
vertical-align: middle;
}
.link {
text-decoration: underline;
}
`}</style>
</div>
)
}
import Head from 'next/head'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { gql, useQuery } from '@apollo/client'
import Header from '../../components/header'
import Footer from '../../components/footer'
const GET_MOVIE = gql`
query GetMovie($movieTitle: String) {
getMovie(filter: { title: $movieTitle }) {
title
tagline
released
actors {
name
}
directors {
name
}
}
}
`
export default function Movie() {
const router = useRouter()
const { title } = router.query
const { loading, error, data } = useQuery(GET_MOVIE, {
movieTitle: title,
})
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
return (
<div className="container">
<Head>
<title>Next with Neo4j</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header title={title} />
<main>
<div className="movie">
<div className="info">
<h2>Information</h2>
<div>
<strong>Tagline: </strong>
{data.getMovie.tagline}
</div>
<div>
<strong>Released: </strong>
{data.getMovie.released}
</div>
</div>
<div className="actors">
<h2>Actors</h2>
{data.getMovie.actors.map((actor) => (
<div key={actor.name}>{actor.name}</div>
))}
</div>
<div className="directors">
<h2>Directors</h2>
{data.getMovie.directors.map((director) => (
<div key={director.name}>{director.name}</div>
))}
</div>
</div>
<div className="back">
<Link href="/">
<a>🔙 Go Back</a>
</Link>
</div>
</main>
<Footer />
<style jsx>
{`
.container {
width: 100vw;
min-height: 100vh;
padding: 0 0.5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
main {
display: flex;
width: 100%;
justify-content: center;
padding: 2rem 0;
text-align: center;
flex-direction: column;
}
.movie {
margin-bottom: 2rem;
}
.back {
padding: 1rem 0;
}
.back a {
font-weight: bold;
}
`}
</style>
</div>
)
}
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>
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;
}
`
import neo4j from 'neo4j-driver'
let driver
const defaultOptions = {
uri: process.env.NEO4J_URI,
username: process.env.NEO4J_USER,
password: process.env.NEO4J_PASSWORD,
}
export default function getDriver() {
const { uri, username, password } = defaultOptions
if (!driver) {
driver = neo4j.driver(uri, neo4j.auth.basic(username, password))
}
return driver
}
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