[英]Efficiently validate nested JSON schema/config on front end
我在typescript
項目中有以下 JSON 配置。 我想在運行時在前端驗證這一點。 我正在尋找類似於node-convict
的解決方案。
我需要驗證
id
/ 無重復 ID。type
folder
他們應該有children
道具。 它可以是一個空數組。 我找到了AJV
。 AJV 文檔僅指整個對象是唯一的,而不是特定的屬性。 我可能會想出自己的方法並進行一些遞歸驗證。 但是,我正在尋找最有效的解決方案,無論是使用 ajv、另一個庫還是可以用來驗證這一點的有效數據結構。
如果使用外部庫,它需要與打字稿兼容。 我不是在尋找打字稿編譯時驗證。
[{
"type": "folder",
"name": "",
"id": 1, // UUID
"chldren": [{
"id": 11, // UUID
"type": "table", // TABLE TYPE
"name": "Some Table 1",
"meta": {},
"dataSource": "..........."
},
{
"type": "folder", // FOLDER TYPE
"name": "",
"id": 111, // UUID
"chldren": [{
"type": "folder",
"name": "",
"id": 1111, // UUID
"chldren": [{
"id": 11111, // UUID
"type": "table",
"name": "Some Another Table",
"meta": {},
"dataSource": "..........."
}]
}]
}
]
}]
我建議使用Joi數據驗證庫。 自 16 版以來,它已獲得 瀏覽器支持。
一個例子如下例如
import Joi from '@hapi/joi';
const schema = Joi.object({
type: Joi.string()
.alphanum()
.required(),
id: Joi.number()
.integer()
// I've not defined the whole schema for your object...
})
然后,您可以使用以下方法驗證您的對象:
schema.validate({ type: 'folder', id: 1 });
// -> { error: null, value: { type: 'folder', id: 1 }}
或者:
try {
const value = await schema.validateAsync({ type: 'folder', id: 1 });
}
catch (err) { }
你可以從這里獲取 Joi 的 TypeScript 類型。
可以在此處找到此工作的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.