Búsqueda de sitios web

javascript - Cómo lanzar una excepción si la estructura de un objeto no coincide/encaja con otra


Leeré los objetos de entrada del usuario que deben estar bien formados.

Es decir, los objetos de entrada ahora podrían tener cualquier clave o subestructura que no esté definida en la interfaz.

¿Cómo podría lanzar una excepción si un usuario proporciona un objeto no válido?

Interfaz predefinida

  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
  }

Estructura de entrada válida

Esta estructura es un subconjunto bajo la InputStructureInterface definida

  {
    "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"
            },
          }
        ]
      }
    ]
  }

Estructura de entrada no válida

Porque viewTypeTHIS_IS_A_TYPO, nameTHIS_IS_A_TYPO no están presentes en la interfaz

{
  "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"
        }
      ]
    }
  ]
}

Respuesta #1

TypeScript solo hará cumplir los tipos en tiempo de compilación. Si quieres hacer este tipo de validaciones, necesitas usar algún tipo de biblioteca de validación de esquemas JSON. Como esta por ejemplo: https://github.com/epoberezkin/ajv

ACTUALIZACIÓN

Por ejemplo, usando esta biblioteca (https://github.com/epoberezkin/ajv) puedes hacer algo como esto:

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);
}

Para instalar la biblioteca: npm install ajv