Home > Software engineering >  Validate object that's received from api and set defaults
Validate object that's received from api and set defaults

Time:04-15

I want to receive something from an api and validate if all fields are strings but if they are not present I want to set default values, I was planning to use yup and validate the object based on that so the object that I return from the function is 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;
}

CodePudding user response:

Just assing validateSync to a variable and that value will be typed

const cleanObject = courseSchema.validateSync(originalObject);

console.log({ cleanObject })

CodePudding user response:

You better use interface and typeguard.

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 can also do it 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...;
}

And use it like this

export default function validateCourses(originalObject: unknown): MySchema {
  if (isMySchema(originalObject)) {
     return originalObject; // Will work because of the typeguard, it cast it into MySchema type
  } else {
     throw Error('wrong schema'); // Not sure what you do if it's not he right type
  }
}

Edit: I paper code this maybe there is small syntax mistake.

  • Related