Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | /** |
| 2 | * Function to transform the response from the API to the expected format |
| 3 | * This takes in the zod schema to be transformed into and the response from the API |
| 4 | * |
| 5 | * Users need to manually map the fields to the expected format |
| 6 | * |
| 7 | * @example |
| 8 | * ```ts |
| 9 | * transform(response) |
| 10 | * .with(ConnectedAccountRetrieveResponseSchema) |
| 11 | * .using((raw) => ({ ... })) |
| 12 | * ``` |
| 13 | */ |
| 14 | import { ZodTypeAny, z } from 'zod/v3'; |
| 15 | import logger from './logger'; |
| 16 | |
| 17 | export function transform<RawInput>(raw: RawInput) { |
| 18 | return { |
| 19 | with<Schema extends ZodTypeAny>(schema: Schema) { |
| 20 | return { |
| 21 | using( |
| 22 | transformer: (input: RawInput) => z.infer<Schema>, |
| 23 | options?: { label?: string } |
| 24 | ): z.infer<Schema> { |
| 25 | const transformed = transformer(raw); |
| 26 | const result = schema.safeParse(transformed); |
| 27 | |
| 28 | if (!result.success) { |
| 29 | const label = options?.label ? ` for ${options.label}` : ''; |
| 30 | const issues = result.error.issues |
| 31 | .map(issue => ` - ${issue.path.join('.') || 'parameter'}: ${issue.message}`) |
| 32 | .join('\n'); |
| 33 | logger.warn(`Transform validation failed${label}:\n${issues}`); |
| 34 | return transformed; |
| 35 | } |
| 36 | |
| 37 | return result.data; |
| 38 | }, |
| 39 | }; |
| 40 | }, |
| 41 | }; |
| 42 | } |