UNPKG

@replyke/express

Version:

Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.

70 lines (69 loc) 2.71 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const models_1 = require("../../../../models"); const models_2 = require("../../../../models"); const createNotification_1 = __importDefault(require("../../../../helpers/createNotification")); // Create a follow relationship exports.default = async (req, res) => { const { userId: followedId } = req.params; const loggedInUserId = req.userId; const projectId = req.project.id; try { // Ensure followerId and followedId are not the same if (loggedInUserId === followedId) { res.status(400).json({ error: "A user cannot follow themselves.", code: "follow/self-follow", }); return; } // Check if the follower and followed users exist const follower = await models_1.User.findByPk(loggedInUserId); const followed = await models_1.User.findByPk(followedId); if (!follower || !followed) { res.status(404).json({ error: "One or both users involved in the follow do not exist.", code: "follow/user-not-found", }); return; } // Check if the follow relationship already exists const existingFollow = await models_2.Follow.findOne({ where: { projectId, followerId: loggedInUserId, followedId }, }); if (existingFollow) { res.status(409).json({ error: "Follow relationship already exists.", code: "follow/already-exists", }); return; } // Create the follow relationship await models_2.Follow.create({ projectId, followerId: loggedInUserId, followedId }); res.sendStatus(201); const followerJSON = follower.toJSON(); (0, createNotification_1.default)(req, res, { userId: followedId, // The recipient user ID, assumed here projectId, type: "new-follow", action: "open-profile", metadata: { initiatorId: followerJSON.id, initiatorName: followerJSON.name, initiatorUsername: followerJSON.username, initiatorAvatar: followerJSON.avatar, }, }); } catch (err) { console.error("Error creating follow:", err); res.status(500).json({ error: "Internal server error.", code: "follow/server-error", details: err.message, }); } };