0

I have five years experience in programming but I am very new to NodeJS and TypeScript.

According to their documentation, the normal way to use AJV for synchronous validation in TypeScript is to use the return of AJV#compile as both a function and an object.

import { AJV } from 'ajv';
// I am loading my schema from an adjacent file
import * as create_search_response from './create_search.schema.json';

const ajv = new AJV();
const validator = ajv.compile(create_search_response);

function throwUnlessObjectIsValid(obj: any) {
    if (!validator(obj)) {
        // assume at least one error
        throw validator.errors?.pop();
    }
}

My understanding is that we use the global value of validator.errors to store and retrieve the error info, similar to errno in C.

What if I perform validation in two threads simultaneously? Wouldn't the errors get mixed up? I have looked at their asynchronous validation system, and it would solve my problem with promise-based API, but I'm very confused about the details of keywords. It seems to require that I change the JSON schema itself.

What is the best practice here?

William Rosenbloom
  • 2,506
  • 1
  • 14
  • 37
  • Node is singlethreaded ...there are no "two threads simultaneously" ... Asynchronous validation is a possiblity, where certain properties of the object to be validated need to be checked for instance against a database – derpirscher Oct 24 '22 at 14:43
  • @derpirscher so a node server can only fulfill requests one at a time? That seems like a huge limitation. – William Rosenbloom Oct 24 '22 at 15:07
  • No of course not. Read for instance https://stackoverflow.com/questions/8982489/how-does-asynchronous-programming-work-in-a-single-threaded-programming-model or https://stackoverflow.com/questions/51007636/how-javascript-single-threaded-and-asynchronous to learn about how the node runtime handles this – derpirscher Oct 24 '22 at 19:44

0 Answers0