( params: Record<string, unknown>, schema: JsonSchemaType, )
| 9 | * @returns Cleaned parameters object with optional empty fields omitted |
| 10 | */ |
| 11 | export function cleanParams( |
| 12 | params: Record<string, unknown>, |
| 13 | schema: JsonSchemaType, |
| 14 | ): Record<string, unknown> { |
| 15 | const cleaned: Record<string, unknown> = {}; |
| 16 | const required = schema.required || []; |
| 17 | const properties = schema.properties || {}; |
| 18 | |
| 19 | for (const [key, value] of Object.entries(params)) { |
| 20 | const isFieldRequired = required.includes(key); |
| 21 | const fieldSchema = properties[key] as JsonSchemaType | undefined; |
| 22 | |
| 23 | // Check if the field has an explicit default value |
| 24 | const hasDefault = fieldSchema && "default" in fieldSchema; |
| 25 | const defaultValue = hasDefault ? fieldSchema.default : undefined; |
| 26 | |
| 27 | if (isFieldRequired) { |
| 28 | // Required fields: always include, even if empty string or falsy |
| 29 | cleaned[key] = value; |
| 30 | } else if (hasDefault && value === defaultValue) { |
| 31 | // Field has a default value and current value matches it - preserve it |
| 32 | // This is important for cases like default: null |
| 33 | cleaned[key] = value; |
| 34 | } else { |
| 35 | // Optional fields: only include if they have meaningful values |
| 36 | if (value !== undefined && value !== "" && value !== null) { |
| 37 | cleaned[key] = value; |
| 38 | } |
| 39 | // Empty strings, undefined, null for optional fields → omit completely |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | return cleaned; |
| 44 | } |
no outgoing calls
no test coverage detected