Unverified Commit a5917317 authored by Nikolas Santis's avatar Nikolas Santis Committed by GitHub

[ EXAMPLES ] Added with-neo4j (#16559)

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

- with-neo4j: basic api routes with neo4j driver.

:)
parent 21e4c3f0
// 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
This is a simple set up for Next using Neo4j Database with api routes. 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-neo4j&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-neo4j%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-neo4j with-neo4j-app
# or
yarn create next-app --example with-neo4j with-neo4j-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-neo4j&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-neo4j%23step-3-set-up-environment-variables)
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>
)
}
export default async function fetcher(...args) {
const res = await fetch(...args)
return res.json()
}
This diff is collapsed.
{
"name": "with-neo4j",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"license": "MIT",
"dependencies": {
"neo4j-driver": "4.1.1",
"next": "latest",
"react": "16.13.1",
"react-dom": "16.13.1",
"swr": "0.3.9"
}
}
import globalStyles from '../styles/global'
export default function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<style jsx global>
{globalStyles}
</style>
</>
)
}
import Head from 'next/head'
import Link from 'next/link'
import { useRouter } from 'next/router'
import useSWR from 'swr'
import fetcher from '../../lib/fetcher'
import Header from '../../components/header'
import Footer from '../../components/footer'
export default function Actor() {
const router = useRouter()
const { name } = router.query
const { data, error } = useSWR(`/api/actors/${name}`, fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
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.actor.born.low}
</div>
</div>
<div className="movies">
<h2>Movies</h2>
{data.actor.movies.map((movie) => (
<div key={movie}>
<Link
href="/movie/[title]"
as={{
pathname: `/movie/${encodeURIComponent(movie)}`,
}}
>
<a>{movie}</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 getDriver from '../../../util/neo4j'
const driver = getDriver()
const session = driver.session()
export default async function handler(req, res) {
const {
query: { name },
method,
} = req
const actorName = decodeURIComponent(name)
switch (method) {
case 'GET':
try {
const actorTxResultPromise = session.readTransaction(
async (transaction) => {
const cypher = `
MATCH (actor:Person {name: $actorName})
MATCH (m:Movie)
WHERE (actor)-[:ACTED_IN]->(m)
RETURN actor {.*, movies: collect(m.title)} as actor
`
const actorTxResponse = await transaction.run(cypher, { actorName })
const [actor] = actorTxResponse.records.map((r) => r.get('actor'))
return actor
}
)
const actor = await actorTxResultPromise
res.status(200).json({ success: true, actor })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
import getDriver from '../../../util/neo4j'
const driver = getDriver()
const session = driver.session()
export default async function handler(req, res) {
const {
query: { title },
method,
} = req
const movieTitle = decodeURIComponent(title)
switch (method) {
case 'GET':
try {
const movieTxResultPromise = session.readTransaction(
async (transaction) => {
const cypher = `
MATCH (movie:Movie {title: $movieTitle})
MATCH (actor:Person)
WHERE (movie)<-[:ACTED_IN]-(actor)
MATCH (director:Person)
WHERE (movie)<-[:DIRECTED]-(director)
RETURN movie {.*, actors: collect(DISTINCT actor.name), directed: collect(DISTINCT director.name)} as movie
`
const movieTxResponse = await transaction.run(cypher, {
movieTitle,
})
const [movie] = movieTxResponse.records.map((r) => r.get('movie'))
return movie
}
)
const movie = await movieTxResultPromise
res.status(200).json({ success: true, movie })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
import getDriver from '../../../util/neo4j'
const driver = getDriver()
const session = driver.session()
export default async function handler(req, res) {
const { method } = req
switch (method) {
case 'GET':
try {
const moviesTxResultPromise = session.readTransaction(
async (transaction) => {
const cypher = `
MATCH (movie:Movie)
MATCH (actor:Person)
WHERE (movie)<-[:ACTED_IN]-(actor)
MATCH (director:Person)
WHERE (movie)<-[:DIRECTED]-(director)
RETURN movie {.*, actors: collect(DISTINCT actor.name), directed: collect(DISTINCT director.name)} as movie
`
const moviesTxResponse = await transaction.run(cypher)
const movies = moviesTxResponse.records.map((r) => r.get('movie'))
return movies
}
)
const movies = await moviesTxResultPromise
res.status(200).json({ success: true, movies })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
import Head from 'next/head'
import Link from 'next/link'
import useSWR from 'swr'
import fetcher from '../lib/fetcher'
import Header from '../components/header'
import Footer from '../components/footer'
export default function Home() {
const { data, error } = useSWR('/api/movies', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
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.movies.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.low}</td>
<td>{movie.tagline}</td>
<td>
<ul>
{movie.directed.map((director) => (
<li key={director}>{director}</li>
))}
</ul>
</td>
<td>
<ul>
{movie.actors.map((actor) => (
<li key={actor}>
<Link
href="/actor/[name]"
as={{
pathname: `/actor/${encodeURIComponent(actor)}`,
}}
>
<a className="link">{actor}</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 useSWR from 'swr'
import fetcher from '../../lib/fetcher'
import Header from '../../components/header'
import Footer from '../../components/footer'
export default function Movie() {
const router = useRouter()
const { title } = router.query
const { data, error } = useSWR(`/api/movies/${title}`, fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
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.movie.tagline}
</div>
<div>
<strong>Released: </strong>
{data.movie.released.low}
</div>
</div>
<div className="actors">
<h2>Actors</h2>
{data.movie.actors.map((actor) => (
<div key={actor}>{actor}</div>
))}
</div>
<div className="directors">
<h2>Directors</h2>
{data.movie.directed.map((director) => (
<div key={director}>{director}</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