Confirm the object received from the API and assign default values

Seeking to extract data from an API and verify if all fields are strings, but if they are missing I aim to assign default values. My intention was to utilize the yup library to validate the object accordingly, ensuring that the returned function is properly typed.

import { v4 } from "uuid";
import { array, object, string } from "yup";

let mySchema = array(
  object({
    id: string().default(() => v4()),
    title: string().default(""),
    description: string().default(""),
    courseVersions: array(
      object({
        courseCodeId: string().default(""),
        courseName: string().default(""),
      })
    ).default([]),
  })
);

export default function validateCourses(originalObject: any) {

  const cleanObject = mySchema.someFunction(originalObject); // Hope yup has a function

  console.log({ originalObject, cleanObject });

  return cleanObject;
}

Answer №1

To assign validateSync to a variable, simply store it in a new variable and the value will become typed.

const validatedObject = courseSchema.validateSync(originalObject);

console.log({ validatedObject })

Answer №2

It's recommended to utilize interface and typeguard for better programming practices.

interface CourseVersion {
  courseCodeId: string;
  courseName: string;
}

interface MySchema {
  id: string;
  title: string;
  description: string;
  courseVersions: CourseVersion[];
}

let mySchema: MySchema = {
    id: 'mock-id',
    title: 'mock-title',
    description: 'mock-description',
    courseVersions: [
      {courseCodeId: 'mock-courseCodeId', courseName: 'mock-courseName'}
    ]
  })
);

function isMySchema (schema: unknown): schema is MySchema {
   return schema instanceof MySchema;
}

You also have the option to implement it in a different way like this:

function isMySchema (schema: unknown): schema is MySchema {
   return schema?.id !== undefined && typeof schema?.id === 'string'
     && schema?.title !== undefined && typeof schema?.title === 'string'
     etc...;
}

To use it, follow this approach:

export default function validateCourses(originalObject: unknown): MySchema {
  if (isMySchema(originalObject)) {
     return originalObject; // This will work due to the typeguard, casting it into MySchema type
  } else {
     throw Error('wrong schema'); // Handle the scenario where it's not the expected type
  }
}

Note: I hand-coded this, so there may be minor syntax errors.

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

Achieving the perfect sorting result in an array using Javascript

I am attempting to arrange the objects inside an array below in ascending order by their values and achieve the desired output as shown: var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.004186044328301671376196 ...

Angular custom window injection

Currently, I am working on an Angular application that is housed within an Android WebView. To facilitate communication with my Android application, I have made an object accessible at the window level: window.MyAndroidApp This object contains various me ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Exploring the bounds of self-invocation functions in JavaScript

Have you ever wondered why self-invocation functions inside another function in JavaScript don't inherit the scope of the outer function? var prop = "global"; var hash = { prop: "hash prop", foo: function(){ console.log(this.prop); ...

Displaying a div on click using Jquery will only impact one div at a time

I am encountering an issue with my WordPress setup. Within my loop, I have a clickable link that toggles a div to show or hide content. However, since each item in the loop uses the same class, clicking on one link activates all of them simultaneously. &l ...

Access the HTML file from a different directory

I have a directory called "myWebsite". Within this directory, there is a file named "index.html" and another subdirectory named "other". Inside the "other" directory, there are CSS files, JS files, and "page2.ht ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

Guide on deploying a Next.js React project with IIS on a Windows Server

Our goal is to deploy the application on an IIS server while ensuring it supports dynamic routing. After attempting to install IIS node, we are unsure of our next steps. Do we need to load a specific file like server.js in order to run the application ...

Guide to uploading a PDF to Google Drive and embedding it on an HTML static website

I manage a static HTML site for a small food shop. They require monthly menu uploads in PDF format. I believe uploading to Google Drive would be a more efficient solution than creating a separate admin view for file uploads. Can anyone advise me on how to ...

Error: mangosse is not recognized

Node keeps throwing the error 'ReferenceError: mangoose is not defined' in my face. The culprit seems to be this line: const dogSchema = new mangoose.Schema({ I made sure to install mongoose using npm $ npm i mongoose Check out the code belo ...

Navigating the grid layout in Material UI can be tricky to

I'm struggling to grasp the concept of the grid system in material UI. Within my grid container, I have two grid items that I want to be centered and occupy the entire width. The button element appears centered, but the typography element does not. A ...

Showcasing ranges from various input types on a single page

I have a challenge in displaying the values of multiple sliders on my webpage. Here's the code snippet I've been working on: var i = 0; var st = 'slider'; var ot = 'output'; var s = ''; var o = ''; for ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Utilizing function arguments in ReactJS

Currently, I am in the process of learning ReactJs and have an inquiry about the code snippet below. Would someone be able to clarify the functionality of the removeTour code and why the id parameter is being used within the function? const removeTour = (i ...

Navigating production mode in nuxtjs and uncovering errors

There seem to be numerous inquiries regarding this matter. Unfortunately, there doesn't appear to be a definitive solution. Is there any way to view detailed error logs in production mode? https://i.stack.imgur.com/prXUt.jpg ...

retrieving the parent of the a tag from a jquery form

When using the jQuery code below: $('#trade-offer form').on("submit", function(event) { event.preventDefault(); var stock = $(this).closest('.allloopedover'); console.log(stock); return; $.ajax({ url: ajaxur ...

Having issues initializing jQuery knob on a jQuery mobile webpage

I'm trying to implement the jquery knob plugin to showcase a circular rating system, but I'm encountering difficulties in getting it to display properly. Below is the code snippet I'm using - can someone please point out what's causing ...

retrieve undefined value from redux state in a React Native application

Received the data in reducer but encountering issues accessing it in the component. Below is the connection code: const mapStateToProps =state => { return { name:state.fbLogin.name } } function mapDispatchToProps(dispatch){ ...

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Failure to highlight items when using the multiple select function

After adding a select all button to a multiple select, I encountered an issue. Although all the items are being selected, they are not highlighted when clicking on the select all button. Below is the code snippet: <div class="label_hd">Profiles* {{ ...