简体   繁体   中英

fastify and ajv schema validation

I am trying to validate the querystring parameter 'hccid' as shown below. Seems like the validation is not working for me. Can some one see what I am missing?

const fastify = require('fastify')({
  ajv: {
        removeAdditional: true,
        useDefaults:      true,
        coerceTypes:      true
    }
});


const schema = {
    querystring: {
       hccid: { type: 'string' }
    }
};

// Declare a route
 fastify.get('/hello', {schema}, function (request, reply) {
    const hccid = request.query.hccid;
    reply.send({ hello: 'world' })
});

// Run the server!
fastify.listen(3000, function (err) {
if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
});

So with that code, I should get a schema validation exception when I call the service with a total new queryparam abc just like I shown below

http://localhost:3000/hello?abc=1

but there was no error. I got the response back {"hello":"world"}

I also tried removing the queryparam all together http://localhost:3000/hello

and I still got {"hello":"world"}

so obviously the validation is not working. What is missing in my code? any help would be appreciated.

this schema structure solved my problem. Just in case if someone wants to check it out if they run into similar issue.

const querySchema = {
    schema: {
       querystring: {
         type: 'object',
           properties: {
             hccid: {
               type: 'string'
             }
         },
       required: ['hccid']
     }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM