The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Email lookup with a fallback.
Rafic15a8562960c
diff --git a/apps/web/lib/api/partners/search/build-search-query.ts b/apps/web/lib/api/partners/search/build-search-query.tsindex 137e2230ea..f945ab4795 100644--- a/apps/web/lib/api/partners/search/build-search-query.ts+++ b/apps/web/lib/api/partners/search/build-search-query.ts@@ -1,4 +1,3 @@-import { isExactEmailQuery } from "@/lib/api/partners/program-enrollment-query";import { getPartnersQuerySchemaExtended } from "@/lib/zod/schemas/partners";import * as z from "zod/v4";import {@@ -30,11 +29,7 @@ export function buildPartnerSearchCandidateQuery({// Exact email and tenant lookups remain database-only. The search provider// is responsible only for finding relevance-ranked free-text candidates.- //- // A search that is itself a complete address is the same lookup: `email` is a- // unique indexed column, so the database answers it exactly, and routing it- // through the provider would spend a network round trip to rank one row.- if (!query || email || tenantId || isExactEmailQuery(query)) {+ if (!query || email || tenantId) {return null;}diff --git a/apps/web/lib/api/partners/search/find-candidates.ts b/apps/web/lib/api/partners/search/find-candidates.tsindex 10ae038865..bae9e0fb93 100644--- a/apps/web/lib/api/partners/search/find-candidates.ts+++ b/apps/web/lib/api/partners/search/find-candidates.ts@@ -1,3 +1,5 @@+import { isExactEmailQuery } from "@/lib/api/partners/program-enrollment-query";+import { prisma } from "@/lib/prisma";import type {PartnerSearchCandidateQuery,PartnerSearchProvider,@@ -17,12 +19,29 @@ interface FindPartnerSearchCandidatesOptions {* the provider fails. Returning null here is what the callers already do when* no provider is configured, so a provider outage costs relevance ranking and* the wider field coverage rather than the entire partners list.+ *+ * A complete email address takes the same exit, but only once the database+ * confirms it: `email` is unique and indexed, so the lookup is a point read+ * against a network round trip. A miss still goes to the provider, because an+ * address matching nothing exactly is usually one the caller is still typing —+ * `[email protected]` on the way to `[email protected]` — and n-grams still match it.*/export async function findPartnerSearchCandidates(searchProvider: PartnerSearchProvider,query: PartnerSearchCandidateQuery,{ throwOnError = false }: FindPartnerSearchCandidatesOptions = {},): Promise<PartnerSearchResult | null> {+ if (isExactEmailQuery(query.query)) {+ const partner = await prisma.partner.findUnique({+ where: { email: query.query },+ select: { id: true },+ });++ if (partner) {+ return null;+ }+ }+try {return await searchProvider.searchCandidates(query);} catch (error) {diff --git a/apps/web/tests/partners/partner-search-find-candidates.test.ts b/apps/web/tests/partners/partner-search-find-candidates.test.tsnew file mode 100644index 0000000000..05668f567f--- /dev/null+++ b/apps/web/tests/partners/partner-search-find-candidates.test.ts@@ -0,0 +1,101 @@+import type { PartnerSearchProvider } from "@/lib/api/partners/search";+import { findPartnerSearchCandidates } from "@/lib/api/partners/search";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ findUnique: vi.fn() }));++vi.mock("@/lib/prisma", () => ({+ prisma: { partner: { findUnique: mocks.findUnique } },+}));++function createProvider(+ searchCandidates = vi.fn().mockResolvedValue({ hits: [{ id: "pge_1" }] }),+) {+ return {+ searchCandidates,+ upsert: vi.fn(),+ delete: vi.fn(),+ } as unknown as PartnerSearchProvider & {+ searchCandidates: typeof searchCandidates;+ };+}++const query = (search: string) => ({+ programId: "prog_1",+ query: search,+ limit: 10,+});++describe("findPartnerSearchCandidates", () => {+ beforeEach(() => {+ mocks.findUnique.mockReset();+ vi.spyOn(console, "error").mockImplementation(() => {});+ });++ it("answers a known email from the database, without calling the provider", async () => {+ mocks.findUnique.mockResolvedValue({ id: "pn_1" });+ const provider = createProvider();++ await expect(+ findPartnerSearchCandidates(provider, query("[email protected]")),+ ).resolves.toBeNull();++ expect(mocks.findUnique).toHaveBeenCalledWith({+ where: { email: "[email protected]" },+ select: { id: true },+ });+ expect(provider.searchCandidates).not.toHaveBeenCalled();+ });++ it("falls back to the provider when no partner has that address", async () => {+ // `[email protected]` on the way to `[email protected]` is a complete address that+ // matches nothing, and n-grams still find the longer one.+ mocks.findUnique.mockResolvedValue(null);+ const provider = createProvider();++ await expect(+ findPartnerSearchCandidates(provider, query("[email protected]")),+ ).resolves.toEqual({ hits: [{ id: "pge_1" }] });++ expect(provider.searchCandidates).toHaveBeenCalledOnce();+ });++ it.each([+ ["half-typed", "steven@"],+ ["domain only", "@dub.co"],+ ["no dot in the domain", "steven@dub"],+ ["a name", "steven tey"],+ ])(+ "does not treat %s as an address, so the database is not queried",+ async (_label, search) => {+ const provider = createProvider();++ await findPartnerSearchCandidates(provider, query(search));++ expect(mocks.findUnique).not.toHaveBeenCalled();+ expect(provider.searchCandidates).toHaveBeenCalledOnce();+ },+ );++ it("degrades to the database search path when the provider throws", async () => {+ const provider = createProvider(+ vi.fn().mockRejectedValue(new Error("down")),+ );++ await expect(+ findPartnerSearchCandidates(provider, query("steven")),+ ).resolves.toBeNull();+ });++ it("surfaces provider failures when the caller opts in", async () => {+ const provider = createProvider(+ vi.fn().mockRejectedValue(new Error("down")),+ );++ await expect(+ findPartnerSearchCandidates(provider, query("steven"), {+ throwOnError: true,+ }),+ ).rejects.toThrow("down");+ });+});diff --git a/apps/web/tests/partners/partner-search-query.test.ts b/apps/web/tests/partners/partner-search-query.test.tsindex 2ea835d9f1..6516ca8522 100644--- a/apps/web/tests/partners/partner-search-query.test.ts+++ b/apps/web/tests/partners/partner-search-query.test.ts@@ -27,27 +27,4 @@ describe("buildPartnerSearchCandidateQuery", () => {])("keeps %s on the database path", (_name, input) => {expect(buildPartnerSearchCandidateQuery(input)).toBeNull();});-- describe("exact email queries", () => {- "keeps %s on the database, which indexes email",- (search) => {- expect(- buildPartnerSearchCandidateQuery({ programId: "prog_1", search }),- ).toBeNull();- },- );-- it.each([- ["half-typed", "steven@"],- ["domain only", "@dub.co"],- ["no dot in the domain", "steven@dub"],- ["two words", "[email protected] other"],- ["a name", "steven"],- ])("sends %s to the provider", (_label, search) => {- expect(- buildPartnerSearchCandidateQuery({ programId: "prog_1", search }),- ).toMatchObject({ query: search });- });- });});