首页 > 解决方案 > 如何在流利的模式中返回数组()?

问题描述

我有一个看起来像这样的对象:

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());

使用邮递员时,我会取回名称,但不会取回数据。

我也试过:

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 具有正确的值,但我未能将我的成功模式与对象数组对齐。有任何想法吗?

标签: javascriptfastify

解决方案


其中一个寻求数小时,一旦你最终提出问题,你也会找到答案。

想保留这个问题,因为这不容易找到。我通过反复试验发现了这一点。

发现有点帮助。

我的最终解决方案:

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)));

这样我就不必添加每个道具。


推荐阅读