cookie-cutter icon indicating copy to clipboard operation
cookie-cutter copied to clipboard

gRPC service returns appropriate error message upon input invalidation

Open hienqnguyen opened this issue 4 years ago • 0 comments

If a grpc service has a validateJS configured and an invalid message comes it, it would be nice if CC returns a grpc.status.INVALID_ARGUMENT with the validation error as message.

This is what we're doing currently to achieve the same behavior:

export function wrap<TM, TC, TR>(fieldNames: string[], f: handlerFunc<TM, TC, TR>): handlerFunc<TM, TC, TR> {
    return async (msg: TM, ctx: IDispatchContext<TC>): Promise<TR | any> => {

        const nullRequiredFields = fieldNames.filter((field) => !getField(field, msg));
        if (nullRequiredFields.length > 0) {
            return new Promise((resolve) => resolve({
                code: grpc.status.INVALID_ARGUMENT,
                message: `Required fields are null: [${nullRequiredFields.join(", ")}]`,
            }));
        }

        return await f(msg, ctx);
    };
}

/**
 * This function is to support the supply of dot-notation fields for validation
 * @param fieldAddress The dot delimited field address e.g. "source.location" || "a.b.c.d"
 * @param objectToTraverse The object on which to traverse for a reference
 */
function getField(fieldAddress: string, objectToTraverse: any) {
    return fieldAddress.split(".").reduce(index, objectToTraverse);
}

function index(obj: any, nextAddress: string) { return obj[nextAddress]; }

hienqnguyen avatar May 19 '20 14:05 hienqnguyen