Topics are used to identify the most relevant tweets to show to the logged-in user. Each topic will contain a list of hashtags. A user can use these hashtags in his tweets. For example, we might have the “Web development” topic that will contain the following hashtags: “web”, “html”, “CSS”, “javascript”, “typescript” etc. These hashtags will be identified with the ‘pound’ symbol in front of them. For example, this might be the content of a tweet: “Hello #webdevelopers”
Let’s not forget to update the relationships on the User and Tweet entities:
Let’s add an endpoint that a user can use to add or remove topics based on their personal preferences:
Now, we can update UsersController to return all the topics of a user and also save them if necessary after we create the Topics model:
Before making a request to set a user’s topics, we need a few topics added in our database. Since we don’t have an admin dashboard we can use to add these topics (which will be the 3rd tutorial), we have to do it manually through the SQL client we are using. So, go ahead and add a few topics like “Music”, “Health”, “Programming” etc. Also, add a few hashtags to these topics. For example, add the “jazz” hashtag to the “Music” topic. We will use this later.
Let’s create a TopicsController together with a Topic model, so we can get a list of all the available topics on our social platform:
Let’s make a request to update a user’s topics where the value for the topics property is an array of topics ids:
In order to link a tweet with hashtags, we need to identify the hashtags in the tweet’s content using Regular expressions (Regexp for short). Let’s modify the TweetsController and add this feature:
Let’s create a tweet with some hashtags:
Now, that we’ve added the ability to set topics for users and hashtags for tweets, we can create a new endpoint that will return the latest tweets based on that:
This might look complex, but what is does is just selecting all the tweets from the platform that contain all the hashtags from the user’s topics. There is also room for query optimization here but let’s only optimize the code by extracting the duplicated code in a method:
Let’s make a request to test these endpoints:
Making a request to /explore should return us the tweet we created earlier with the #jazz hashtag.
Since we are here, lets also add an endpoint that will return all the tweets of a user based on a given username. We can use this to show all the tweets of a user when going to its profile:
Let’s also make here a request to test this endpoint: