All files / src/domain/baby baby-measurement.ts

100% Statements 10/10
100% Branches 21/21
100% Functions 1/1
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                                    45x 45x 1x   44x 44x 1x   43x 3x   40x 3x      
import { DomainError } from '../../shared/errors/domain-error';
 
export interface BabyMeasurement {
  id: string;
  measuredOn: Date;
  weightGrams: number | null;
  heightMillimeters: number | null;
}
 
export interface BabyMeasurementInput {
  measuredOn: string;
  weightGrams?: number | null;
  heightMillimeters?: number | null;
}
 
export class InvalidBabyMeasurementError extends DomainError {}
 
export function validateBabyMeasurement(measurement: BabyMeasurement, birthDate: Date): void {
  const date = measurement.measuredOn;
  if (!Number.isFinite(date.getTime()) || date < birthDate || date.toISOString().slice(0, 10) > new Date().toISOString().slice(0, 10)) {
    throw new InvalidBabyMeasurementError('Measurement date must be between birth and today');
  }
  const { weightGrams, heightMillimeters } = measurement;
  if (weightGrams === null && heightMillimeters === null) {
    throw new InvalidBabyMeasurementError('A measurement needs weight or height');
  }
  if (weightGrams !== null && (!Number.isInteger(weightGrams) || weightGrams < 100 || weightGrams > 150000)) {
    throw new InvalidBabyMeasurementError('Weight must be between 100 and 150000 grams');
  }
  if (heightMillimeters !== null && (!Number.isInteger(heightMillimeters) || heightMillimeters < 100 || heightMillimeters > 2500)) {
    throw new InvalidBabyMeasurementError('Height must be between 100 and 2500 millimeters');
  }
}