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

Enable contenteditable on table by pressing the tab key

I developed a table entry tool and I would like to be able to input items by pressing the tab key instead of having to manually click on each element. I haven't been able to figure out how to make this function work yet. $('table').on(&apos ...

I am looking to manage the error handling service, and my next step is to intentionally insert a single error into my service and have it automated

Need help with error handling in my service. I want to manually insert a single error, but would like it to be done automatically instead. 'use strict'; angular.module('nexoolApp.errorservice', ['nexoolApp.config']) .servic ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

bindings and validation of input values in angularjs

In my scenario, I am dealing with a dynamic regExp and unique masks for each input. For instance, the regExp is defined as [0-9]{9,9} and the corresponding mask is XXX-XX-XX-XX. However, when it comes to Angular's pattern validation, this setup is con ...

Error: There was a problem trying to import the `.d.ts` file

Software Stack Vue version 3.2.19 @vue/test-utils version 2.0.0-rc.15 Typescript version 4.1.6 Issue Description Encountering an error when running the command vue-cli-service test:unit --no-cache. Please refer to the TypeError screenshot (link to Con ...

How to Access Nested Arrays in ReactJS

As a ReactJS beginner, I've been making progress with my project. However, I've hit a roadblock that seems to be my final hurdle. Here's what I'm trying to achieve: TV Show - Simpsons Name: Bart Simpson, Gender: Male Name: Homer Simp ...

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Is Python being used to track NBA.com stats?

Does anyone have any advice on how to extract NBA.com "tracking" stats using a python script and display them in a simple table? I'm particularly struggling with this specific section of stats on the site. Accessing stats directly from NBA.com can be ...

Investigate the CSS display property of an element using JavaScript

Can JavaScript be used to determine if an element's CSS display == block or none? ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

Learning the process of configuring neo4j connection details without relying on environment variables

Is there a way to specify the database connection in code using the Drivine neo4j driver without relying on environment variables? ...

Is mocking all dependencies in an AngularJS controller necessary for unit testing?

Is it necessary to mock all the dependencies of my controller in order to test the scope? Here is a snippet of my code... .controller('SignupCtrl', ['$scope', 'vcRecaptchaService', '$http', '$location', & ...

Get the npm distribution package without the need to actually install npm

Is there a way to obtain an npm package without the need for running npm view XXX ... or installing node/npm? Specifically, I am attempting this process on a Linux operating system. ~UPDATE~ I now understand that I should have provided more details about ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

Storing information in an array and converting it to JSON using dual nested foreach loops in PHP

I need to retrieve data from two tables that have no relation. I am using a foreach loop to fetch all the data by a selected key and combine the data from both tables into an array. How can I store the data in an array while fetching data from two tables u ...

What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons <md-tab-group> <md-tab label="Tab 1">Content 1</md-tab> <md-tab label="Tab 2">Content 2</md-tab> </md-tab-group> <button md-button (click)="showTab1()">Show Tab 1< ...

What is the method for accessing 'this' beyond the scope of my object?

My Jcrop initialization for a website includes my own namespace. I have a question regarding the this keyword. Whenever I need to access my base object called "aps" in any callback function, I have to wrap this in a variable (I chose the word that). Is t ...

Extracting key-value pairs and unkeyed values from a JSON string during deserialization

Here is a JSON string that I attempted to deserialize, containing key-value pairs and values without keys: {"build":42606,"torrentc": "928729876"} "torrents:[["3C50FB27DB1469EFFD2F7BEAB9997D6425416380",136,"Westworld.S01E02.720p.HDTV.x265.ShAaNiG.mkv",31 ...

Finding the correct placement for importing 'reflect-metadata' in Next.js version 14.1.0

I am currently integrating tsyringe for dependency injection in my Next.js 14.1.0 application using the new App Router. However, I am facing an issue with its functionality when adding import 'reflect-metadata'; at the beginning of my Root Layout ...