All files / postcardotp-backend/src/controllers notificationPreferenceController.js

23.33% Statements 7/30
0% Branches 0/6
0% Functions 0/3
23.33% Lines 7/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 641x 1x 1x     1x                             1x                                 1x                                         1x          
const notificationService = require("../services/notificationPreferences.service");
const { ApiError, handleErrors } = require("../utils/errorHandler");
const successResponse = require("../utils/successResponse");
 
// GET /api/notifications/:userId
const getUserPreferences = async (req, res, next) => {
  try {
    const userId = req.userId;
    const preferences =
      await notificationService.getAllPreferencesByUserId(userId);
    if (!preferences) {
      handleErrors(res, "No preferences found for this user", 404);
    }
    successResponse(res, preferences, "Data Fetch successfully", 201);
  } catch (err) {
    next(err);
  }
};
 
// PUT /api/notifications/:userId/:category
const updatePreference = async (req, res, next) => {
  try {
    const userId = req?.userId;
    const category = req?.params?.category;
    const { email_enabled, sms_enabled } = req.body;
    const updated = await notificationService.updatePreferenceByCategory(
      userId,
      category,
      { email_enabled, sms_enabled },
    );
    successResponse(res, updated, "Preference updated successfully", 201);
  } catch (err) {
    next(err);
  }
};
 
// POST /api/notifications/:userId/defaults
const createDefaults = async (req, res, next) => {
  try {
    const userId = req?.userId;
    if (!userId) {
      handleErrors(res, "User ID is required", 400);
    }
    const defaults = await notificationService.createDefaultPreferences(userId);
    if (!defaults) {
      throw new ApiError("Failed to create default preferences");
    }
    successResponse(
      res,
      defaults,
      "Default preferences created successfully",
      201,
    );
  } catch (err) {
    next(err);
  }
};
 
module.exports = {
  getUserPreferences,
  updatePreference,
  createDefaults,
};