Skip to content

Commit

Permalink
Filter out falsey opts in /relations API hits (#2059)
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy authored Dec 13, 2021
1 parent 6244d77 commit 169b6b5
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 8 deletions.
9 changes: 9 additions & 0 deletions spec/unit/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion src/@types/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export interface IBindThreePidBody {
export interface IRelationsRequestOpts {
from?: string;
to?: string;
limit?: string;
limit?: number;
}

export interface IRelationsResponse {
Expand Down
6 changes: 1 addition & 5 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6763,11 +6763,7 @@ export class MatrixClient extends EventEmitter {
eventType?: EventType | string | null,
opts: IRelationsRequestOpts = {},
): Promise<IRelationsResponse> {
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<string, string | number>);

let templatedUrl = "/rooms/$roomId/relations/$eventId";
if (relationType !== null) templatedUrl += "/$relationType";
Expand Down
11 changes: 9 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, string>): string {
return new URLSearchParams(params).toString();
export function encodeParams(params: Record<string, string | number | boolean>): 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<string, string | string[]>;
Expand Down

0 comments on commit 169b6b5

Please sign in to comment.