typescriptmodelloopbackv4l2loopback

How should Model Validation be implemented in Loopback 4?


I'm pretty new to Loopback 4 framework, and I'm trying to use it for a small project that needs to connect data from different kinds of databases and services. One of the main reasons I'm using version 4 is because of Typescript and also because it supports ES7 features (async/await), which I really appreciate. Still, I have no idea how to implement model validation, at least not like Loopback v3 supports.

I've tried to implement custom validation on model constructors, but it looks like a really bad pattern to follow.

import {Entity, model, property} from '@loopback/repository';

@model()
export class Person extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'date',
    required: true,
  })
  birthDate: string;

  @property({
    type: 'number',
    required: true,
  })
  phone: number;

  constructor(data: Partial<Person>) {
    if (data.phone.toString().length > 10) throw new Error('Phone is not a valid number');
    super(data);
  }
}


Solution

  • LB4 uses ajv module to validate the incoming request data based on your model metadata. So, you can do a it using jsonSchema as mentioned below.

    export class Person extends Entity {
      @property({
        type: 'number',
        id: true,
        required: true,
      })
      id: number;
    
      @property({
        type: 'string',
        required: true,
      })
      name: string;
    
      @property({
        type: 'date',
        required: true,
      })
      birthDate: string;
    
      @property({
        type: 'number',
        required: true,
        jsonSchema: {
          maximum: 9999999999,
        },
      })
      phone: number;
    
      constructor(data: Partial<Person>) {
        super(data);
      }
    }
    

    Hope that works. Refer to the answer to a similar question on LB4 repo here for more details.