Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return array() in fluent-schema?

I have an object that looks like this:

interface LotteryData {
  PROP1: string;
  PROP2: string;
  PROP3: string;
  PROP4: string;
  PROP5: string;
}

interface LotterySuccess {
  name: string;
  data: Array<LotteryData>;
}

My schema is like this:

const successResponseSchema = S.object()
  .title('About 200 response')
  .description('Some description')
  .prop('name', S.string())
  .definition('data', S.array());

When using postman I get back the name but not the data.

I have also tried:

const successResponseSchema = S.object()
  .title('About 200 response')
  .description('Some description')
  .prop('name', S.string())
  .prop('data', S.anyOf([S.object()]));

Here data is null and I understand that since the data I am sending back in an array and not an object.

The handler that handles the request looks like this:

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 has the correct values but I am failing to align my success schema to responde with an array of objects. Any ideas?

like image 820
CodingLittle Avatar asked Aug 31 '26 09:08

CodingLittle


1 Answers

One of those seek for hours and once you finaly ask the question you also find an answer.

Want to keep this question since this isn't something easy to find. I figured this out by trial and error.

found this to be somewhat helpful.

My final solution:

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

To be honest I dont feel that this is an answer that covers everything. I can¨t explain why it has to be like this. If anyone can explain that part then great. I will hopefully be able to update this answer with more details in the future.

EDIT: @Manuel Spigolon gave some pointers in the comments.

Changed above to :

const successResponseSchema = S.object()
  .title('About 200 response')
  .description('Some description')
  .prop('name', S.string())
  .prop('data', S.array().items(S.object().additionalProperties(true)));

This way I did not have to add each prop.

like image 188
CodingLittle Avatar answered Sep 02 '26 14:09

CodingLittle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!