github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/notifications/notifications.go (about)

     1  package notifications
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  
     7  	"github.com/cozy/cozy-stack/model/app"
     8  	"github.com/cozy/cozy-stack/model/notification"
     9  	"github.com/cozy/cozy-stack/model/notification/center"
    10  	"github.com/cozy/cozy-stack/pkg/consts"
    11  	"github.com/cozy/cozy-stack/pkg/couchdb"
    12  	"github.com/cozy/cozy-stack/pkg/jsonapi"
    13  	"github.com/cozy/cozy-stack/web/middlewares"
    14  	"github.com/labstack/echo/v4"
    15  )
    16  
    17  type apiNotif struct {
    18  	n *notification.Notification
    19  }
    20  
    21  func (n *apiNotif) ID() string                             { return n.n.ID() }
    22  func (n *apiNotif) Rev() string                            { return n.n.Rev() }
    23  func (n *apiNotif) DocType() string                        { return consts.Notifications }
    24  func (n *apiNotif) Clone() couchdb.Doc                     { return n }
    25  func (n *apiNotif) SetID(_ string)                         {}
    26  func (n *apiNotif) SetRev(_ string)                        {}
    27  func (n *apiNotif) Relationships() jsonapi.RelationshipMap { return nil }
    28  func (n *apiNotif) Included() []jsonapi.Object             { return nil }
    29  func (n *apiNotif) Links() *jsonapi.LinksList {
    30  	return &jsonapi.LinksList{Self: "/notifications/" + n.n.ID()}
    31  }
    32  
    33  func (n *apiNotif) MarshalJSON() ([]byte, error) {
    34  	return json.Marshal(n.n)
    35  }
    36  
    37  func createHandler(c echo.Context) error {
    38  	inst := middlewares.GetInstance(c)
    39  	n := &notification.Notification{}
    40  	if _, err := jsonapi.Bind(c.Request().Body, &n); err != nil {
    41  		return err
    42  	}
    43  	perm, err := middlewares.GetPermission(c)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	if err := center.Push(inst, perm, n); err != nil {
    48  		return wrapErrors(err)
    49  	}
    50  	return jsonapi.Data(c, http.StatusCreated, &apiNotif{n}, nil)
    51  }
    52  
    53  func wrapErrors(err error) error {
    54  	if err == nil {
    55  		return nil
    56  	}
    57  	switch err {
    58  	case center.ErrBadNotification:
    59  		return jsonapi.BadRequest(err)
    60  	case center.ErrUnauthorized:
    61  		return jsonapi.Forbidden(err)
    62  	case center.ErrNoCategory:
    63  		return jsonapi.Forbidden(err)
    64  	case center.ErrCategoryNotFound:
    65  		return jsonapi.Forbidden(err)
    66  	case app.ErrNotFound:
    67  		return jsonapi.NotFound(err)
    68  	}
    69  	return err
    70  }
    71  
    72  // Routes sets the routing for the notification service.
    73  func Routes(router *echo.Group) {
    74  	router.POST("", createHandler)
    75  }