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
:
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:
-
The
sort
,order
,limit
andskip
values are extracted from the query string. This allows us to apply sorting and pagination to the results. -
A new instance of the
MovieService
is created with the Driver instance that you created in Adding the Driver passed to the constructor. -
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.
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.
Opensrc/services/movie.service.js
→
1. Open a new Session
Within the all()
method, first open a new session:
// 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:
-
The Cypher statement as a parameterised string.
-
An object containing the values for the parameters prefixed in the query with a dollar sign (
$
).
// 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.
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.
// 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.
// Close the session
await session.close()
5. Return the Results
Finally, update the return
statement to return the movies
list extracted above.
return movies
Working Solution
Click here to reveal the completed all()
method
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:
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:
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:
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.