go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/chirp/pkg/controller/notifications.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package controller
     9  
    10  import (
    11  	"go.charczuk.com/sdk/apputil"
    12  	"go.charczuk.com/sdk/uuid"
    13  	"go.charczuk.com/sdk/web"
    14  
    15  	"go.charczuk.com/projects/chirp/pkg/config"
    16  	"go.charczuk.com/projects/chirp/pkg/model"
    17  )
    18  
    19  type Notifications struct {
    20  	apputil.BaseController
    21  
    22  	Config config.Config
    23  	Model  model.Manager
    24  }
    25  
    26  func (n Notifications) Register(app *web.App) {
    27  	app.Get("/notifications", web.NestMiddleware(n.notifications, web.SessionRequired))
    28  	app.Get("/notifications/:after", web.NestMiddleware(n.notificationsAfter, web.SessionRequired))
    29  }
    30  
    31  const DEFAULT_NOTIFICATIONS_FEED_LENGTH = 50
    32  
    33  func (n Notifications) notifications(r web.Context) web.Result {
    34  	userID := n.GetUserID(r)
    35  	notifs, err := n.Model.Notifications(r, userID, DEFAULT_NOTIFICATIONS_FEED_LENGTH, nil)
    36  	if err != nil {
    37  		return r.Views().InternalError(err)
    38  	}
    39  	var markRead []uuid.UUID
    40  	for _, n := range notifs {
    41  		if n.ReadUTC == nil {
    42  			markRead = append(markRead, n.ID)
    43  		}
    44  	}
    45  	if len(markRead) > 0 {
    46  		if err := n.Model.MarkNotificationsRead(r, userID, markRead); err != nil {
    47  			return r.Views().InternalError(err)
    48  		}
    49  	}
    50  	return r.Views().View("notifications", notifs)
    51  }
    52  
    53  func (n Notifications) notificationsAfter(r web.Context) web.Result {
    54  	userID := n.GetUserID(r)
    55  	after, err := web.RouteValue[uuid.UUID](r, "after")
    56  	if err != nil {
    57  		return r.Views().BadRequest(err)
    58  	}
    59  	notifs, err := n.Model.Notifications(r, userID, DEFAULT_NOTIFICATIONS_FEED_LENGTH, &after)
    60  	if err != nil {
    61  		return r.Views().InternalError(err)
    62  	}
    63  	return r.Views().View("notifications", notifs)
    64  }