|
| 1 | +import { AsyncController } from '../../types/auth.types'; |
| 2 | +import { sendSuccess, sendValidationError, sendNotFound } from '../../utils/api-response.utils'; |
| 3 | +import { prisma } from '../../utils/prisma.utils'; |
| 4 | +import { emitAuditEvent } from '../../utils/audit.utils'; |
| 5 | +import { z } from 'zod'; |
| 6 | + |
| 7 | +const UpdateCreatorMetadataSchema = z.object({ |
| 8 | + isVerified: z.boolean().optional(), |
| 9 | +}); |
| 10 | + |
| 11 | +type UpdateCreatorMetadataInput = z.infer<typeof UpdateCreatorMetadataSchema>; |
| 12 | + |
| 13 | +export const httpUpdateCreatorMetadata: AsyncController = async (req, res, next) => { |
| 14 | + try { |
| 15 | + const { id } = req.params as { id: string }; |
| 16 | + const adminIdHeader = req.headers['x-admin-id']; |
| 17 | + const actorId = |
| 18 | + typeof adminIdHeader === 'string' |
| 19 | + ? adminIdHeader |
| 20 | + : Array.isArray(adminIdHeader) |
| 21 | + ? adminIdHeader[0] |
| 22 | + : undefined; |
| 23 | + |
| 24 | + if (!id || !actorId) { |
| 25 | + return sendValidationError(res, 'Missing required parameters', [ |
| 26 | + { field: 'id', message: 'Creator ID is required' }, |
| 27 | + { field: 'x-admin-id', message: 'Admin ID header is required' }, |
| 28 | + ]); |
| 29 | + } |
| 30 | + |
| 31 | + const parsed = UpdateCreatorMetadataSchema.safeParse(req.body); |
| 32 | + if (!parsed.success) { |
| 33 | + return sendValidationError(res, 'Invalid request body', [ |
| 34 | + { field: 'body', message: 'Invalid metadata update' }, |
| 35 | + ]); |
| 36 | + } |
| 37 | + |
| 38 | + const updates = parsed.data as UpdateCreatorMetadataInput; |
| 39 | + |
| 40 | + const creator = await prisma.creatorProfile.findUnique({ |
| 41 | + where: { id }, |
| 42 | + }); |
| 43 | + |
| 44 | + if (!creator) { |
| 45 | + return sendNotFound(res, 'Creator'); |
| 46 | + } |
| 47 | + |
| 48 | + const previousValues = { |
| 49 | + isVerified: creator.isVerified, |
| 50 | + }; |
| 51 | + |
| 52 | + const updated = await prisma.creatorProfile.update({ |
| 53 | + where: { id }, |
| 54 | + data: updates, |
| 55 | + }); |
| 56 | + |
| 57 | + const changes: Record<string, unknown> = {}; |
| 58 | + Object.entries(updates).forEach(([key, value]) => { |
| 59 | + if (value !== previousValues[key as keyof typeof previousValues]) { |
| 60 | + changes[key] = { |
| 61 | + before: previousValues[key as keyof typeof previousValues], |
| 62 | + after: value, |
| 63 | + }; |
| 64 | + } |
| 65 | + }); |
| 66 | + |
| 67 | + if (Object.keys(changes).length > 0) { |
| 68 | + await emitAuditEvent({ |
| 69 | + actor: actorId, |
| 70 | + action: 'update_creator_metadata', |
| 71 | + target: 'CreatorProfile', |
| 72 | + targetId: id, |
| 73 | + metadata: changes, |
| 74 | + }); |
| 75 | + } |
| 76 | + |
| 77 | + sendSuccess(res, updated); |
| 78 | + } catch (error) { |
| 79 | + next(error); |
| 80 | + } |
| 81 | +}; |
0 commit comments