Improve type checks of RequestParser.parseCreditBody

This commit is contained in:
Simon Warta 2020-08-04 11:23:29 +02:00
parent 8bb2b1bb76
commit 7dfdec3da3
2 changed files with 20 additions and 2 deletions

View File

@ -7,6 +7,18 @@ describe("RequestParser", () => {
});
it("throws for invalid credit requests", () => {
// body not a dictionary
{
expect(() => RequestParser.parseCreditBody("foo")).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(null)).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(42)).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody([])).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(true)).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(undefined)).toThrowError(
/Request body must be a dictionary./i,
);
}
// address unset
{
const body = { ticker: "TKN" };

View File

@ -1,3 +1,5 @@
import { isNonNullObject } from "@cosmjs/utils";
import { HttpError } from "./httperror";
export interface CreditRequestBodyData {
@ -8,8 +10,12 @@ export interface CreditRequestBodyData {
}
export class RequestParser {
public static parseCreditBody(body: any): CreditRequestBodyData {
const { address, ticker } = body;
public static parseCreditBody(body: unknown): CreditRequestBodyData {
if (!isNonNullObject(body) || Array.isArray(body)) {
throw new HttpError(400, "Request body must be a dictionary.");
}
const { address, ticker } = body as any;
if (typeof address !== "string") {
throw new HttpError(400, "Property 'address' must be a string.");