@Summary Update user notification preferences @ID update-user-notification-preferences @Security CoderSessionToken @Accept json @Produce json @Tags Notifications @Param request body codersdk.UpdateUserNotificationPreferences true "Preferences" @Param user path string true "User ID, name, or me" @Suc
(rw http.ResponseWriter, r *http.Request)
| 278 | // @Success 200 {array} codersdk.NotificationPreference |
| 279 | // @Router /api/v2/users/{user}/notifications/preferences [put] |
| 280 | func (api *API) putUserNotificationPreferences(rw http.ResponseWriter, r *http.Request) { |
| 281 | var ( |
| 282 | ctx = r.Context() |
| 283 | user = httpmw.UserParam(r) |
| 284 | logger = api.Logger.Named("notifications.preferences").With(slog.F("user_id", user.ID)) |
| 285 | ) |
| 286 | |
| 287 | // Parse request. |
| 288 | var prefs codersdk.UpdateUserNotificationPreferences |
| 289 | if !httpapi.Read(ctx, rw, r, &prefs) { |
| 290 | return |
| 291 | } |
| 292 | |
| 293 | // Build query params. |
| 294 | input := database.UpdateUserNotificationPreferencesParams{ |
| 295 | UserID: user.ID, |
| 296 | NotificationTemplateIds: make([]uuid.UUID, 0, len(prefs.TemplateDisabledMap)), |
| 297 | Disableds: make([]bool, 0, len(prefs.TemplateDisabledMap)), |
| 298 | } |
| 299 | for tmplID, disabled := range prefs.TemplateDisabledMap { |
| 300 | id, err := uuid.Parse(tmplID) |
| 301 | if err != nil { |
| 302 | logger.Warn(ctx, "failed to parse notification template UUID", slog.F("input", tmplID), slog.Error(err)) |
| 303 | |
| 304 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 305 | Message: "Unable to parse notification template UUID.", |
| 306 | Detail: err.Error(), |
| 307 | }) |
| 308 | return |
| 309 | } |
| 310 | |
| 311 | input.NotificationTemplateIds = append(input.NotificationTemplateIds, id) |
| 312 | input.Disableds = append(input.Disableds, disabled) |
| 313 | } |
| 314 | |
| 315 | // Update preferences with params. |
| 316 | updated, err := api.Database.UpdateUserNotificationPreferences(ctx, input) |
| 317 | if err != nil { |
| 318 | logger.Error(ctx, "failed to update preferences", slog.Error(err)) |
| 319 | |
| 320 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 321 | Message: "Failed to update user notifications preferences.", |
| 322 | Detail: err.Error(), |
| 323 | }) |
| 324 | return |
| 325 | } |
| 326 | |
| 327 | // Preferences updated, now fetch all preferences belonging to this user. |
| 328 | logger.Info(ctx, "updated preferences", slog.F("count", updated)) |
| 329 | |
| 330 | userPrefs, err := api.Database.GetUserNotificationPreferences(ctx, user.ID) |
| 331 | if err != nil { |
| 332 | logger.Error(ctx, "failed to retrieve preferences", slog.Error(err)) |
| 333 | |
| 334 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 335 | Message: "Failed to retrieve user notifications preferences.", |
| 336 | Detail: err.Error(), |
| 337 | }) |
no test coverage detected