Custom Result Handler Response Structures #2542
-
How can I customize the result handler so I enforce a certain structure for positive responses, basically I want to have message field on root level the same as success and data fields and then in data field we can append any fields that are provided within data object? Wanted output: {
"success": true,
"message": string, // a default fallback message if not provided
"data": {...} // any fields we return within data object or simply null if none
} Current output by the provided code: {
"success": true,
"data": {
"message": "No rate limit exceeded."
}
} export const customResultHandler = new ResultHandler({
positive: (data) => ({
schema: z.object({ data }),
mimeType: "application/json",
}),
negative: z.object({
success: z.boolean(),
error: z.object({
message: z.string(),
}),
}),
handler: ({ error, input, output, request, response, logger }) => {
if (error) {
const { statusCode } = ensureHttpError(error);
const message = getMessageFromError(error);
if (error instanceof InputValidationError) {
return void response.status(400).json({
success: false,
error: {
message: message,
},
});
}
return void response.status(statusCode).json({
success: false,
error: {
message: message,
},
});
}
response.status(200).json({ success: true, data: output });
},
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
You should add that Since if (data && "message" in data && typeof data.message === "string") {
// ...
} Schemas are used by Documentation and Integration generators, and they also enforce the constraints on |
Beta Was this translation helpful? Give feedback.
You should add that
message
property both intopositive
schema andhandler
implementation (where you do.json()
), @marcelmatkoSince
data
technically can be anything object-based, your implementation would need to ensure the presence of themessage
prop withindata
in order to pull it on top.Schemas are used by Documentation and Integration generators, and they also enforce the constraints on
.json()
within handler.