jokarl
jokarl

Reputation: 2225

Pattern for validating objects against interface in TypeScript

I have a REST endpoint hosted in Azure Functions. When someone calls that endpoint, I handle the incoming request like this:

// Construct
const requestBody: RequestBody = new RequestBody(req.body)

// Class
export class RequestBody {
    private _packages: IPackage[]

    constructor(object: any) {
        this._packages = object.packages
    }

    get packages(): IPackage[] {
        return this._packages
    }
}

// IPackage interface
export interface IPackage {
    packageId: string
    shipmentId: string
    dimensions: IDimension
}

Where req.body is received from the trigger of an Azure Function (source if is relevant)

When receiving the message and constructing the object, what is a pattern that allows me to verify that all properties in the IPackage interface are present? The entire list needs to have all properties defined in the interface.

Upvotes: 0

Views: 467

Answers (1)

masp
masp

Reputation: 350

You can check your req.body with a isValid method like this:

export class RequestBody {
    private _packages: IPackage[]

    constructor(object: any) {
        this._packages = object.packages
    }

    isValid(): boolean {
        let bValid = Array.isArray(this._packages);
        if (bValid) {
            for(const entry of this._packages) {
                if (!entry.packageId || typeof entry.packageId !== "string") {
                    bValid = false;
                    break;
                }
                // Check other attributes the same way and write some
                // custom code for IDimension.
            }
        }
        return bValid
    }

    get packages(): IPackage[] {
        return this._packages
    }
}

If you want to use a library for schema validation you could take a look at joi. You may enter your example online in the schema tester here https://joi.dev/tester/. For the type 'IDimension' you would need to write a subtype to validate via joi.

Upvotes: 1

Related Questions