Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas.

For instance,

/schemas/banana-schema.json

{
  "$schema": "http://json-schema.org/draft-06/schema",
  "type": "object",
  "properties": {
    "banana_name": {
      "type": "string"
    },
    "id": {
      "type": "integer"
    },
    "banana_weight": {
      "type": "number"
    },
    "timestamp": {
      "type": "string",
      "format": "date-time"
    },
    "required": ["id"]
  }
}

/schemas/orange-schema.json

{
  "$schema": "http://json-schema.org/draft-06/schema",
  "type": "object",
  "properties": {
    "orange_name": {
      "type": "string"
    },
    "id": {
      "type": "integer"
    },
    "orange_sweetness": {
      "type": "number"
    },
    "orange_timestamp": {
      "type": "string",
      "format": "date-time"
    },
    "required": ["id"]
  }
}

Each schema has different attributes. My aim is to validate the following:

  1. All keys (e.g. banana_name, id, timestamp, orange_name, orange_sweetness, and so on) across all schemas adhere to the same naming convention (lowercase with an underscore: 'xxx' or 'xxx_yyy').

  2. Any key containing the word 'timestamp' must be in 'date-time' format.

  3. Every schema must include the 'id' key. ('id' is mandatory for all schemas)

Is it feasible to create a unit test that imports all JSON schemas and performs these validations?

Answer №1

To ensure schema validation during runtime, it is essential to utilize a JSON Schema Validator like Ajv instead of relying solely on TypeScript features.

If you wish to code under a type-safe environment, consider creating type definitions for the fruits schema.

While TypeScript offers static type checking at compile-time, it does not provide runtime type checking capabilities.


Considering your specific requirements:

  1. Enforcing naming conventions

This can be achieved using regular expressions.

  1. Ensuring existence of key 'id' in any schema

Here are some advantages that TypeScript brings:

interface Schema {
  id: number;
}

interface AppleSchema extends Schema {
  apple_name: string,
  apple_weight: number,
  // additional properties...
}

interface MongoSchema extends Schema {
  mango_name: string,
  mango_mature: number,
  // additional properties...
}

// leveraging the benefits of TypeScript
export function testApple(apple: AppleSchema) {
  console.log(apple.id); // accessing apple.id, apple.apple_name, apple.apple_weight ...
}

// and more
export function findFruit<T extends Schema>(fruits: T[], id: number) {
    return fruits.find(fruit => fruit.id === id)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing Properties in React.js: A Guide

<Element id="1" onClick={this.runFunction(???)}/> When the onClick event is triggered, I want to execute a different function with the key value "1" as an argument. How can I make this happen? Thank you. ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

Encountering NotFoundHttpException with Jquery Ajax in Laravel 4

Hello everyone! I'm diving into the world of ajax and currently experimenting with sending form input to a controller through a route and then displaying it in a div. Unfortunately, I've hit a roadblock as I keep getting a NotFoundHttpException ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

Attempting to populate the database with information from a JSON array

My code is designed to work in the following way: An HTTP post request (in an AsyncTask class) is sent to a MySQL database using PHP to retrieve JSON encoded data. The JSON encoded data from each row is fetched one by one in the dbCodeHelper class, which ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Having trouble testing Material-ui Modal using react-test-renderer

While attempting to create a basic test using the Jest library for the Modal component, I encountered the following issue: import { Modal } from '@material-ui/core'; import React from 'react'; import TestRenderer from 'react-test- ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

Checking the parameters passed to a function in Typescript: A step-by-step guide

Currently, I am working with Typescript and then transpiling my TS code into JavaScript. However, I have encountered an issue that I am struggling to resolve. The error message I am facing is as follows: Error Found in TypeScript on Line:2 - error TS230 ...

How can you effectively blend Vue/Angular with other JavaScript resources to enhance your development process?

My curiosity lies in understanding how front-end javascript libraries such as Vue and Angular can seamlessly integrate with other libraries and assets. For instance, if I were to procure a website template already equipped with additional javascript, is it ...

Sometimes jQuery may require multiple executions with just one click

Content of index.php <script type="text/javascript" src="//<?php echo $_SERVER["SERVER_NAME"];?>/javascript/jquery-1.10.2.min.js" ></script> <script type="text/javascript"> $(document).ready(function() { $( document ).on( 'c ...

Can the parameters in a .slice() be customized within a v-for loop?

I am currently working with Laravel 8 and using blade syntax. The following code snippet is from a Vue component I created: <li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" v-if="comic.item_type === 'b&ap ...

Navigating with ASP.NET 5 Routing and AngularJS Routing

Currently, I am working on an ASP.NET 5 application which also utilizes AngularJS for the front-end. The basic client-side HTML routing support offered by Angular has been successfully implemented in my project. In the Startup class, the default routing is ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

Ways to determine the generic type of a property value from a decorated property within a decorator

While experimenting with some code, I encountered an issue where the generic type of a property value wasn't being resolved correctly when changing from TValue to (t: TValue) => TValue. Instead of being recognized as the expected number, it was now ...

Setting a variable in Angular after a successful AJAX call

Working on a new small application and experimenting with Angular. Encountering an issue where I am making an AJAX GET request upon clicking a button. After receiving the response, I want to set a variable to hold the result, but for some reason the variab ...

What are the steps for designing personalized syncfusion grid-columns while still preserving the built-in search functionality of syncfusion?

Looking to transform the data coming from the backend, specifically mapping a user's status which is represented as a number to its corresponding string value. Considered using typescript for this mapping task, but it interferes with syncfusion' ...

Generating a JSON object on the fly in a React Native application

There have been similar questions asked in the past like this & this. After looking at those SO questions, I came up with this code. As a newcomer to React Native and Javascript, I am facing two issues. 1. I'm trying to structure my data like this ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...