0

I just started learning fastify today, but there is something about the Schemas and their properties that doesnt work for me as expected!

The tutorial i follow showed me how to filter the send properties in the reply from the server :

const getItemsOpts = {
  schema: {
    response: {
      200: {
        type: "array",
        items: {
          type: "object",
          properties: {
            id: {type: "string"},
            //name: {type: "string"}
          }
        }
      }
    }
  }
}

function itemRoutes (fastify, options, done) {

  fastify.get("/items", getItemsOpts, (req, reply) => {
    reply.send(items)
  })
}

So there only the id would be send to the client obviously.

If i do this with a different set of small data, it somehow doesnt work though...

const animals = require("../animals")

const getAnimalsOpt = {
  schema: {
    response: {
      200: {
        type: "array",
        animals: {
          type: "object",
          properties: {
            name: {type: "string"}
          }
        }
      }
    }
  }
}

function animalRoutes(f, opt, d) {
  f.get("/animals", getAnimalsOpt, (req, res) => {
    const a = animals;
    res.send(a);
  })

  d()
}

module.exports = animalRoutes

The "data" for it comes from here :

let animals = [
  {name: "alexander", type: "dog", age: "7"},
  {name: "syrie", type: "cat", age: "6"},
  {name: "myra", type: "dog", age: "2"}
]

module.exports = animals

But i am just not able to filter out the properties being send out via the reply, like in the example from the tutorial! I literally tried to it EXACTLY like in said tutorial, but it doesnt work, and i dont know why...

If i do a more specific reply with a param and filter out a single object from the array, it works with the option schema, but not for all...

  • In your 200 response animals should read items. – Frazer Jul 15 '21 at 21:41
  • @Frazer Oh my... i somewhat assumed that i have to enter the collection there, since the tutorial used items... Thank you for helping me in solving this! :) –  Jul 15 '21 at 21:44

0 Answers0