2017-10-12 61 views
0

我正在使用Node的AJV(強制JSON模式)。JSON模式/ AJV數組項必須在另一個數組中

我想驗證array1 properties.bars。很簡單。

然後我想確保array2 properties.keep中的項目在array1 properties.bars中。

我該怎麼做?

我有:

const config = require('../../../config') 
const VALID_BARS = Object.keys(config.LHS_RHS_LOOKUP) 

const schemaItems = { 
    id: 'schemaItems', 
    type: 'string', 
    anyOf: [ 
    { enum: VALID_BARS }, 
    { pattern: '^[^\\s]+ [^\\s]+$' } 
    ] 
} 

const schemaOptions = { 
    type: 'object', 
    properties: { 
    bars: { 
     type: 'array', 
     default: [VALID_BARS[0]], 
     items: schemaItems, 
     minItems: 1, 
     uniqueItems: true 
    }, 
    keep: { 
     type: 'array', 
     default: [], 
     items: schemaItems, // << THIS NEEDS TO CHANGE 
     minItems: 0, 
     uniqueItems: true 
    }, 
    protect: { 
     default: true, 
     type: 'boolean' 
    } 
    } 
} 

module.exports = schemaOptions 

回答

1

你想使用$data pointer到第一陣列。現在它只是一個proposal。它允許您使用另一個屬性的數據值爲關鍵字分配值。

因此,在這種情況下,您的第二個數組的items屬性將具有將使用第一個數組的$ data值的enum屬性。

爲了做到這一點,我必須刪除原始模式中的'anyOf',以便第一個數組不會最終引用自己。我也通過$ ref和definition將schemaItems結合到主模式中。

這是a PLNKR它的行動。

測試代碼看起來是這樣的:

let schema = { 
    definitions: { 
    schemaItems: { 
     id: 'schemaItems', 
     type: 'string', 
     pattern: '^[^\\s]+ [^\\s]+$' 
    } 
    }, 
    type: 'object', 
    properties: { 
    bars: { 
     type: 'array', 
     items: { 
     $ref: "#/definitions/schemaItems" 
     }, 
     minItems: 1, 
     uniqueItems: true 
    }, 
    keep: { 
     type: 'array', 
     items: { 
     type: 'string', 
     enum: { 
      "$data": "/bars" 
     } 
     }, 
     minItems: 0, 
     uniqueItems: true 
    }, 
    protect: { 
     default: true, 
     type: 'boolean' 
    } 
    } 
}; 

和有效數據樣本是:

let data = { 
    bars: [ 
    "d d", 
    "b b" 
    ], 
    keep: [ 
    "d d" 
    ], 
    protect: true 
}; 
+0

感謝羅伊的努力和明確的解釋:) – danday74

相關問題