Source

controllers/link.controller.js

import { createLink, getLinksByInvestigationId, resolveAndIncrementVisit, toUrlResponseDto, } from "@services/url.service";
import { Types } from "mongoose";
/**
 * Link Controller
 * Handles link (URL) creation, listing, and public resolve for investigations
 * @category Controllers
 */
export class LinkController {
    /**
     * Resolve a link by key and subLink (public). Increments visit count and returns investigation id.
     * GET /api/link/:key/:subLink
     * @param {IResolveLinkRequest} req - Request object with key and subLink in params
     * @param {Response} res - Express response object
     * @returns {Promise<void>} Resolves when the response has been sent
     */
    static async resolveLink(req, res) {
        const { key, subLink } = req.params;
        const result = await resolveAndIncrementVisit(key, subLink);
        res.status(200).json({
            success: true,
            data: result,
        });
    }
    /**
     * Create a new link for an investigation.
     * POST /api/investigation/:id/links
     * @param {ICreateLinkRequest} req - Request object with investigation id in params and link data in body
     * @param {Response} res - Express response object
     * @returns {Promise<void>} Resolves when the response has been sent
     */
    static async createLink(req, res) {
        const investigationId = new Types.ObjectId(req.params.id);
        const userId = req.user?.userId && Types.ObjectId.isValid(req.user.userId)
            ? new Types.ObjectId(req.user.userId)
            : null;
        const created = await createLink(investigationId, {
            key: req.body.key,
            subLink: req.body.subLink,
            description: req.body.description,
        }, userId);
        res.status(201).json({
            success: true,
            message: "Link created successfully",
            data: toUrlResponseDto(created),
        });
    }
    /**
     * List all links for an investigation.
     * GET /api/investigation/:id/links
     * @param {IGetLinksRequest} req - Request object with investigation id in params
     * @param {Response} res - Express response object
     * @returns {Promise<void>} Resolves when the response has been sent
     */
    static async getLinks(req, res) {
        const investigationId = new Types.ObjectId(req.params.id);
        const links = await getLinksByInvestigationId(investigationId);
        res.status(200).json({
            success: true,
            data: links.map(toUrlResponseDto),
        });
    }
}