feat: add computeTTL and sanitizeValue utilities#252
Conversation
There was a problem hiding this comment.
🤖 PR Reviewer
Two utility functions added with reasonable documentation and logic. Minor issues exist: sanitizeValue may produce invalid UTF-8 output when truncating multibyte characters, and computeTTL silently returns negative values for past dates without any warning or validation.
📝 2 suggestion(s) - Please review inline comments below.
💡 How to re-trigger
Comment /review or /pr-reviewer on this PR
| const encoded = Buffer.from(value) | ||
| if (encoded.length <= maxBytes) return value | ||
| return encoded.slice(0, maxBytes).toString() | ||
| } |
There was a problem hiding this comment.
Buffer.from(value) defaults to UTF-8 encoding, but slicing at an arbitrary byte boundary can split a multibyte character, producing an invalid/garbled string. Use a TextDecoder or ensure truncation happens on a character boundary.
| } | |
| function sanitizeValue (value, maxBytes) { | |
| const encoded = Buffer.from(value, 'utf8') | |
| if (encoded.length <= maxBytes) return value | |
| // Truncate safely on a character boundary by decoding with replacement | |
| return new TextDecoder('utf-8', { fatal: false }).decode(encoded.slice(0, maxBytes)).replace(/\uFFFD$/, '') | |
| } |
| */ | ||
| function computeTTL (expiry) { | ||
| if (expiry === undefined || expiry === null) return undefined | ||
| if (expiry instanceof Date) { |
There was a problem hiding this comment.
computeTTL can return a negative TTL if the provided Date is in the past. Callers will likely get unexpected behavior (e.g., negative cache TTLs). Consider returning 0 or throwing an error for expired dates.
| if (expiry instanceof Date) { | |
| function computeTTL (expiry) { | |
| if (expiry === undefined || expiry === null) return undefined | |
| if (expiry instanceof Date) { | |
| const ttl = Math.floor((expiry.getTime() - Date.now()) / 1000) | |
| if (ttl < 0) throw new Error('expiry date is in the past') | |
| return ttl | |
| } | |
| if (typeof expiry !== 'number' || expiry < 0) throw new Error('expiry must be a non-negative number of seconds') | |
| return expiry | |
| } |
Description
Related Issue
Motivation and Context
How Has This Been Tested?
Screenshots (if appropriate):
Types of changes
Checklist: