Skip to content
This repository has been archived by the owner on Sep 21, 2022. It is now read-only.

Update decodeOpaqueId.js #63

Open
wants to merge 5 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions lib/decodeOpaqueId.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import config from "./config.js";

/**
* @name decodeOpaqueId
* @method
* @memberof GraphQL/Transforms
* @summary Transforms an opaque ID to an internal ID
* @summary Transforms an opaque ID to an internal ID. Returns the `id`
* unchanged and the `namespace` as null if the `REACTION_SHOULD_ENCODE_IDS`
* environment variable is `false`
* @param {String} opaqueId The ID to transform
* @returns {String} An internal ID
*/
export default function decodeOpaqueId(opaqueId) {
if (opaqueId === undefined || opaqueId === null) return null;

const [namespace, id] = Buffer
.from(opaqueId, "base64")
if (config.REACTION_SHOULD_ENCODE_IDS === false) {
return { namespace: null, id: opaqueId };
}

const [namespace, id] = Buffer.from(opaqueId, "base64")
.toString("utf8")
.split(":", 2);

Expand Down
19 changes: 19 additions & 0 deletions lib/decodeOpaqueId.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { jest } from "@jest/globals";
import config from "./config.js";
import decodeOpaqueId from "./decodeOpaqueId.js";

jest.mock("./config.js", () => ({
__esModule: true, // this property makes it work
default: {
REACTION_SHOULD_ENCODE_IDS: true
}
}));

test("decodes base64", () => {
const encodedId = "cmVhY3Rpb24vc2hvcDpieTV3cGRnM25NcThnWDU0Yw==";
expect(decodeOpaqueId(encodedId)).toEqual({
Expand All @@ -15,3 +24,13 @@ test("passes through non-base64", () => {
namespace: null
});
});

test("skips decoding if REACTION_SHOULD_ENCODE_IDS env is false", async () => {
const id = "by5wpdg3nMq8gX54c";
config.REACTION_SHOULD_ENCODE_IDS = false;
expect(decodeOpaqueId(id)).toEqual({
id,
namespace: null
});
config.REACTION_SHOULD_ENCODE_IDS = true;
});