The Home Page

Now for another challenge.

In this challenge, you will use the knowledge gained so far in this course to add new functionality to the API. You will modify the all() method of the MovieService to do the following:

Once you have completed the challenge, you will be asked to run a unit test to verify that the code has been correctly implemented. If the test runs correctly, the title of the highest rated movie will be logged. You will need this value to verify that the test has run correctly.

Exploring the Code

Before you start, let’s take a look at the code. If you are not interested in the code, you can skip straight to Challenge: Implementing Read Transactions.

If you start the application and access the app at http://localhost:3000, you will see two lists on the home page; one for Popular Movies and one for Latest Releases. Both of these lists are populated by a request to http://localhost:3000/api/movies with some additional parameters.

Route Handler

You can find the route handler, the function that handles the request, in src/routes/movies.routes.js:

js
src/routes/movies.routes.js
router.get('/', async (req, res, next) => {
  try {
    const { sort, order, limit, skip }
      = getPagination(req, MOVIE_SORT) // (1)

    const movieService = new MovieService(
      getDriver()
    ) // (2)

    const movies = await movieService.all(
      sort, order, limit, skip
    ) // (3)

    res.json(movies)
  }
  catch (e) {
    next(e)
  }
})

Within the route handler, you can see that:

  1. The sort, order, limit and skip values are extracted from the query string. This allows us to apply sorting and pagination to the results.

  2. A new instance of the MovieService is created with the Driver instance that you created in Adding the Driver passed to the constructor.

  3. The results are retrieved via the all() method and are returned by the handler as JSON.

The Movie Service

The magic happens in the MovieService, located at src/services/movies.service.js. For this route we are concerned with the all() method.

If we take a closer look at the all() method, we can see that it currently returns a hardcoded list of popular movies from another file in the repository.

js
src/services/movie.service.js
async all(sort = 'title', order = 'ASC', limit = 6, skip = 0, userId = undefined) {
  // TODO: Open an Session
  // TODO: Execute a query in a new Read Transaction
  // TODO: Get a list of Movies from the Result
  // TODO: Close the session

  return popular
}

You will need to replace these TODO comments with working code to complete the challenge.

Challenge: Implementing Read Transactions

As you learned in the Sessions and Transactions lesson, you will complete code to open a new session and run the query within a Read Transaction. Once the query has run, you add code to close the session. Then, finally you add code to extract and return the results.

Open src/services/movie.service.js

1. Open a new Session

Within the all() method, first open a new session:

js
// Open a new session
const session = this.driver.session()

2. Execute a Cypher statement within a new Read Transaction

This session provides an executeRead() method for which you pass a function to represent the unit of work.

The function will have one argument passed to it, a Transaction instance that you can use to execute a Cypher statement using the run() method. The run() method accepts two arguments:

  1. The Cypher statement as a parameterised string.

  2. An object containing the values for the parameters prefixed in the query with a dollar sign ($).

js
// Execute a query in a new Read Transaction
const res = await session.executeRead(
  tx => tx.run(
    `
      MATCH (m:Movie)
      WHERE m.\`${sort}\` IS NOT NULL
      RETURN m {
        .*
      } AS movie
      ORDER BY m.\`${sort}\` ${order}
      SKIP $skip
      LIMIT $limit
    `, { skip: int(skip), limit: int(limit) })
)

In the second argument, we use references to the int() function imported from neo4j-driver to convert the skip and limit values into a Neo4j integer. Remember to add the import statement to the top of the file.

js
import { int } from 'neo4j-driver'

3. Extract a list of Movies from the Result

Now that you have a complete result assigned to the res variable, you use the map() function on the res.records array to retrieve the movie value returned by the query.

js
// Get a list of Movies from the Result
const movies = res.records.map(
  row => toNativeTypes(row.get('movie'))
)

4. Close the Session

Before returning anything, make sure that the session is closed.

js
// Close the session
await session.close()

5. Return the Results

Finally, update the return statement to return the movies list extracted above.

js
return movies

Working Solution

Click here to reveal the completed all() method
js
src/services/movie.service.js
async all(sort = 'title', order = 'ASC', limit = 6, skip = 0, userId = undefined) {
  // Open an Session
  const session = this.driver.session()

  // Execute a query in a new Read Transaction
  const res = await session.executeRead(
    tx => tx.run(
      `
        MATCH (m:Movie)
        WHERE m.\`${sort}\` IS NOT NULL
        RETURN m {
          .*
        } AS movie
        ORDER BY m.\`${sort}\` ${order}
        SKIP $skip
        LIMIT $limit
      `, { skip: int(skip), limit: int(limit) })
  )

  // Get a list of Movies from the Result
  const movies = res.records.map(
    row => toNativeTypes(row.get('movie'))
  )

  // Close the session
  await session.close()

  return movies
}

Testing

To test that this functionality has been correctly implemented, run the following code in a new terminal session:

sh
Running the test
npm run test 02

The test file is located at test/challenges/02-movie-lists.spec.js.

Are you stuck? Click here for help

If you get stuck, you can see a working solution by checking out the 02-movie-lists branch by running:

sh
Check out the 02-movie-lists branch
git checkout 02-movie-lists

You may have to commit or stash your changes before checking out this branch. You can also click here to expand the Support pane.

Verifying the Test

Highest Rated Movie

The final test in the suite logs out the name of the highest rated movie according to the imdbRating property on each movie. Enter the title of the highest rated movie.

  • ✓ Band of Brothers

Hint

You can also find the answer by running the following Cypher statement:

cypher
MATCH (m:Movie)
WHERE m.imdbRating IS NOT NULL
RETURN m.title
ORDER BY m.imdbRating DESC LIMIT 1

Copy the answer without any quotes or whitespace.

Solution

The answer is Band of Brothers.

Lesson Summary

In this Challenge, you used your knowledge of sessions and transactions to retrieve a list of Movie nodes from the database.

In the next Challenge, you will write data to the database.

Chatbot

Hi, I am an Educational Learning Assistant for Intelligent Network Exploration. You can call me E.L.A.I.N.E.

How can I help you today?