2017-10-05 67 views
1

父PARAMS我如何能實現的東西像下面的邏輯查詢參數驗證:驗證子PARAMS依賴於與淳佳和哈皮

if (type is 'image') { 
    subtype is Joi.string().valid('png', 'jpg') 
else if (type is 'publication') { 
    subtype is Joi.string().valid('newspaper', 'book') 

得到任何

server/?type=image&subtype=png 

server/?type=publication&subtype=book 

但是不是imagepublication在同一時間嗎?

更新:我嘗試下面的代碼,但沒有運氣

type: Joi 
    .string() 
    .valid('image', 'publication', 'dataset') 
    .optional(), 
subtype: Joi 
    .when('type', 
     { 
      is: 'image', 
      then: Joi 
       .string() 
       .valid('png', 'jpg') 
       .optional() 
     }, 
     { 
      is: 'publication', 
      then: Joi 
       .string() 
       .valid('newspaper', 'book') 
       .optional() 
     } 
    ) 
     .optional() 
     .description('subtype based on the file_type') 

回答

2

你接近與使用.when()。與其試圖將所有排列組合在一個調用中,您可以將它們鏈接在一起,因爲該函數從通用的any結構下降。不幸的是,這些文件並沒有使這個特別清楚。

{ 
    type: Joi.string() 
      .valid('image', 'publication', 'dataset') 
      .optional(), 

    subtype: Joi.string() 
       .optional() 
       .when('type', {is: 'image',  then: Joi.valid('png', 'jpg')}) 
       .when('type', {is: 'publication', then: Joi.valid('newspaper', 'book')}) 
       .description('subtype based on the file_type') 
} 
+0

謝謝,那可以工作 – punkish