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

Implement dynamic routes within your Nuxt single page application once it has been generated

I'm currently exploring the possibility of implementing dynamic routes in a Nuxt SPA. While I am familiar with using dynamic routes in Universal Mode and generating them during build time through functions, I am searching for a solution that does not ...

Can the animation be looped using setInterval()?

Once the images finish sliding in the animation, they continue to slide right endlessly. I've attempted using a setTimeout function to move the images back left and restart the animation, but this causes the setInterval animation to stop. Is there a w ...

The issue I am experiencing within my PHP code is that the redirection to the gratitude page is not functioning correctly when utilizing

As a newcomer to PHP, I have been struggling with an example code from a website that is not redirecting to the thank you page as expected. Moreover, the email functionality is not working properly either. The code was sourced from: Upon downloading the f ...

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

Utilizing a Function's Return Value as a State in React - A Comprehensive Guide

Currently, I am delving into the realm of functional components within React and have crafted a simple piece of code that should output 'Nah' if the state value is at 0. However, there seems to be an issue as this functionality does not seem to ...

Dropdown element vanishes upon selecting in HTML

Utilizing Angular's ng-init to populate a rest call function and populate $scope.races before filling up the dropdown. Initially, everything appears to be working correctly. However, upon selecting an option from the dropdown menu, it immediately cle ...

SQL Query For Retrieving 30 Distinct Variables

My task involves retrieving data on the number of user registrations for each of the past 30 days. I am then converting this data into Json format to be used in a GoogleChart. I'm exploring more efficient ways to retrieve the data I need without havi ...

What is the best way to format a User object into JSON before sending it to an API endpoint?

Encountering an error 400 when attempting to submit a POST request. "$.User": [ "The JSON value could not be converted to WebApi.Models.User. Path: $.User | LineNumber: 5 | BytePositionInLine: 19." ] } Detailing my Order Model with ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

Searching the database to find if the username is already in use with MEAN

Help needed with signup controller code! app.controller('SignupController', function ($scope, $http, $window) { $scope.submitSignup = function () { var newUser = { username: $scope.username, ...

Deactivate an element completely, preventing any interaction with it, including disabling links that trigger other JavaScript functions

<li class=" active"> <input class="check-shopby" type="checkbox" onclick="$(this).next().click()" checked="checked"> <a class="checked" href="http://mysite/~dev433/products//cooking/cook-tops.html" onclick="$(this).previous().checked = f ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

What is the most effective method for destructuring within React components?

Observing how people implement destructuring in functional components in React, I have noticed a common pattern. const InputGroup = ({ name, placeholder, value }) => ( However, my preferred method differs: const InputGroup = props => { ...

What is the best way to showcase a formatted JSON string on a webpage?

Currently, I'm in the process of creating a proof-of-concept React application that fetches data from the GitHub API. This app is designed to showcase the retrieved GitHub data as a JSON string within a paragraph element. Issue The problem arises whe ...

Looking to split the month and year input boxes when utilizing stripe version 7.2.0

Currently, I am utilizing ngx-stripe Version 7.2.0 to manage UI elements in Angular. I'm wondering if there is a method to split the Month and Year into separate text boxes within the UI of Angular 7 instead of having them combined into one field? ...

Is there a way to simultaneously send a file and additional information in Flask?

Below is the code I am using to upload a file to Flask. Client Side: <form id="upload-file" method="post" enctype="multipart/form-data"> <fieldset> <label for="file">Select a file</label> <input name="file8" ...

Choose a selection in ExtJS by finding matching attributes

Is there a convenient method to choose an item in an Ext.tree.Panel by matching it with an item based on the same attribute in an Ext.grid.Panel? For example, using something like: tree_dir.getSelectionModel().select(grid_file.getSelectionModel().getSelect ...

The application of knockoutjs bindings is restricted to specific ids and cannot be used on any

In my project, I have multiple views where each one applies bindings to its own tag individually. Here is a snippet of the code: (Please note that some code has been omitted for brevity. For a more complete example, you can view the full fiddle here: http ...

Ways to determine the types of props received by a function when the arguments vary for each scenario?

I have a specialized component that handles the majority of tasks for a specific operation. This component needs to invoke the onSubmit function received through props, depending on the type of the calling component. Below is an example code snippet show ...