Design Pattern for Handling Different Notification Types in a TypeScript Frontend

  Kiến thức lập trình

I am currently working on an application with the following structure:

  • Backend: Ruby on Rails
  • Frontend: Next.js with TypeScript
  • Real-time notifications via WebSockets

The notifications are stored in a database and are retrieved with an API call when the app loads, followed by opening a WebSocket connection for real-time updates.

The Notification model in my database looks like this:

{
  "ID": 1,
  "User": "user_id",
  "notification_type": "like",
  "message": "Sample message",
  "read": false,
  "payload": {
    "user_infos": {"user_name": "JohnDoe", "user_id": "user_id"},
    "post_infos": {"post_id": "post_id"}
  },
  "sent_at": "timestamp"
}

The payload field is a JSON object that varies depending on the notification_type. For example:

For notification_type: ‘like’:

{
  "user_infos": {"user_name": "JohnDoe", "user_id": "user_id"},
  "post_infos": {"post_id": "post_id"}
}

For notification_type: ‘comment’:

{
  "user_infos": {"user_name": "JohnDoe", "user_id": "user_id"},
  "post_infos": {"post_id": "post_id"},
  "comment_info": {"comment_id": "comment_id", "comment": "Nice post!"}
}

Here is my question:

When I receive these notifications from the backend, I want to create specific Notification objects for each type. Each Notification object should have a display() method to format its message. For example:

  • For notification_type: ‘like’: “JohnDoe has liked your post.”
  • For notification_type: ‘comment’: “JohnDoe commented ‘Nice post!’ on
    your post.”

I am considering using the Factory Method design pattern to achieve this, but I am not a specialist in design patterns. I would appreciate any advice on whether this is a good approach or if another design pattern might be more suitable.

Thank you!

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT