From 50d1b53ec2c2d5095df265e90d6fac56dc46cbbf Mon Sep 17 00:00:00 2001 From: Francisco Giordano Date: Mon, 5 Oct 2020 12:57:20 -0300 Subject: [PATCH] fix: filter out undefined query parameters and headers (#209) --- src/merge.ts | 5 +++++ src/util/remove-undefined-properties.ts | 8 +++++++ test/endpoint.test.ts | 29 +++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 src/util/remove-undefined-properties.ts diff --git a/src/merge.ts b/src/merge.ts index c2a0939f..bbbbf24a 100644 --- a/src/merge.ts +++ b/src/merge.ts @@ -2,6 +2,7 @@ import { EndpointDefaults, RequestParameters, Route } from "@octokit/types"; import { lowercaseKeys } from "./util/lowercase-keys"; import { mergeDeep } from "./util/merge-deep"; +import { removeUndefinedProperties } from "./util/remove-undefined-properties"; export function merge( defaults: EndpointDefaults | null, @@ -18,6 +19,10 @@ export function merge( // lowercase header names before merging with defaults to avoid duplicates options.headers = lowercaseKeys(options.headers); + // remove properties with undefined values before merging + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options) as EndpointDefaults; // mediaType.previews arrays are merged, instead of overwritten diff --git a/src/util/remove-undefined-properties.ts b/src/util/remove-undefined-properties.ts new file mode 100644 index 00000000..45129250 --- /dev/null +++ b/src/util/remove-undefined-properties.ts @@ -0,0 +1,8 @@ +export function removeUndefinedProperties(obj: any): any { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } + } + return obj; +} diff --git a/test/endpoint.test.ts b/test/endpoint.test.ts index 0c13ce3d..728b0922 100644 --- a/test/endpoint.test.ts +++ b/test/endpoint.test.ts @@ -427,4 +427,33 @@ describe("endpoint()", () => { }, }); }); + + it("Undefined query parameter", () => { + const options = endpoint({ + method: "GET", + url: "/notifications", + before: undefined, + }); + + expect(options).toEqual({ + method: "GET", + url: "https://api.github.com/notifications", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent, + }, + }); + }); + + it("Undefined header value", () => { + const options = endpoint({ + method: "GET", + url: "/notifications", + headers: { + "if-modified-since": undefined, + }, + }); + + expect(options).not.toHaveProperty("headers.if-modified-since"); + }); });