Skip to content

07 API CRUD

JP Barbosa edited this page Apr 20, 2023 · 3 revisions

API CRUD

Additional Operations

code ./packages/api/src/controllers/movies.ts
...

export const moviesController = {
  getAll: async (req, res: AppResponse<Movie[]>, next: NextFunction) => {
    try {
      const search = req.query.search as string;
      const movies = await graph.movies(req.neo4jSession).getAll(search);
      res.send(movies);
    } catch (err) {
      next(err);
    }
  },

  getById: async (req, res: AppResponse<Movie>, next: NextFunction) => {
    const id = parseInt(req.params.id);
    try {
      const movie = await graph.movies(req.neo4jSession).getById(id);
      if (!movie) {
        res.status(404).send({ error: 'Not Found' });
      }
      res.send(movie);
    } catch (err) {
      next(err);
    }
  },

  create: async (req, res: AppResponse<Movie>, next: NextFunction) => {
    try {
      const movie = await graph.movies(req.neo4jSession).create(req.body);
      res.send(movie);
    } catch (err) {
      next(err);
    }
  },

  update: async (req, res: AppResponse<Movie>, next: NextFunction) => {
    const id = parseInt(req.params.id);
    try {
      const movie = await graph.movies(req.neo4jSession).update(id, req.body);
      res.send(movie);
    } catch (err) {
      next(err);
    }
  },

  remove: async (req, res: AppResponse<Movie>, next: NextFunction) => {
    const id = parseInt(req.params.id);
    try {
      const movie = await graph.movies(req.neo4jSession).remove(id);
      res.send(movie);
    } catch (err) {
      next(err);
    }
  },
};

Test New Operations

open "http://localhost:3333/movies?search=Top%20Gun"
[
  {
    "tagline": "I feel the need, the need for speed.",
    "id": 1,
    "title": "Top Gun",
    "released": 1986,
  },
  ...
]

Postman

Create Search

Commit

git add .
git commit -m "API CRUD"

Next step: React Frontend