简体   繁体   English

固定和ajv模式验证

[英]fastify and ajv schema validation

I am trying to validate the querystring parameter 'hccid' as shown below. 我正在尝试验证querystring参数“ hccid”,如下所示。 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 因此,使用该代码,当我使用总的新queryparam abc调用服务时,我应该得到一个模式验证异常,如下所示

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

but there was no error. 但没有错误。 I got the response back {"hello":"world"} 我收到了回复{"hello":"world"}

I also tried removing the queryparam all together http://localhost:3000/hello 我也尝试过一起删除queryparam http://localhost:3000/hello

and I still got {"hello":"world"} 而且我仍然得到{"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']
     }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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