Skip to content
Merged
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
12 changes: 10 additions & 2 deletions src/referrals/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,16 @@ export function createReferralsRouteHandler(options: ReferralsRouteHandlerOption
const userId = await getUserId(req);
if (!userId) return jsonResponse({ error: "Unauthorized" }, { status: 401 });
const code = typeof body["code"] === "string" ? body["code"] : null;
const amount = typeof body["amount"] === "number" ? body["amount"] : null;
if (!code || !amount) return jsonResponse({ error: "Missing code or amount" }, { status: 400 });
const rawAmount = body["amount"];
const amount =
typeof rawAmount === "number" &&
Number.isSafeInteger(rawAmount) &&
rawAmount > 0
? rawAmount
: null;
if (!code || amount === null) {
return jsonResponse({ error: "Missing code or amount" }, { status: 400 });
}
const usage = await applyReferral({
code,
newUserId: userId,
Expand Down
29 changes: 29 additions & 0 deletions tests/referrals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,35 @@ describe("createReferralsRouteHandler (authenticated)", () => {
expect(await missing.json()).toEqual({ error: "Missing code or amount" });
});

it.each([-100, 0, 1.5, Number.MAX_SAFE_INTEGER + 1, "100", null])(
"POST apply rejects invalid cent amount %j without saving a usage",
async (amount) => {
const { store, usages } = makeMemoryStore();
await store.saveCode({
code: "ABC123",
ownerId: "user-1",
createdAt: new Date(),
expiresAt: null,
});
const { POST } = createReferralsRouteHandler({
store,
getUserId: () => "user-2",
});

const res = await POST(
makeReq("https://app.test/api/referrals", {
action: "apply",
code: "ABC123",
amount,
})
);

expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: "Missing code or amount" });
expect(usages).toHaveLength(0);
}
);

it("POST apply records the usage with the default 60/20 split", async () => {
const { store, usages } = makeMemoryStore();
await store.saveCode({
Expand Down
Loading