Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation:

{
            "name": "Some unique name",
            "blocks": [
                {"cj5458hyl0001zss42td3waww": {
                    "quantity": 9,
                    "rate": 356.77,
                    "dId": "ewdwe4434"
                }},
                {"cj5458hyl0001zss42td3wawu": {
                    "quantity": 4,
                    "rate": 356.77,
                    "dId": "3434ewdwe4434"
                }}]
}

My current structure (invalid and incorrect):

const subSchema = {
    "type": ["string"],
    "pattern": "/^c[^\s-]{8,}$/",
    "properties": {
        "quantity": {
            "type": "integer"
        },
        "rate": {
            "type": "integer"
        },
        "dId": {
            "type": "string"
        }
    },
    "required": ["quantity", "rate", "dId"]
};

const schema = {
    "type": ["object"],
    "properties": {
        "name": {
            "type": "string"
        },
        "blocks": {
            "type": "array",
            "items": subSchema,
            "uniqueItems": true,
            "minItems": 1
        }
    },
    "required": ["name", "blocks"]
};

Validation process (for context):

const { BadRequestError } = require("restify");
const ajv = require("ajv");
var schemaValidator = ajv();

const validateRoomTypePostRequest = (req, res, next) => {

    if (req.body && req.body.data){
        const blockReq = Object.assign({}, req.body.data);
        const testSchemaValidator = schemaValidator.compile(schema);
        const valid = testSchemaValidator(blockReq);
        if (!valid) {
            const messages = testSchemaValidator.errors.map(e => {
                return e.message;
            });
            return next(new BadRequestError(JSON.stringify(messages)));
        }
        return next();
    }
    else {
        return next(new BadRequestError("Invalid or non-existent request body"));
    }
};

References used:

1) AJV schema validation for array of objects

2) https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md

3)

Additional details:

1) Operating on Node 8.1.3

2) Using AJV version 5.2

I realize I need to employ an array of items to define the object. However, my object comprises a distinct cuid as a key and an object as its value. Any advice on accurately describing this dataset using a schema that validates both the nested properties and the cuid will be appreciated. Thank you for your time.

Answer №1

After some introspection, I came to the realization that by utilizing the patternPropertieskeyword specifically for strings, I was able to make significant progress.

{
    "blockType": {
        "additionalProperties": false,
            "type": "object",
                "properties": {
                    "name": {
                         "type": "string"
                    },
                    "blocks": {
                        "type": "array",
                        "items": {
                        "type": "object",
                        "patternProperties": {
                            "^[a-z][a-z0-9\\-]*$": {
                                "type": ["object"],
                                "properties": {
                                    "rate": {
                                        "type": ["integer"]
                                    },
                                    "quantity": {
                                        "type": ["integer"]
                                    },
                                    "dId": {
                                        "type": "string"
                                    }
                                },
                            "additionalProperties": false,
                            "required": ["dId", "quantity", "rate"]
                        }
                    }
                }
            }
        },
    "required": ["name", "blocks"]
    }
}

I realized there is room for enhancement in the regex used for cuid validation.

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

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

Creating an interactive map on an image using HTML and drawing circles

I've been experimenting with drawing circles on images using the map property in HTML. I have an image set up, and when clicking on the image in JavaScript, I'm adding the area coordinates for the map property. However, I keep encountering a null ...

Issue with Vuex: currentUser state not persisting after page refresh

I'm currently working on a Vue.js SPA that utilizes Rails 6 API as the backend and Vue-cli (legacy webpack template). After signing in a user, everything seems to be functioning correctly. I can view the user details, it updates my setCurrentUser mut ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

Trying out a React component that relies on parameters for connection

Having an issue while attempting to test a connected react component that requires a props.params.id in order to call action creators. During the testing process, when checking if the component is connected to the store, an error "Uncaught TypeError: Canno ...

Using JSON in Node.js

After recently diving into Node, I've been working on parsing JSON data from an API. While I have managed to access most of the JSON content, there are certain elements that seem to elude me. var request = require("request"); var url = 'https: ...

Is there a way to verify the custom form when the braintree PayPal checkout button is clicked?

I am seeking a solution to validate a custom PHP form when the Braintree PayPal checkout button is clicked. Currently, the form redirects to the PayPal screen if it is not properly filled out. My goal is to prevent the PayPal popup window from opening if ...

Get all the classes from the body element of the AJAX-loaded page and update the body classes on the current page with them

I am currently in the process of AJAX-ing a WordPress theme with a persistent music player. In Wordpress, dynamic classes are used on the <body> tag. The structure I'm working with looks like this: <html> <head> </head> ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

Utilize ScriptControl for JSON parsing in VBA: convert output into dictionaries and collections

Looking to utilize Microsoft ScriptControl in VBA for parsing a JSON string and converting the resulting Object into Dictionary and Collection objects. While I have the parsing aspect down with ScriptControl, I'm struggling with how to translate the r ...

Troubleshooting Bootstrap 3.0: Issues with nav-tabs not toggling

I have set up my navigation tabs using Bootstrap 3 in the following way: <ul class="nav nav-tabs pull-right projects" role="tablist" style="margin-top:20px;"> <li class="active"><a role="tab" data-toggle="tab" href="#progress">In Pr ...

NodeJS: Implement a method to delete a file or folder using a path without the file extension (Strategic approach)

I am facing a challenge in deleting a file or folder based on a path that does not include an extension. Consider the path below: /home/tom/windows The name windows could refer to either a folder named windows OR a file named windows.txt Given that the ...

Using JavaScript, you can employ the .split() and .replace() methods on a string value to accurately extract the specific

I'm currently attempting to extract hashtags from a text string by splitting it and removing unwanted HTML tags. Despite my efforts, I haven't been able to achieve the desired outcome. I am seeking guidance on where I might be going wrong. Here ...

Utilize HTML5 to enable fullscreen functionality for embedded SWF files

I have implemented a function that handles the click event of a button to toggle a DOM element into fullscreen mode. The function works well, but I am facing an issue when there is another div containing a swf inside the main div. var elem = document.getE ...

Encountered an error while trying to initialize ng-init in Angular, specifically when including PHP

I have a PHP variable called $output. When I use echo json_encode($output), the output looks like this: [{ "title": null }, { "title": "a b c" }, { "title": "d e f" }, { "title": "d f g" }, { "title": "f g d" }] It appears to be corre ...

Can you explain the process of extracting images from JSON data using AJAX and jQuery?

Hello, I'm looking for guidance on incorporating jquery with AJAX to fetch images from a JSON file and showcase them on my website. Below is the code snippet I have put together. function bookSearch(){ var search = document.getElementById('sea ...

Can object-fit be preserved while applying a CSS transform?

Currently, I am developing a component that involves transitioning an image from a specific starting position and scale to an end position and scale in order to fill the screen. This transition is achieved through a CSS transform animation on translate and ...