我有一个看起来像这样的对象:
interface LotteryData {
PROP1: string;
PROP2: string;
PROP3: string;
PROP4: string;
PROP5: string;
}
interface LotterySuccess {
name: string;
data: Array<LotteryData>;
}
我的模式是这样的:
const successResponseSchema = S.object()
.title('About 200 response')
.description('Some description')
.prop('name', S.string())
.definition('data', S.array());
当使用 postman 时,我得到的是名字而不是数据。
我也试过:
const successResponseSchema = S.object()
.title('About 200 response')
.description('Some description')
.prop('name', S.string())
.prop('data', S.anyOf([S.object()]));
这里的数据是空的,我明白这是因为我发回的数据是数组而不是对象。
处理请求的处理程序如下所示:
const handler = async (req, reply) => {
const responseData = await fileManager();
const response: LotterySuccess = {
name: responseData.Name,
data: responseData.Data,
};
reply.send(response);
};
export default (server: FastifyInstance) =>
server.get<null>('/', opts, handler);
responseData.Data 具有正确的值,但我无法使我的成功模式与 responde 保持一致 一组对象。有什么想法吗?
最佳答案
其中一个搜索了几个小时,一旦您最终提出问题,您也会找到答案。
想保留这个问题,因为这不容易找到。 我通过反复试验弄清楚了这一点。
找到 this有点帮助。
我的最终解决方案:
const successResponseSchema = S.object()
.title('About 200 response')
.description('Some description')
.prop('name', S.string())
.prop(
'data',
S.array().items(
S.object()
.prop('PROP1', S.string())
.prop('PROP2', S.string())
)
);
老实说,我不觉得这是一个包罗万象的答案。我无法解释为什么它必须是这样的。如果有人能解释那部分,那就太好了。我希望将来能够使用更多详细信息更新此答案。
编辑: @Manuel Spigolon 在评论中给出了一些指示。
上面改为:
const successResponseSchema = S.object()
.title('About 200 response')
.description('Some description')
.prop('name', S.string())
.prop('data', S.array().items(S.object().additionalProperties(true)));
这样我就不必添加每个 Prop 。
关于javascript - 如何以流畅的模式返回数组()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294320/