Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support passing custom getUserId function #310

Open
wants to merge 3 commits into
base: main
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ Finally, in case you are using banners and want to have further control on the a
</div>
```

### Overriding default User ID behavior

If you want to pass your own User ID when sending events, you can do so by overiding the `getUserID()` function which is
responsible for retrieving a unique identifier for the user. It should additionally set a new value if none is found. This function should return a string with the User ID (as a string) passed in the events.

```javascript
window.TS = {
token: "<YOUR-TOPSORT.JS-TOKEN>",
getUserId() {
// globalUserId is the user id you would like to pass to the analytics
// generateAndStoreUserId is a function that generates a new user id and stores it in a cookie/local storage
return globalUserId ?? generateAndStoreUserId();
},
};
```

```html
# Troubleshooting

## I see `Uncaught Error: Mismatched anonymous define() module` in the browser console
Expand Down
38 changes: 38 additions & 0 deletions src/detector.custom-getuserid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { expect, test } from "vitest";

test("support custom getUserId function", async () => {
window.TS = {
token: "token",
getUserId: () => {
return "custom-user-id";
},
};
const events: any[] = [];
window.addEventListener("topsort", (e) => {
events.push((e as any).detail);
});
document.body.innerHTML = `
<div id="product" data-ts-product="product-id-click-1" data-ts-resolved-bid="1247eaae-63a1-4c20-9b52-9efdcdef3095"></div>
`;
await import("./detector");

document.getElementById("product")?.click();
expect(events).toMatchObject([
{
type: "Impression",
page: "/",
product: "product-id-click-1",
bid: "1247eaae-63a1-4c20-9b52-9efdcdef3095",
id: expect.stringMatching(/[\d.a-zA-Z-]+/),
uid: "custom-user-id",
},
{
type: "Click",
page: "/",
product: "product-id-click-1",
bid: "1247eaae-63a1-4c20-9b52-9efdcdef3095",
id: expect.stringMatching(/[\d.a-zA-Z-]+/),
uid: "custom-user-id",
},
]);
});
18 changes: 10 additions & 8 deletions src/detector.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type Config, Entity, TopsortClient, Event as TopsortEvent } from "@topsort/sdk";
import { type Config, type Entity, TopsortClient, type Event as TopsortEvent } from "@topsort/sdk";
import { version } from "../package.json";
import { ProcessorResult, Queue } from "./queue";
import { type ProcessorResult, Queue } from "./queue";
import { truncateSet } from "./set";
import { BidStore } from "./store";

Expand All @@ -17,7 +17,7 @@
* just be a random number;
*/
function generateId(): string {
return window.URL.createObjectURL?.(new Blob()).split("/").pop() || Math.random() + "";
return window.URL.createObjectURL?.(new Blob()).split("/").pop() || `${Math.random()}`;
}

let globalUserId: string | undefined;
Expand All @@ -39,7 +39,7 @@
function setUserIdCookie(id: string): void {
const cookieName = window.TS.cookieName || "tsuid";
globalUserId = id;
document.cookie = cookieName + "=" + id + ";max-age=31536000";
document.cookie = `${cookieName}=${id};max-age=31536000`;
}

function resetUserId(): string {
Expand All @@ -49,13 +49,15 @@
}

window.TS.setUserId = setUserIdCookie;
window.TS.getUserId = getUserId;
if (typeof window.TS.getUserId !== "function") {
window.TS.getUserId = getUserId;
}
window.TS.resetUserId = resetUserId;

// Based on https://stackoverflow.com/a/25490531/1413687
function getUserIdCookie(): string | undefined {
const cookieName = window.TS.cookieName || "tsuid";
const regex = new RegExp("(^|;)\\s*" + cookieName + "\\s*=\\s*([^;]+)");
const regex = new RegExp(`(^|;)\\s*${cookieName}\\s*=\\s*([^;]+)`);
return regex.exec(document.cookie)?.pop();
}

Expand Down Expand Up @@ -212,7 +214,7 @@
let product = node.dataset.tsProduct;
let bid = node.dataset.tsResolvedBid;
let additionalProduct: string | undefined = undefined;
if (bid == "inherit" && product && (type == "Click" || type == "Impression")) {
if (bid === "inherit" && product && (type === "Click" || type === "Impression")) {
bid = bidStore.get();
additionalProduct = product;
product = undefined;
Expand All @@ -225,7 +227,7 @@
t: Date.now(),
page: getPage(),
id: generateId(),
uid: getUserId(),
uid: window.TS.getUserId() ?? getUserId(),

Check failure on line 230 in src/detector.ts

View workflow job for this annotation

GitHub Actions / lint

Cannot invoke an object which is possibly 'undefined'.
};
if (type === "Purchase") {
event.items = JSON.parse(node.dataset.tsItems || "[]");
Expand Down
Loading