ค้นหาเว็บไซต์

javascript - วิธีตรวจสอบผลรวมของ refs ใน Joi


ฉันจะตรวจสอบผลรวมของสอง refs ดังด้านล่างได้อย่างไร? ฉันต้องการให้ custom อยู่บน total แต่ไม่แน่ใจว่าจะดึงค่าของ refs ใน custom เมื่อใช้ Joi.ref ได้อย่างไร

ฉันสามารถทำสิ่งต่อไปนี้และแนบ custom ไปกับสคีมาการตรวจสอบทั้งหมดได้ แต่ฉันอยากแนบมันไปที่ total มากกว่า

ฉันไม่ต้องการใช้ expression()

ฉันไม่ค่อยอยากเปลี่ยนโครงสร้างของสเกมาตามคำตอบนี้

  const widgetValidator = Joi.object({
    a: Joi.number().integer().min(0).required(),
    b: Joi.number().integer().min(1).required(),
    total: Joi.number().integer().min(1).required(),
  }).custom((value: {a: number; b: number; total: number;}, helpers) => {
      if (value.total !== value.a + value.b) {
        throw new Error('invalid balance calculation');
      }

      return value;
    },
  );

คำตอบ #1

เมื่อคุณติดตั้ง custom บนแอตทริบิวต์ จะค่อนข้างยากในการดึงค่าของอ็อบเจ็กต์ทั้งหมด คุณต้องดึงค่าจาก states ของ helpers:

Joi.object({
    a: Joi.number().integer().min(0).required(),
    b: Joi.number().integer().min(1).required(),
    total: Joi.number().integer().min(1).required().custom((value, helpers) => {
      const { a, b } = helpers.state.ancestors[0];
      if (value !== a + b) {
        throw new Error('invalid balance calculation');
      }

      return value;
    },
  )
})