Skip to content

02 Graph Database

JP Barbosa edited this page Apr 15, 2023 · 2 revisions

Graph Database

Start Local Neo4j With Docker

docker run \
    --env=NEO4J_AUTH=none \
    --env=NEO4J_apoc_export_file_enabled=true \
    --env=NEO4J_apoc_import_file_enabled=true \
    --env=NEO4J_apoc_import_file_use__neo4j__config=true \
    --env=NEO4J_PLUGINS=\[\"apoc\"\] \
    --publish=7474:7474 --publish=7687:7687 \
    --volume=$HOME/neo4j/data:/data \
    neo4j

Load Movies Data Into Neo4j

cypher-shell "CALL apoc.example.movies()"

Install Packages

npm install body-parser cors dotenv neo4j-driver
npm install --save-dev @types/cors

Shared Types

code ./packages/shared/src/types/Movie.ts
import { Node, Integer } from 'neo4j-driver';

export type Movie = {
  id?: number;
  title: string;
  released: number;
  tagline: string;
}

export type MovieNode = Node<Integer, Movie>;

export type MoviesQueryResult = {
  movie: Movie;
}
code ./packages/shared/src/types/index.ts
export * from './Movie';
code ./packages/shared/src/index.ts
export * from './types';

Graph

code ./packages/graph/src/movies/index.ts
import { Session } from 'neo4j-driver';
import { MoviesQueryResult } from '@neo4j-crud/shared';

export const movies = (session: Session) => ({
  getAll: async () => {
    const result = await session.run<MoviesQueryResult>(
      `
      MATCH (movie:Movie)
      RETURN movie {
        .*,
        id: id(movie)
      }
      ORDER BY movie.title
      `
    );

    const records = result.records.map((record) => record.get('movie'));

    return records;
  },
});
code ./packages/graph/src/index.ts
export * from './movies';

API

code ./packages/api/src/main.ts
import express from 'express';
import neo4j from 'neo4j-driver';
import { movies } from '@neo4j-crud/graph';

const app = express();
const port = process.env.PORT || 3333

app.get('/movies', async (req, res) => {
  const auth = neo4j.auth.basic('', '');
  const config = { disableLosslessIntegers: true };
  const session = neo4j.driver('bolt://localhost:7687', auth, config).session();
  const records = await movies(session).getAll();
  await session.close();
  res.send(records);
});

const server = app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`);
});

server.on('error', console.error);

Start

nx run-many --target=serve --all
open http://localhost:3333/movies
[
  {
    "tagline": "In the heart of the nation's capital, in a courthouse of the U.S. government...",
    "id": 198,
    "title": "A Few Good Men",
    "released": 1992,
  },
  ...
]

Commit

git add .
git commit -m "Graph Database"

Next step: API Structure