2017-07-22 30 views
0

我有我嘗試驗證一個獨特數據中的對象:如何描述和驗證與CUID對象作爲鍵和值的數組作爲具有特殊性能的

{ 
      "name": "Some random name", 
      "blocks": [ 
       {"cj5458hyl0001zss42td3waww": { 
        "quantity": 9, 
        "rate": 356.77, 
        "dId": "ewdwe4434" 
       }}, 
       {"cj5458hyl0001zss42td3wawu": { 
        "quantity": 4, 
        "rate": 356.77, 
        "dId": "3434ewdwe4434" 
       }}] 
} 

這裏是我有該組合物現在(無效和不正確的):

const subSchema = { 
    "type": ["string"], 
    "pattern": "/^c[^\s-]{8,}$/", 
    "properties": { 
     "quantity": { 
      "type": "integer" 
     }, 
     "rate": { 
      "type": "integer" 
     }, 
     "dId": { 
      "type": "string" 
     } 
    }, 
    "required": ["quantity", "rate", "dId"] 
}; 

const schema = { 
    "type": ["object"], 
    "properties": { 
     "name": { 
      "type": "string" 
     }, 
     "blocks": { 
      "type": "array", 
      "items": subSchema, 
      "uniqueItems": true, 
      "minItems": 1 
     } 
    }, 
    "required": ["name", "blocks"] 
}; 

,以及如何我確認它(的情況下):

const { BadRequestError } = require("restify"); 
const ajv = require("ajv"); 
var schemaValidator = ajv(); 

const validateRoomTypePostRequest = (req, res, next) => { 

    if (req.body && req.body.data){ 
     const blockReq = Object.assign({}, req.body.data); 
     const testSchemaValidator = schemaValidator.compile(schema); 
     const valid = testSchemaValidator(blockReq); 
     if (!valid) { 
      const messages = testSchemaValidator.errors.map(e => { 
       return e.message; 
      }); 
      return next(new BadRequestError(JSON.stringify(messages))); 
     } 
     return next(); 
    } 
    else { 
     return next(new BadRequestError("Invalid or non-existent request body")); 
    } 
}; 

這是我迄今爲止所引用:

1)AJV schema validation for array of objects

2)https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md

3)https://spacetelescope.github.io/understanding-json-schema/reference/object.html

其他信息:

1)使用節點8.1.3

2)AJV版本5.2

我知道我需要使用項目的數組來描述對象。但是,該對象包含一個唯一的cuid作爲鍵和作爲對象的值。我想了解如何使用驗證嵌套屬性和cuid的模式來描述這些數據。我歡迎有關如何以最佳方式處理這些數據的反饋。感謝您的時間。

回答

0

我做了一些靈魂搜索,並意識到我所要做的只是利用patternProperties關鍵字,特定於字符串。

{ 
    "blockType": { 
     "additionalProperties": false, 
      "type": "object", 
       "properties": { 
        "name": { 
         "type": "string" 
        }, 
        "blocks": { 
         "type": "array", 
         "items": { 
         "type": "object", 
         "patternProperties": { 
          "^[a-z][a-z0-9\\-]*$": { 
           "type": ["object"], 
           "properties": { 
            "rate": { 
             "type": ["integer"] 
            }, 
            "quantity": { 
             "type": ["integer"] 
            }, 
            "dId": { 
             "type": "string" 
            } 
           }, 
          "additionalProperties": false, 
          "required": ["dId", "quantity", "rate"] 
         } 
        } 
       } 
      } 
     }, 
    "required": ["name", "blocks"] 
    } 
} 

我可以改進用於驗證cuid的正則表達式。

相關問題