javascript - วิธีการโยนข้อยกเว้น หากโครงสร้างของวัตถุไม่ตรงกับ/ไม่เข้ากับอีกโครงสร้างหนึ่ง
ฉันจะอ่านวัตถุอินพุตของผู้ใช้ซึ่งควรอยู่ในรูปแบบที่ถูกต้อง
นั่นหมายความว่า วัตถุอินพุตตอนนี้อาจมีคีย์หรือโครงสร้างย่อยใด ๆ ก็ได้ที่ไม่ได้ถูกกำหนดในอินเทอร์เฟซ
ฉันจะสามารถโยนข้อยกเว้นได้อย่างไร หากผู้ใช้ให้วัตถุที่ไม่ถูกต้อง?
อินเทอร์เฟซที่กำหนดล่วงหน้า
export interface InputStructureInterface {
"tableName": string,
"viewType": string,
"structureName": string,
"sections": Array<Section>,
}
interface Section{
"name": string,
"fields": Array<Field>
}
interface Field{
"fieldName": string,
"relationType": string,
"relationName": null,
"fieldUi": FieldUi
}
interface FieldUi {
"fieldType": string,
"label": strin
}
โครงสร้างข้อมูลนำเข้าที่ถูกต้อง
โครงสร้างนี้เป็นส่วนหนึ่งภายใต้ InputStructureInterface ที่กำหนด
{
"tableName": "User",
"viewType": "List View",
"structureName": "personal_data_settings_list_view",
"sections": [
{
"name": null,
"fields": [
{
"fieldName": "Name",
"relationType": null,
"relationName": null,
"fieldUi": {
"fieldType": "string",
"label": "Name"
},
}
]
}
]
}
โครงสร้างข้อมูลนำเข้าผิดพลาด
เพราะว่า viewTypeTHIS_IS_A_TYPO, nameTHIS_IS_A_TYPO ไม่มีอยู่บนอินเทอร์เฟซ
{
"tableName": "User",
"viewTypeTHIS_IS_A_TYPO": "List View",
"structureName": "personal_data_settings_list_view",
"sections": [
{
"nameTHIS_IS_A_TYPO": null,
"fields": [
{
"fieldNameTHIS_IS_A_TYPO": "Name"
}
]
}
]
}
คำตอบ #1
TypeScript จะบังคับใช้ชนิดข้อมูลเฉพาะในเวลาคอมไพล์เท่านั้น หากคุณต้องการทำการตรวจสอบรูปแบบแบบนี้ คุณจำเป็นต้องใช้ไลบรารีตรวจสอบ json-schema บางประเภท เช่น ตัวอย่างนี้: https://github.com/epoberezkin/ajv
อัปเดต
ตัวอย่างเช่น การใช้ไลบรารีนี้ (https://github.com/epoberezkin/ajv) คุณสามารถทำบางอย่างแบบนี้ได้:
import * as Ajv from 'ajv';
const ajv = new Ajv();
const schema = {
"type": "object",
"properties": {
"tableName": { "type": "string" },
"viewType": { "type": "string" },
"structureName": { "type": "string" },
"sections": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"name": { "type": ["string", "null"] },
"fields": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"fieldName": { "type": "string" },
"relationType": { "type": ["string", "null"] },
"relationName": { "type": ["string", "null"] },
"fieldUi": {
"fieldType": { "type": "string" },
"label": { "type": "string" }
}
},
"required": ["fieldName", "relationType", "relationName"],
"additionalProperties": false
}
]
}
},
"required": ["name", "fields"],
"additionalProperties": false
}
]
}
},
"required": ["tableName", "viewType", "structureName"],
"additionalProperties": false
};
const validate = ajv.compile(schema);
let valid = validate(data); // <-- pass your json object here
if (!valid) {
console.log(validate.errors);
}
ในการติดตั้งไลบรารี: npm install ajv
