Skip to content

Commit

Permalink
Allow passing custom cid variant (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
zapo authored Apr 4, 2024
1 parent ec5185f commit 2b380ce
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 11 deletions.
30 changes: 21 additions & 9 deletions lib/sdk.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,29 @@ test("eid ignores case", () => {
expect(eid).toEqual(OptableSDK.eid(var4));
});

test("cid is correct", () => {
const expected = "c:FooBarBAZ-01234#98765.!!!";
test("cid rejects non-string id", () => {
expect(() => OptableSDK.cid(1)).toThrow();
});

expect(expected).toEqual(OptableSDK.cid("FooBarBAZ-01234#98765.!!!"));
expect(expected).toEqual(OptableSDK.cid(" FooBarBAZ-01234#98765.!!!"));
expect(expected).toEqual(OptableSDK.cid("FooBarBAZ-01234#98765.!!! "));
expect(expected).toEqual(OptableSDK.cid(" FooBarBAZ-01234#98765.!!! "));
test("cid prefixes with c: by default", () => {
expect(OptableSDK.cid("abc")).toEqual("c:abc");
});

test("cid is case sensitive", () => {
const unexpected = "c:FooBarBAZ-01234#98765.!!!";
test("cid accepts a custom variant", () => {
expect(OptableSDK.cid("abc", 0)).toEqual("c:abc");
for (let i = 1; i < 10; i++) {
expect(OptableSDK.cid("abc", i)).toEqual(`c${i}:abc`);
}

expect(() => OptableSDK.cid("abc", -1)).toThrow();
expect(() => OptableSDK.cid("abc", 10)).toThrow();
expect(() => OptableSDK.cid("abc", "1")).toThrow();
});

test("cid trim spaces", () => {
expect(OptableSDK.cid(" \n abc\t")).toEqual("c:abc");
});

expect(OptableSDK.cid("foobarBAZ-01234#98765.!!!")).not.toEqual(unexpected);
test("cid preserve case", () => {
expect(OptableSDK.cid("ABCD")).toEqual("c:ABCD");
});
18 changes: 16 additions & 2 deletions lib/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,22 @@ class OptableSDK {
return email ? "e:" + sha256.hex(email.toLowerCase().trim()) : "";
}

static cid(ppid: string): string {
return ppid ? "c:" + ppid.trim() : "";
static cid(ppid: string, variant: number = 0): string {
let prefix = "c:";

if (typeof ppid !== "string") {
throw new Error("Invalid ppid");
}

if (typeof variant !== "number" || isNaN(variant) || variant < 0 || variant > 9) {
throw new Error("Invalid variant");
}

if (variant > 0) {
prefix = `c${variant}:`;
}

return ppid ? prefix + ppid.trim() : "";
}

static TargetingKeyValues(tdata: TargetingResponse): TargetingKeyValues {
Expand Down

0 comments on commit 2b380ce

Please sign in to comment.