Skip to content

04 Graph Structure

JP Barbosa edited this page Apr 15, 2023 · 1 revision

Graph Structure

Movies Queries

code ./packages/graph/src/movies/queries/getAll.ts
export const getAll = `
  WITH toLower($search) AS search
  MATCH (movie:Movie)
  WHERE
    search IS NULL
    OR search = ""
    OR toLower(movie.title) CONTAINS search
  RETURN movie {
    .*,
    id: id(movie)
  }
  ORDER BY movie.title
`;
code ./packages/graph/src/movies/queries/getById.ts
export const getById = `
  MATCH (movie:Movie)
  WHERE id(movie) = $id
  RETURN movie {
    .*,
    id: id(movie)
  }
`;
code ./packages/graph/src/movies/queries/create.ts
export const create = `
  CREATE (movie:Movie)
  SET
    movie.title = $movie.title,
    movie.released = $movie.released,
    movie.tagline = $movie.tagline

  RETURN movie {
    .*,
    id: id(movie)
  }
`;
code ./packages/graph/src/movies/queries/index.ts
export * from './getAll';
export * from './getById';
export * from './create';

Movies Graph

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

export const movies = (session: Session) => ({
  getAll: async (search = '') => {
    const result = await session.run<MoviesQueryResult>(queries.getAll, {
      search,
    });

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

    return records;
  },

  getById: async (id: number) => {
    const result = await session.run<MoviesQueryResult>(queries.getById, {
      id,
    });

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

    return records.pop();
  },

  create: async (movie: Movie) => {
    const result = await session.run<MoviesQueryResult>(queries.create, {
      movie,
    });

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

    return records.pop();
  },
});

Check if Get All Movies still works

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 Structure"

Next step: Graph Testing