Skip to content

Validation

Maximilian Mittelhammer edited this page Mar 31, 2024 · 1 revision

Validation

Dynormo provides a way to validate data before it is created or updated in the database. This is done through the ValidationConfig type, which allows you to specify validation functions for create and update operations.

ValidationConfig

The ValidationConfig type is defined as follows:

export type ValidationConfig<T, U> = {
  create: (item: T) => T;
  update: (item: U) => U;
};

It consists of two functions:

  • create: A function that takes an item of type T (eqaul to the Create_Entityl_Input) and returns an item of the same type. This function is used to validate items before they are created.

  • update: A function that takes an item of type U (equal to Update_Entity_Input) and returns an item of the same type. This function is used to validate items before they are updated.

Using ValidationConfig

You can specify a ValidationConfig for each table in your DynormoClientOptions:

export type DynormoClientOptions = {
  // ...
  validators?: {
    Users?: ValidationConfig<CreateUserInput, UpdateUserInput>;
  };
  // ...
};

In this example, a ValidationConfig is specified for the Users table. The create function will be used to validate items before they are created in the Users table, and the update function will be used to validate items before they are updated in the Users table.

Validation Functions

The validation functions should take an item as a parameter and return the validated item. If the item is not valid, the function should throw an error.

Here is an example of a validation function:

function validateUser(user: CreateUserInput): CreateUserInput {
  if (!user.name) {
    throw new Error("Name is required");
  }

  if (!user.email) {
    throw new Error("Email is required");
  }

  if (!user.password) {
    throw new Error("Password is required");
  }

  return user;
}

In this example, the validateUser function checks that the name, email, and password properties are present on the user object. If any of these properties are missing, the function throws an error. If all properties are present, the function returns the user object.

You can then use this function as the create function in your ValidationConfig:

const clientOptions: DynormoClientOptions = {
  // ...
  validators: {
    Users: {
      create: validateUser,
      update: validateUser,
    },
  },
  // ...
};

In this example, the validateUser function will be used to validate users before they are created or updated in the Users table.

Clone this wiki locally