Skip to content

Commit

Permalink
feat(core-api): transform comma query into array to allow OR (#4068)
Browse files Browse the repository at this point in the history
  • Loading branch information
air1one authored Sep 30, 2020
1 parent da2e563 commit 0a69f65
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
61 changes: 61 additions & 0 deletions __tests__/unit/core-api/plugins/comma-array-query.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { commaArrayQuery } from "@packages/core-api/src/plugins/comma-array-query";

describe("commaArrayQuery.register", () => {
it("should register onRequest extension", () => {
const server = {
ext: jest.fn(),
};

commaArrayQuery.register(server);

expect(server.ext).toBeCalledWith("onRequest", commaArrayQuery.onRequest);
});
});

describe("commaArrayQuery.onRequest", () => {
it("should replace comma separated query parameter by array", () => {
const addresses = [
"AXGc1bgU3v3rHmx9WVkUUHLA6gbzh8La7V",
"AQvWbCAXbBnY9fHpgNrcLZ99hYfDifH4Hs",
"ATKegneyu9Fkoj5FxiJ3biup8xv8zM34M3",
];
const request = {
query: {
address: addresses.join(","),
},
};

const h = {
continue: Symbol,
};

const ret = commaArrayQuery.onRequest(request, h);

expect(request.query).toEqual({
address: addresses,
});

expect(ret).toBe(h.continue);
});

it("should leave as-is query parameter without comma", () => {
const address = "AXGc1bgU3v3rHmx9WVkUUHLA6gbzh8La7V";
const request = {
query: {
address,
},
};

const h = {
continue: Symbol,
};

const ret = commaArrayQuery.onRequest(request, h);

expect(request.query).toEqual({
address,
});

expect(ret).toBe(h.continue);
});
});
22 changes: 22 additions & 0 deletions packages/core-api/src/plugins/comma-array-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import Hapi from "@hapi/hapi";

export const commaArrayQuery = {
name: "comma-array-query",
version: "1.0.0",

register(server: Hapi.Server): void {
server.ext("onRequest", this.onRequest);
},

onRequest(request: Hapi.Request, h: Hapi.ResponseToolkit): Hapi.Lifecycle.ReturnValue {
const query = {};
const separator = ",";

for (const [key, value] of Object.entries(request.query as { [key: string]: string })) {
query[key] = value.indexOf(separator) > -1 ? value.split(separator) : value;
}

request.query = query;
return h.continue;
},
};
2 changes: 2 additions & 0 deletions packages/core-api/src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { dotSeparatedQuery } from "./dot-separated-query";
import { commaArrayQuery } from "./comma-array-query";
import { hapiAjv } from "./hapi-ajv";
import { whitelist } from "./whitelist";

Expand All @@ -10,6 +11,7 @@ export const preparePlugins = (config) => [
},
},
{ plugin: hapiAjv },
{ plugin: commaArrayQuery },
{ plugin: dotSeparatedQuery },
{
plugin: require("./cache"),
Expand Down

0 comments on commit 0a69f65

Please sign in to comment.