Wednesday, December 26, 2018

Write a general purpose Angular 2+ comments

As long as there is something in your website to show to users, there must be urgent of your users to comment on that something. This is always true for any content-providing website. After all, what's the good of a website if you can't dump any of your garbage opinions on its garbage content.


"Commenting on a post" is very essential of blogger or forum or any community website. At the very first of scratching a data structure we can trivially add a comment array to post, like:


It's very straightforward when we attach comments directly under post, and also simple enough, probably cost me less than one day to implement the inputs and view of comments.

But after that, you quickly realise that users do want to comment on everything they see, no matter how meaningless it could be.

I have no idea why I have to comment on this.

"Commenting on everything" sounds very attractive and fortunately, it's not hard at all, we can just isolate out the comment object to another collection(or table as in RDBM), and give comment a subject ID, which will represent the subject of any type which this comment belongs to. Something like this:
When we need to fetch all comments belongs to some post, or image, or video whatever, we can just query the comment collection(table) with subjectId == post.id.

Note: we use uuid for identifying every object, so a single subjectId is enough to represent the subject of a comment. If not uuid, you may need to store collection(table) name additionally in comment to get the target subject.

The rest of the work is an Angular 2+ component which integrates both showing a list of comments and a textarea for user to add new comments. Here is its implementation:




No comments:

Post a Comment