在nodejs中使用ajv验证和转换字段值

问题描述 投票:0回答:1

我想使用 ajv 验证和更改字段

json_data.childOrder.Order.triggerPrice
。但我的 customKeyword 函数从未被调用过。

我想更新到10%

json_data.ltp

我尝试阅读文档,但不太清楚如何执行此操作。 stackoverflow 上的抱怨示例指的是旧版本的

ajv
库。

const Ajv = require('ajv')
const ajv = new Ajv({ coerceTypes: true }) // options can be passed, e.g. {allErrors: true}

const OrderSchema = {
    type: 'object',
    properties: {
        childOrder: {
            type: 'object',
            additionalProperties: true,
            properties: {
                Order: {
                    type: 'object',

                    additionalProperties: true,

                    properties: {
                        qty: {
                            type: 'string'
                        },
                        triggerPrice: {
                            type: 'number'
                        }

                    },
                    required: ['triggerPrice', 'qty']

                }

            }
        }

    },
    additionalProperties: true

}

json_data = {
    childOrder: {
        Order: {
            buy: 'true',
            orderType: '3',
            price: 3999,
            qty: '10',
            triggerPrice: 3400
        }
    },
    duration: 'DAY',
    ltp: 3435,
    orderType: '3',
    price: 0,
    product: 'wood',
    qty: '10',
}

ajv.addKeyword({
    keyword: 'triggerPrice',
    type: 'number',
    compile: (a, b) => {
        // logic to transaform trigger price
        console.log(a, b)
    }
})
const validateOrder = ajv.compile(OrderSchema)

const _validate = validateOrder(json_data)

是否有其他替代方法可以在 NodeJS 中进行验证,就像 Python Marshmallow 和 django DRF 中那样。

javascript node.js validation serialization ajv
1个回答
0
投票

为了使自定义关键字验证起作用,您需要修改

compile
函数以返回数据验证函数,而不是实际运行验证逻辑:

ajv.addKeyword({
  keyword: "triggerPrice",
  type: "number",
  compile: (schema, parentSchema, it) => {
    const validate = (data, dataPath) => {
      // run your validation logic here and return true/false if data is valid
      return true;
    };
    return validate;
  },
});

此外,为了将关键字应用于

schema
中的属性,您需要使用自定义关键字“标记”此属性(具有相同的名称不会执行任何操作...):注意
 triggerPrice: true
已添加到架构对象中的triggerPrice属性

const OrderSchema = {
  type: "object",
  properties: {
    childOrder: {
      type: "object",
      additionalProperties: true,
      properties: {
        Order: {
          type: "object",
          additionalProperties: true,
          properties: {
            qty: {
              type: "string",
            },
            triggerPrice: {
              type: "number",
              triggerPrice: true, // add custom validation keyword
            },
          },
          required: ["triggerPrice", "qty"],
        },
      },
    },
  },
  additionalProperties: true,
};
© www.soinside.com 2019 - 2024. All rights reserved.