From 169b6b55727d0eea181a31b3170439c9a355065b Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Mon, 13 Dec 2021 15:38:03 +0000 Subject: [PATCH] Filter out falsey opts in /relations API hits (#2059) --- spec/unit/utils.spec.ts | 9 +++++++++ src/@types/requests.ts | 2 +- src/client.ts | 6 +----- src/utils.ts | 11 +++++++++-- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/spec/unit/utils.spec.ts b/spec/unit/utils.spec.ts index 61d11b1cf..cd9b1b5b5 100644 --- a/spec/unit/utils.spec.ts +++ b/spec/unit/utils.spec.ts @@ -26,6 +26,15 @@ describe("utils", function() { "foo=bar&baz=beer%40", ); }); + + it("should handle boolean and numeric values", function() { + const params = { + string: "foobar", + number: 12345, + boolean: false, + }; + expect(utils.encodeParams(params)).toEqual("string=foobar&number=12345&boolean=false"); + }); }); describe("encodeUri", function() { diff --git a/src/@types/requests.ts b/src/@types/requests.ts index d502b63e3..0ca79da2b 100644 --- a/src/@types/requests.ts +++ b/src/@types/requests.ts @@ -143,7 +143,7 @@ export interface IBindThreePidBody { export interface IRelationsRequestOpts { from?: string; to?: string; - limit?: string; + limit?: number; } export interface IRelationsResponse { diff --git a/src/client.ts b/src/client.ts index ce5a01381..f9a12f332 100644 --- a/src/client.ts +++ b/src/client.ts @@ -6763,11 +6763,7 @@ export class MatrixClient extends EventEmitter { eventType?: EventType | string | null, opts: IRelationsRequestOpts = {}, ): Promise { - const params = new URLSearchParams(); - for (const [key, val] of Object.entries(opts)) { - params.set(key, val); - } - const queryString = params.toString(); + const queryString = utils.encodeParams(opts as Record); let templatedUrl = "/rooms/$roomId/relations/$eventId"; if (relationType !== null) templatedUrl += "/$relationType"; diff --git a/src/utils.ts b/src/utils.ts index a4862b1ce..136d7ffe0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -27,12 +27,19 @@ import type NodeCrypto from "crypto"; /** * Encode a dictionary of query parameters. + * Omits any undefined/null values. * @param {Object} params A dict of key/values to encode e.g. * {"foo": "bar", "baz": "taz"} * @return {string} The encoded string e.g. foo=bar&baz=taz */ -export function encodeParams(params: Record): string { - return new URLSearchParams(params).toString(); +export function encodeParams(params: Record): string { + const searchParams = new URLSearchParams(); + for (const [key, val] of Object.entries(params)) { + if (val !== undefined && val !== null) { + searchParams.set(key, String(val)); + } + } + return searchParams.toString(); } export type QueryDict = Record;