首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fastify和ajv模式验证

fastify和ajv模式验证
EN

Stack Overflow用户
提问于 2017-12-23 16:45:24
回答 2查看 2.3K关注 0票数 1

我正在尝试验证querystring参数'hccid‘,如下所示。看来验证对我不起作用。有人能看到我错过了什么吗?

代码语言:javascript
复制
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}`)
});

因此,使用该代码,当我用一个完全新的queryparam abc调用服务时,我应该得到一个模式验证异常,如下所示

代码语言:javascript
复制
http://localhost:3000/hello?abc=1

但没有任何错误。我得到回复了,{"hello":"world"}

我还尝试将queryparam全部删除( http://localhost:3000/hello )

我还有{"hello":"world"}

所以很明显,验证是不起作用的。我的代码中遗漏了什么?任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-12-24 14:01:18

这个架构结构解决了我的问题。以防万一,如果有人想看看,如果他们遇到类似的问题。

代码语言:javascript
复制
const querySchema = {
    schema: {
       querystring: {
         type: 'object',
           properties: {
             hccid: {
               type: 'string'
             }
         },
       required: ['hccid']
     }
  }
}
票数 3
EN

Stack Overflow用户

发布于 2021-09-18 10:19:42

根据文档,可以使用querystringquery验证查询字符串,使用params验证路由参数。

伙伴关系将是:

  • /api/garage/:id,其中id是param可访问的request.params.id
  • /api/garage/:plate,其中platerequest.params.plate上可访问的param

param验证的示例如下:

代码语言:javascript
复制
const getItems = (req, reply) => {
  const { plate } = req.params;
  delete req.params.plate;
  reply.send(plate);
};

const getItemsOpts = {
  schema: {
    description: "Get information about a particular vehicle present in garage.",
    params: {
      type: "object",
      properties: {
        plate: {
          type: "string",
          pattern: "^[A-Za-z0-9]{7}$",
        },
      },
    },
    response: {
      200: {
        type: "array",
      },
    },
  },
  handler: getItems,
};

fastify.get("/garage/:plate", getItemsOpts);
done();

Query / Querystring将是:

  • /api/garage/id?color=white&size=small,其中colorsize是在request.query.colorrequest.query.size上可访问的两个查询字符串。

请参考上述答案作为查询验证的示例。

验证 路由验证在内部依赖于Ajv v6,它是一个高性能的JSON验证器。验证输入非常简单:只需在路由模式中添加所需的字段,您就完成了! 所支持的验证是:

  • body:验证请求的主体,如果它是POST、PUT或修补方法。
  • querystringquery:验证查询字符串。
  • params:验证路由参数。
  • headers:验证请求头。

1个Fastify验证:https://www.fastify.io/docs/latest/Validation-and-Serialization/#validation

2 Ajv@v6:https://www.npmjs.com/package/ajv/v/6.12.6

3 Fastify请求:https://www.fastify.io/docs/latest/Request/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47954210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档