Database Reference
In-Depth Information
To search for users to follow, the
UserController
uses the
searchbyusername
method, which calls the
searchByUserName
method in
UserImpl
. The
searchByUserName
method requests the
searchByUserName
method in the
UserRepository
, which is shown in the second part of Listing 11-30 and was also covered in more detail in Listing 11-17
of the “Spring Repositories” section. The
searchByUserName
method in
UserRepository
matches the current user and
then returns a
List
of users not already being followed by the current user and whose username matches on a wildcard
String value, which is created in the
searchByUserName
method in
UserImpl
.
Listing 11-30.
The
searchByUsername
Method in
UserImpl
// UserImpl
public List<User>
searchByUsername
(String currentusername, String username) throws Exception {
username = username.toLowerCase() + ".*";
LinkedList<User> users =
new LinkedList<User>(
userRepository.searchByUsername
(currentusername, username));
return users;
}
// UserRepository
@Query(" MATCH (n:User), (user { username:{c}}) " +
" WHERE (n.username =~ {u} AND n <> user) " +
" AND (NOT (user)-[:FOLLOWS]->(n)) " +
" RETURN n")
List<User>
searchByUsername
(@Param("c") String currentusername, @Param("u") String username);
The
searchByUsername
in
{PROJECTROOT}/WebContent/resources/js/graphstory.js
uses an AJAX request
and formats the response in
renderSearchByUsername
. If the list contains users, it will be displayed in the center of
the page under the search form, as shown in Figure
11-9
. Otherwise, the response will display “No Users Found”. The
display code for showing the list of users found can be reviewed by opening the
friends.html
file in
{PROJECTROOT}/
WebContent/mustache/html/graphs/social/
.
Once the search returns results, the next action would be to click on the “Add as Friend” link, which will call the
addfriend
method in
graphstory.js
. This will perform an AJAX request to the
follow
method in the
UserController
and call
follow
in
UserImpl
. The
follow
method in
UserImpl
, shown in Listing 11-31, will create the relationship
between the two users by first finding each entity via
getByUserName
and then use
createRelationshipBetween
provided by the
neo4jTemplate
.
Listing 11-31.
The
follow
Method in
UserImpl
// UserImpl
public void
follow
(String currentusername, String username) throws Exception {
User cu =
getByUserName
(currentusername);
User toFollow =
getByUserName
(username);
neo4jTemplate.
createRelationshipBetween
(neo4jTemplate.getNode(cu.getNodeId()),
neo4jTemplate.getNode(toFollow.getNodeId()), GraphStoryConstants.FOLLOWS, null);
}