Files
scouthub/scouthub-home-be/src/controllers/membri.controller.ts
T
2026-07-25 12:09:12 +02:00

67 lines
2.1 KiB
TypeScript

import { Request, Response, NextFunction } from 'express';
import { listaMembri, cambiaRuoloMembro, rimuoviMembro, aggiungiMembro } from '../services/membri.service';
import { HttpError } from '../errors';
interface PostMembroBody {
email?: unknown;
ruolo?: unknown;
}
function parseAggiungiMembroBody(body: PostMembroBody): { email: string; ruolo: string } {
if (typeof body.email !== 'string' || body.email.trim().length === 0) {
throw new HttpError(400, "Il campo 'email' è obbligatorio ed è una stringa non vuota");
}
if (typeof body.ruolo !== 'string' || body.ruolo.trim().length === 0) {
throw new HttpError(400, "Il campo 'ruolo' è obbligatorio ed è una stringa non vuota");
}
return { email: body.email, ruolo: body.ruolo };
}
export async function postMembro(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const { orgId } = req.params;
const { email, ruolo } = parseAggiungiMembroBody(req.body ?? {});
const result = await aggiungiMembro({ orgId, email, ruolo });
res.status(201).json(result);
} catch (err) {
next(err);
}
}
export async function getMembri(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const { orgId } = req.params;
const membri = await listaMembri(orgId);
res.json(membri);
} catch (err) {
next(err);
}
}
export async function putRuoloMembro(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const { orgId, userId } = req.params;
const { ruolo } = req.body ?? {};
if (typeof ruolo !== 'string' || ruolo.trim().length === 0) {
throw new HttpError(400, "Il campo 'ruolo' è obbligatorio ed è una stringa non vuota");
}
await cambiaRuoloMembro(orgId, userId, ruolo);
res.status(200).json({ userId, ruolo });
} catch (err) {
next(err);
}
}
export async function deleteMembro(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const { orgId, userId } = req.params;
await rimuoviMembro(orgId, userId);
res.status(204).send();
} catch (err) {
next(err);
}
}