|
| 1 | +import type { Request } from 'express' |
| 2 | + |
| 3 | +import { ConflictError } from '@crowd/common' |
| 4 | +import type { IMemberIdentity } from '@crowd/types' |
| 5 | + |
| 6 | +import { notifyOnce } from '@/api/public/alerts/notifyOnce' |
| 7 | +import { rethrowDbConflict } from '@/utils/err' |
| 8 | + |
| 9 | +type IdentityConflictSubject = Pick<IMemberIdentity, 'memberId' | 'platform' | 'value' | 'type'> |
| 10 | + |
| 11 | +function notifyIdentityConflict( |
| 12 | + req: Request, |
| 13 | + identity: IdentityConflictSubject, |
| 14 | + message: string, |
| 15 | +): void { |
| 16 | + const dedupeKey = [ |
| 17 | + 'member-identity-conflict', |
| 18 | + identity.platform, |
| 19 | + identity.type, |
| 20 | + identity.value, |
| 21 | + identity.memberId, |
| 22 | + ] |
| 23 | + .filter(Boolean) |
| 24 | + .join(':') |
| 25 | + |
| 26 | + void notifyOnce(req, dedupeKey, 'Identity conflict', [ |
| 27 | + { |
| 28 | + title: 'Identity', |
| 29 | + text: `*Platform:* \`${identity.platform}\`\n*Type:* \`${identity.type}\`\n*Value:* \`${identity.value}\``, |
| 30 | + }, |
| 31 | + ...(identity.memberId |
| 32 | + ? [{ title: 'Member', text: `*Member ID:* \`${identity.memberId}\`` }] |
| 33 | + : []), |
| 34 | + { title: 'Conflict', text: `*Message:* ${message}` }, |
| 35 | + { |
| 36 | + title: 'Request', |
| 37 | + text: `*Method:* \`${req.method}\`\n*URL:* \`${req.url}\``, |
| 38 | + }, |
| 39 | + ]) |
| 40 | +} |
| 41 | + |
| 42 | +/** Maps identity unique violations to ConflictError and alerts once. */ |
| 43 | +export function rethrowIdentityConflict( |
| 44 | + req: Request, |
| 45 | + error: unknown, |
| 46 | + identity: IdentityConflictSubject, |
| 47 | +): never { |
| 48 | + try { |
| 49 | + rethrowDbConflict(error, { |
| 50 | + platform: identity.platform, |
| 51 | + value: identity.value, |
| 52 | + type: identity.type, |
| 53 | + }) |
| 54 | + } catch (e) { |
| 55 | + if (e instanceof ConflictError) { |
| 56 | + notifyIdentityConflict(req, identity, e.message) |
| 57 | + } |
| 58 | + throw e |
| 59 | + } |
| 60 | +} |
0 commit comments