Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Add list polls endpoint to private API (#2736)

Luke Vella8603c7a862bf
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.ts
index 6b7b0672b..aa240709d 100644
--- a/apps/web/src/app/api/private/[...route]/route.test.ts
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -7,6 +7,7 @@ const mockDeletePoll = vi.fn();
const mockCreatePoll = vi.fn();
const mockGetPollResults = vi.fn();
const mockGetPollParticipants = vi.fn();
+const mockListPolls = vi.fn();
vi.mock("@/features/poll/mutations", () => ({
deletePoll: (...args: unknown[]) => mockDeletePoll(...args),
@@ -16,6 +17,7 @@ vi.mock("@/features/poll/mutations", () => ({
vi.mock("@/features/poll/data", () => ({
getPollResults: (...args: unknown[]) => mockGetPollResults(...args),
getPollParticipants: (...args: unknown[]) => mockGetPollParticipants(...args),
+ listPolls: (...args: unknown[]) => mockListPolls(...args),
}));
vi.mock("@rallly/database", () => ({
@@ -66,6 +68,7 @@ import {
getPollParticipantsSuccessResponseSchema,
getPollResultsSuccessResponseSchema,
getPollSuccessResponseSchema,
+ listPollsSuccessResponseSchema,
} from "../schemas";
import { RATE_LIMIT_PER_MINUTE } from "../utils/rate-limit";
import { app } from "./route";
@@ -956,6 +959,179 @@ describe("Private API - /polls", () => {
});
});
+ describe("List polls", () => {
+ const mockListedPoll = {
+ id: "test-poll-id",
+ title: "Team sync",
+ description: "Weekly team meeting",
+ location: "Zoom",
+ timeZone: "Europe/London",
+ status: "open",
+ createdAt: new Date("2025-01-10T12:00:00Z"),
+ user: {
+ name: "John Doe",
+ image: null,
+ },
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T09:00:00Z"),
+ duration: 30,
+ },
+ ],
+ participantCount: 3,
+ };
+
+ it("should return a list of polls", async () => {
+ mockListPolls.mockResolvedValue({
+ polls: [mockListedPoll],
+ nextCursor: null,
+ });
+
+ const res = await app.request("/api/private/polls", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(listPollsSuccessResponseSchema, json);
+
+ expect(json.data).toHaveLength(1);
+ expect(json.data[0].id).toBe("test-poll-id");
+ expect(json.data[0].title).toBe("Team sync");
+ expect(json.data[0].status).toBe("open");
+ expect(json.data[0].participantCount).toBe(3);
+ expect(json.data[0].createdAt).toBe("2025-01-10T12:00:00.000Z");
+ expect(json.data[0].options).toEqual([
+ {
+ id: "opt-1",
+ startTime: "2025-01-15T09:00:00.000Z",
+ duration: 30,
+ },
+ ]);
+ expect(json.data[0].adminUrl).toBe(
+ "https://example.com/poll/test-poll-id",
+ );
+ expect(json.data[0].inviteUrl).toBe(
+ "https://example.com/invite/test-poll-id",
+ );
+ expect(json.nextCursor).toBeNull();
+
+ expect(mockListPolls).toHaveBeenCalledWith({
+ spaceId: "test-space-id",
+ status: undefined,
+ cursor: undefined,
+ limit: 20,
+ });
+ });
+
+ it("should return an empty list when the space has no polls", async () => {
+ mockListPolls.mockResolvedValue({
+ polls: [],
+ nextCursor: null,
+ });
+
+ const res = await app.request("/api/private/polls", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(listPollsSuccessResponseSchema, json);
+ expect(json.data).toEqual([]);
+ expect(json.nextCursor).toBeNull();
+ });
+
+ it("should pass the status filter to the query", async () => {
+ mockListPolls.mockResolvedValue({
+ polls: [],
+ nextCursor: null,
+ });
+
+ const res = await app.request("/api/private/polls?status=open", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ expect(mockListPolls).toHaveBeenCalledWith(
+ expect.objectContaining({
+ spaceId: "test-space-id",
+ status: "open",
+ }),
+ );
+ });
+
+ it("should return 400 for an invalid status", async () => {
+ const res = await app.request("/api/private/polls?status=finalized", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(400);
+ expect(mockListPolls).not.toHaveBeenCalled();
+ });
+
+ it("should pass cursor and limit to the query and return nextCursor", async () => {
+ mockListPolls.mockResolvedValue({
+ polls: [mockListedPoll],
+ nextCursor: "test-poll-id",
+ });
+
+ const res = await app.request(
+ "/api/private/polls?cursor=prev-poll-id&limit=1",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(listPollsSuccessResponseSchema, json);
+ expect(json.nextCursor).toBe("test-poll-id");
+
+ expect(mockListPolls).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cursor: "prev-poll-id",
+ limit: 1,
+ }),
+ );
+ });
+
+ it("should return 400 when limit exceeds the maximum", async () => {
+ const res = await app.request("/api/private/polls?limit=101", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(400);
+ expect(mockListPolls).not.toHaveBeenCalled();
+ });
+
+ it("should return 401 without authorization", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "GET",
+ });
+
+ expect(res.status).toBe(401);
+ });
+ });
+
describe("Get poll results", () => {
it("should return aggregated vote results", async () => {
mockGetPollResults.mockResolvedValue({
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
index 7ddf681c0..ffcc97cee 100644
--- a/apps/web/src/app/api/private/[...route]/route.ts
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -10,7 +10,11 @@ import {
resolver,
validator,
} from "hono-openapi";
-import { getPollParticipants, getPollResults } from "@/features/poll/data";
+import {
+ getPollParticipants,
+ getPollResults,
+ listPolls,
+} from "@/features/poll/data";
import { createPoll, deletePoll } from "@/features/poll/mutations";
import type { AuthorizedSpaceId } from "@/features/space/types";
import { isMaintenanceModeEnabled } from "@/lib/maintenance";
@@ -23,6 +27,8 @@ import {
getPollParticipantsSuccessResponseSchema,
getPollResultsSuccessResponseSchema,
getPollSuccessResponseSchema,
+ listPollsQuerySchema,
+ listPollsSuccessResponseSchema,
} from "../schemas";
import { spaceApiKeyAuth } from "../utils/api-key";
import { apiError } from "../utils/poll";
@@ -367,6 +373,64 @@ app.post(
},
);
+app.get(
+ "/polls",
+ spaceApiKeyAuth,
+ rateLimit,
+ describeRoute({
+ tags: ["Polls"],
+ summary: "List polls",
+ description: [
+ "Lists the polls in the space associated with the API key, sorted by creation date (newest first).",
+ "",
+ "Use the `status` query parameter to only return polls in a given state — for example `status=open` to sweep polls that are still collecting responses. Results are paginated with a cursor: pass the `nextCursor` value from the previous response to fetch the next page.",
+ ].join("\n"),
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: "Successful response",
+ content: {
+ "application/json": {
+ schema: resolver(listPollsSuccessResponseSchema),
+ },
+ },
+ },
+ 400: {
+ description: "Invalid query parameters",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+ },
+ 403: spaceNotProResponse,
+ 429: rateLimitExceededResponse,
+ },
+ }),
+ validator("query", listPollsQuerySchema),
+ async (c) => {
+ const { status, cursor, limit } = c.req.valid("query");
+ const { spaceId } = c.get("apiAuth");
+
+ const { polls, nextCursor } = await listPolls({
+ spaceId,
+ status,
+ cursor,
+ limit,
+ });
+
+ return c.json(
+ listPollsSuccessResponseSchema.parse({
+ data: polls.map((poll) => ({
+ ...toPollResponseBody(poll).data,
+ participantCount: poll.participantCount,
+ })),
+ nextCursor,
+ }),
+ );
+ },
+);
+
app.get(
"/polls/:pollId",
spaceApiKeyAuth,
diff --git a/apps/web/src/app/api/private/schemas.ts b/apps/web/src/app/api/private/schemas.ts
index e13e0be6a..54ea213d9 100644
--- a/apps/web/src/app/api/private/schemas.ts
+++ b/apps/web/src/app/api/private/schemas.ts
@@ -167,32 +167,36 @@ export const pollUserSchema = z
})
.openapi("PollUser");
-export const getPollSuccessResponseSchema = z
+const pollSchema = z
.object({
- data: z.object({
- id: z.string().openapi({ example: "p_123abc" }),
- title: z.string().openapi({ example: "Team sync" }),
- description: z.string().nullable().openapi({
- example: "Pick a time that works for everyone",
- }),
- location: z.string().nullable().openapi({ example: "Zoom" }),
- timezone: z.string().nullable().openapi({ example: "Europe/London" }),
- status: pollStatusSchema,
- createdAt: z
- .string()
- .datetime()
- .openapi({ example: "2025-01-10T12:00:00Z" }),
- user: pollUserSchema.nullable().openapi({
- description: "The poll organizer",
- }),
- options: z.array(pollOptionSchema),
- adminUrl: z
- .string()
- .openapi({ example: "https://example.com/poll/p_123abc" }),
- inviteUrl: z
- .string()
- .openapi({ example: "https://example.com/invite/p_123abc" }),
+ id: z.string().openapi({ example: "p_123abc" }),
+ title: z.string().openapi({ example: "Team sync" }),
+ description: z.string().nullable().openapi({
+ example: "Pick a time that works for everyone",
+ }),
+ location: z.string().nullable().openapi({ example: "Zoom" }),
+ timezone: z.string().nullable().openapi({ example: "Europe/London" }),
+ status: pollStatusSchema,
+ createdAt: z
+ .string()
+ .datetime()
+ .openapi({ example: "2025-01-10T12:00:00Z" }),
+ user: pollUserSchema.nullable().openapi({
+ description: "The poll organizer",
}),
+ options: z.array(pollOptionSchema),
+ adminUrl: z
+ .string()
+ .openapi({ example: "https://example.com/poll/p_123abc" }),
+ inviteUrl: z
+ .string()
+ .openapi({ example: "https://example.com/invite/p_123abc" }),
+ })
+ .openapi("Poll");
+
+export const getPollSuccessResponseSchema = z
+ .object({
+ data: pollSchema,
})
.openapi("GetPollResponse");
@@ -200,6 +204,42 @@ export const getPollSuccessResponseSchema = z
export const createPollSuccessResponseSchema =
getPollSuccessResponseSchema.openapi("CreatePollResponse");
+export const listPollsQuerySchema = z.object({
+ status: pollStatusSchema.optional().openapi({
+ description: "Filter polls by status. Omit to include all statuses.",
+ example: "open",
+ }),
+ cursor: z.string().optional().openapi({
+ description:
+ "Cursor for pagination. Pass the `nextCursor` value from the previous response to fetch the next page.",
+ example: "p_123abc",
+ }),
+ limit: z.coerce.number().int().min(1).max(100).default(20).openapi({
+ description: "Number of polls to return per page (1-100).",
+ example: 20,
+ }),
+});
+
+export const listPollItemSchema = pollSchema
+ .extend({
+ participantCount: z.int().nonnegative().openapi({
+ description: "Number of participants who have responded to the poll",
+ example: 3,
+ }),
+ })
+ .openapi("ListPollItem");
+
+export const listPollsSuccessResponseSchema = z
+ .object({
+ data: z.array(listPollItemSchema),
+ nextCursor: z.string().nullable().openapi({
+ description:
+ "Cursor to fetch the next page. `null` when there are no more results.",
+ example: "p_123abc",
+ }),
+ })
+ .openapi("ListPollsResponse");
+
export const voteCountSchema = z
.object({
type: z.string().openapi({
diff --git a/apps/web/src/features/poll/data.test.ts b/apps/web/src/features/poll/data.test.ts
new file mode 100644
index 000000000..8ba83228d
--- /dev/null
+++ b/apps/web/src/features/poll/data.test.ts
@@ -0,0 +1,105 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const mockFindMany = vi.fn();
+
+vi.mock("@rallly/database", () => ({
+ prisma: {
+ poll: {
+ findMany: (...args: unknown[]) => mockFindMany(...args),
+ },
+ },
+}));
+
+import type { AuthorizedSpaceId } from "@/features/space/types";
+import { listPolls } from "./data";
+
+const spaceId = "test-space-id" as AuthorizedSpaceId;
+
+const makePoll = (id: string) => ({
+ id,
+ title: `Poll ${id}`,
+ description: null,
+ location: null,
+ timeZone: null,
+ status: "open",
+ createdAt: new Date("2025-01-10T12:00:00Z"),
+ user: null,
+ options: [],
+ _count: { participants: 2 },
+});
+
+describe("listPolls", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns all polls with a null nextCursor when there are no more pages", async () => {
+ mockFindMany.mockResolvedValue([makePoll("p1"), makePoll("p2")]);
+
+ const result = await listPolls({ spaceId, limit: 20 });
+
+ expect(result.polls).toHaveLength(2);
+ expect(result.polls[0]?.participantCount).toBe(2);
+ expect(result.nextCursor).toBeNull();
+ });
+
+ it("slices to the limit and returns the last item's id as nextCursor", async () => {
+ mockFindMany.mockResolvedValue([
+ makePoll("p1"),
+ makePoll("p2"),
+ makePoll("p3"),
+ ]);
+
+ const result = await listPolls({ spaceId, limit: 2 });
+
+ expect(result.polls).toHaveLength(2);
+ expect(result.polls.map((poll) => poll.id)).toEqual(["p1", "p2"]);
+ expect(result.nextCursor).toBe("p2");
+
+ expect(mockFindMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ take: 3,
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ }),
+ );
+ });
+
+ it("scopes the query to the space and excludes deleted polls", async () => {
+ mockFindMany.mockResolvedValue([]);
+
+ await listPolls({ spaceId, limit: 20 });
+
+ expect(mockFindMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { spaceId, deleted: false },
+ }),
+ );
+ });
+
+ it("applies the status filter when provided", async () => {
+ mockFindMany.mockResolvedValue([]);
+
+ await listPolls({ spaceId, status: "closed", limit: 20 });
+
+ expect(mockFindMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { spaceId, deleted: false, status: "closed" },
+ }),
+ );
+ });
+
+ it("resumes from the cursor when provided", async () => {
+ mockFindMany.mockResolvedValue([]);
+
+ await listPolls({ spaceId, cursor: "p2", limit: 20 });
+
+ expect(mockFindMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cursor: { id: "p2" },
+ skip: 1,
+ }),
+ );
+ });
+});
diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.ts
index b793101a3..8cecc3041 100644
--- a/apps/web/src/features/poll/data.ts
+++ b/apps/web/src/features/poll/data.ts
@@ -153,6 +153,73 @@ export async function getPollParticipants({
};
}
+export async function listPolls({
+ spaceId,
+ status,
+ cursor,
+ limit,
+}: {
+ spaceId: AuthorizedSpaceId;
+ status?: PollStatus;
+ cursor?: string;
+ limit: number;
+}) {
+ // Fetch one extra row to determine whether there is a next page
+ const polls = await prisma.poll.findMany({
+ where: {
+ spaceId,
+ deleted: false,
+ ...(status && { status }),
+ },
+ select: {
+ id: true,
+ title: true,
+ description: true,
+ location: true,
+ timeZone: true,
+ status: true,
+ createdAt: true,
+ user: {
+ select: {
+ name: true,
+ image: true,
+ },
+ },
+ options: {
+ select: {
+ id: true,
+ startTime: true,
+ duration: true,
+ },
+ orderBy: {
+ startTime: "asc",
+ },
+ },
+ _count: {
+ select: {
+ participants: {
+ where: { deleted: false },
+ },
+ },
+ },
+ },
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ take: limit + 1,
+ ...(cursor && { cursor: { id: cursor }, skip: 1 }),
+ });
+
+ const hasMore = polls.length > limit;
+ const page = hasMore ? polls.slice(0, limit) : polls;
+
+ return {
+ polls: page.map(({ _count, ...poll }) => ({
+ ...poll,
+ participantCount: _count.participants,
+ })),
+ nextCursor: hasMore ? (page[page.length - 1]?.id ?? null) : null,
+ };
+}
+
type PollFilters = {
status?: PollStatus;
page?: number;