Validate HTTP request with HttpClient & Zod

Luca Del Puppo - Full Stack Developer

@puppo92

Luca Del Puppo

  • Full Stack Developer
  • Javascript Enthusiastic
  • Typescript Lover
  • “Youtuber”
  • “Writer”

Love sport: running, hiking

Love animals

@puppo92

Typescript Journey

interface CustomerModel {
  id: number;
  name: string;
  email: string;
  phone: string;
}

Interaces

@puppo92

type CustomerModel = {
  id: number;
  name: string;
  email: string;
  phone: string;
};

Types

@puppo92

@puppo92

HTTP Request

Why?

  • Typescript enables type check but on BUILT-TIME
  • After the build all your types disappears
  • After the build all your considerations about types dissolve

@puppo92

@puppo92

Prevent ugly mistakes

Zod is your superhero

import { z } from ‘zod’;

const CustomerSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string(),
  phone: z.string(),
});

Schema

@puppo92

import { TypeOf } from ‘zod';

type CustomerModel = TypeOf<typeof CustomerSchema>;

Convert to Type

@puppo92

const res = CustomerSchema.parse({
  id: 1,
  name: 'John Doe',
  email: 'john@doe.com',
  phone: '555-555-5555'
});

Parse Method

@puppo92

Something wrong?

  • Parse throws an Error
  • ZodError is the right error to check
  • ZodError contains all the issues that describe the errors

@puppo92

@puppo92

Benefits of using Zod

Create a layer between your app and the outside

Validation

@puppo92

Demo

@puppo92

Conclusion

Conclusion

  • Typescript is awesome, but it’s good only on built time
  • Create a validation layer between your app and the outside
    • Prevent execution of code with wrong data
    • You can get notifications if something is changed
  • Using Zod, you can guarantee your types, both built-time and run-time

Code

Slides

Luca Del Puppo

@puppo92

Luca Del Puppo

Puppo_92

@puppo

Validate HTTP request with HttpClient & Zod

By Luca Del Puppo

Validate HTTP request with HttpClient & Zod

  • 448