0

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.

1
  • TS is unable to check if object has all properties in runtime. I would rather use avj (ajv.js.org) to make runtime type checks. You can make special TypeScript guard to check all properties Commented Nov 10, 2020 at 15:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for showing how to do this with pure js. Joi looks promising, will probably implement it to not have to write so much boilerplate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.