针对 TypeScript 中的接口验证对象的模式

Pattern for validating objects against interface in TypeScript

我在 Azure Functions 中托管了一个 REST 端点。当有人调用该端点时,我会像这样处理传入请求:

// 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
}

其中 req.body 是从 trigger of an Azure Function 收到的(来源如果相关)

在接收消息和构造对象时,允许我验证 IPackage 接口中的 all 属性存在的模式是什么?整个列表需要在界面中定义所有属性。

您可以使用如下 isValid 方法检查您的 req.body:

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
    }
}

如果您想使用库进行模式验证,您可以查看 joi. You may enter your example online in the schema tester here https://joi.dev/tester/。对于 'IDimension' 类型,您需要编写一个子类型以通过 joi.

进行验证