|
| 1 | +import { |
| 2 | + EXCEEDED_LIMIT_ORDER, |
| 3 | + ExceededLimit, |
| 4 | +} from '@epam/statgpt-dial-toolkit'; |
| 5 | + |
| 6 | +function uniqExceededLimits(limits: ExceededLimit[]): ExceededLimit[] { |
| 7 | + return [...new Set(limits)]; |
| 8 | +} |
| 9 | + |
| 10 | +function sortExceededLimits(limits: ExceededLimit[]): ExceededLimit[] { |
| 11 | + return [...limits].sort( |
| 12 | + (a, b) => EXCEEDED_LIMIT_ORDER.indexOf(a) - EXCEEDED_LIMIT_ORDER.indexOf(b), |
| 13 | + ); |
| 14 | +} |
| 15 | + |
| 16 | +function formatExceededLimitsList( |
| 17 | + limits: ExceededLimit[], |
| 18 | + t: (key: string, params?: Record<string, string>) => string, |
| 19 | +): string { |
| 20 | + const labels = sortExceededLimits(uniqExceededLimits(limits)).map((limit) => |
| 21 | + t(`statusMessages.rateLimit.limit.${limit}`), |
| 22 | + ); |
| 23 | + |
| 24 | + if (labels.length === 0) { |
| 25 | + return ''; |
| 26 | + } |
| 27 | + |
| 28 | + if (labels.length === 1) { |
| 29 | + return labels[0]; |
| 30 | + } |
| 31 | + |
| 32 | + if (labels.length === 2) { |
| 33 | + return t('statusMessages.rateLimit.list.two', { |
| 34 | + first: labels[0], |
| 35 | + second: labels[1], |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + return t('statusMessages.rateLimit.list.many', { |
| 40 | + items: labels.slice(0, -1).join(', '), |
| 41 | + last: labels[labels.length - 1], |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +export function getExceededLimitsMessage( |
| 46 | + limits: ExceededLimit[], |
| 47 | + t: (key: string, params?: Record<string, string>) => string, |
| 48 | +): string { |
| 49 | + const normalizedLimits = sortExceededLimits(uniqExceededLimits(limits)); |
| 50 | + const formattedLimits = formatExceededLimitsList(normalizedLimits, t); |
| 51 | + |
| 52 | + if (!formattedLimits) { |
| 53 | + return ''; |
| 54 | + } |
| 55 | + |
| 56 | + return t( |
| 57 | + normalizedLimits.length === 1 |
| 58 | + ? 'statusMessages.rateLimit.message.exceeded.one' |
| 59 | + : 'statusMessages.rateLimit.message.exceeded.many', |
| 60 | + { |
| 61 | + limits: formattedLimits, |
| 62 | + }, |
| 63 | + ); |
| 64 | +} |
0 commit comments