Skip to content

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

✨ Represent options, results and participants explicitly in /api/v1 (#3216)

Luke Vellaa65f6a73bcf1
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 a336210b9..edbe3d47d 100644
--- a/apps/web/src/app/api/private/[...route]/route.test.ts
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -1541,6 +1541,7 @@ describe("Private API - /polls", () => {
duration: 30,
votes: [
{ type: "yes", count: 1 },
+ { type: "ifNeedBe", count: 0 },
{ type: "no", count: 2 },
],
score: 1001,
@@ -1550,7 +1551,11 @@ describe("Private API - /polls", () => {
id: "opt-3",
startTime: new Date("2025-01-15T11:00:00Z"),
duration: 30,
- votes: [],
+ votes: [
+ { type: "yes", count: 0 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 0,
isTopChoice: false,
},
@@ -1573,6 +1578,17 @@ describe("Private API - /polls", () => {
expect(json.data.participantCount).toBe(5);
expect(json.data.highScore).toBe(4003);
expect(json.data.options).toHaveLength(3);
+ // The frozen shape is a sparse array of the types that received votes.
+ expect(json.data.options[0].votes).toEqual([
+ { type: "yes", count: 3 },
+ { type: "ifNeedBe", count: 1 },
+ { type: "no", count: 1 },
+ ]);
+ expect(json.data.options[1].votes).toEqual([
+ { type: "yes", count: 1 },
+ { type: "no", count: 2 },
+ ]);
+ expect(json.data.options[2].votes).toEqual([]);
expect(mockGetPollResults).toHaveBeenCalledWith({
pollId: "test-poll-id",
@@ -1591,7 +1607,11 @@ describe("Private API - /polls", () => {
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 1 }],
+ votes: [
+ { type: "yes", count: 1 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 1001,
isTopChoice: true,
},
@@ -1622,7 +1642,11 @@ describe("Private API - /polls", () => {
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 2 }],
+ votes: [
+ { type: "yes", count: 2 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 2002,
isTopChoice: true,
},
@@ -1630,7 +1654,11 @@ describe("Private API - /polls", () => {
id: "opt-2",
startTime: new Date("2025-01-15T10:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 2 }],
+ votes: [
+ { type: "yes", count: 2 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 2002,
isTopChoice: true,
},
@@ -1664,7 +1692,11 @@ describe("Private API - /polls", () => {
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 4 }],
+ votes: [
+ { type: "yes", count: 4 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 4004,
isTopChoice: false,
},
@@ -1675,6 +1707,7 @@ describe("Private API - /polls", () => {
votes: [
{ type: "yes", count: 3 },
{ type: "ifNeedBe", count: 2 },
+ { type: "no", count: 0 },
],
score: 5003,
isTopChoice: true,
@@ -1713,6 +1746,7 @@ describe("Private API - /polls", () => {
votes: [
{ type: "yes", count: 3 },
{ type: "ifNeedBe", count: 1 },
+ { type: "no", count: 0 },
],
score: 4003,
isTopChoice: false,
@@ -1721,7 +1755,11 @@ describe("Private API - /polls", () => {
id: "opt-2",
startTime: new Date("2025-01-15T10:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 4 }],
+ votes: [
+ { type: "yes", count: 4 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 4004,
isTopChoice: true,
},
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
index 291fe795d..1e59c7e66 100644
--- a/apps/web/src/app/api/private/[...route]/route.ts
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -746,6 +746,8 @@ app.get(
options: data.options.map((option) => ({
...option,
startTime: option.startTime.toISOString(),
+ // The frozen shape omits types that received no votes.
+ votes: option.votes.filter((vote) => vote.count > 0),
})),
},
}),
diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.ts
index b75fc7f6c..30be8744b 100644
--- a/apps/web/src/app/api/v1/[...route]/route.test.ts
+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts
@@ -167,6 +167,7 @@ describe("API v1 - /polls", () => {
location: null,
timeZone: null,
status: "open",
+ kind: "date",
createdAt: new Date("2025-01-10T12:00:00Z"),
user: {
name: "Test User",
@@ -649,6 +650,7 @@ describe("API v1 - /polls", () => {
location: null,
timeZone: "Europe/London",
status: "open",
+ kind: "time",
createdAt: new Date("2025-01-10T12:00:00Z"),
user: { name: "Test User", image: null },
options: [
@@ -1026,9 +1028,16 @@ describe("API v1 - /polls", () => {
"ErrorResponse",
]),
);
- expect(schemas.OptionResult.properties.score.description).toContain(
- "Ranking score",
+ // Option shapes are unions keyed by the poll kind; both variants are
+ // named components and the score description states it is opaque.
+ expect(schemas.OptionResult.anyOf).toEqual([
+ { $ref: "#/components/schemas/DateOptionResult" },
+ { $ref: "#/components/schemas/TimeOptionResult" },
+ ]);
+ expect(schemas.TimeOptionResult.properties.score.description).toContain(
+ "Opaque ranking value",
);
+ expect(schemas.DateOptionResult.properties.date.format).toBe("date");
expect(schemas.Poll.properties.title.example).toBe("Team sync");
expect(
json.paths["/api/v1/polls"].post.requestBody.content["application/json"]
@@ -1073,6 +1082,13 @@ describe("API v1 - /polls", () => {
}
});
+ it("should serve the spec without a no-store header", async () => {
+ const res = await app.request("/api/v1/openapi");
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("Cache-Control")).toBeNull();
+ });
+
it("should not serve a docs page (the reference lives in the docs site)", async () => {
const res = await app.request("/api/v1/docs");
@@ -1088,6 +1104,7 @@ describe("API v1 - /polls", () => {
location: null,
timeZone: null,
status: "closed",
+ kind: "date",
createdAt: new Date("2025-01-10T12:00:00Z"),
user: { name: "Test User", image: null },
options: [],
@@ -1285,6 +1302,7 @@ describe("API v1 - /polls", () => {
location: "Zoom",
timeZone: "Europe/London",
status: "open",
+ kind: "time",
createdAt: new Date("2025-01-10T12:00:00Z"),
user: {
name: "John Doe",
@@ -1323,6 +1341,7 @@ describe("API v1 - /polls", () => {
expect(json.data.location).toBe("Zoom");
expect(json.data.timezone).toBe("Europe/London");
expect(json.data.status).toBe("open");
+ expect(json.data.kind).toBe("time");
expect(json.data.createdAt).toBe("2025-01-10T12:00:00.000Z");
expect(json.data.user).toEqual({
name: "John Doe",
@@ -1345,6 +1364,42 @@ describe("API v1 - /polls", () => {
});
});
+ it("should return calendar dates instead of datetimes for date polls", async () => {
+ mockGetPollWithOptions.mockResolvedValue({
+ ...mockPoll,
+ timeZone: null,
+ kind: "date",
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T00:00:00.000Z"),
+ duration: 0,
+ },
+ {
+ id: "opt-2",
+ startTime: new Date("2025-01-16T00:00:00.000Z"),
+ duration: 0,
+ },
+ ],
+ });
+
+ const res = await app.request("/api/v1/polls/test-poll-id", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(pollResponseSchema, json);
+ expect(json.data.kind).toBe("date");
+ expect(json.data.options).toEqual([
+ { id: "opt-1", date: "2025-01-15" },
+ { id: "opt-2", date: "2025-01-16" },
+ ]);
+ });
+
it("should return poll without user when user is null", async () => {
mockGetPollWithOptions.mockResolvedValue({
...mockPoll,
@@ -1410,6 +1465,7 @@ describe("API v1 - /polls", () => {
location: "Zoom",
timeZone: "Europe/London",
status: "open",
+ kind: "time",
createdAt: new Date("2025-01-10T12:00:00Z"),
user: {
name: "John Doe",
@@ -1447,6 +1503,7 @@ describe("API v1 - /polls", () => {
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].kind).toBe("time");
expect(json.data[0].createdAt).toBe("2025-01-10T12:00:00.000Z");
expect(json.data[0].options).toEqual([
{
@@ -1471,6 +1528,41 @@ describe("API v1 - /polls", () => {
});
});
+ it("should return calendar dates for date polls in the list", async () => {
+ mockListPolls.mockResolvedValue({
+ polls: [
+ {
+ ...mockListedPoll,
+ timeZone: null,
+ kind: "date",
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T00:00:00.000Z"),
+ duration: 0,
+ },
+ ],
+ },
+ ],
+ nextCursor: null,
+ });
+
+ const res = await app.request("/api/v1/polls", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(listPollsSuccessResponseSchema, json);
+ expect(json.data[0].kind).toBe("date");
+ expect(json.data[0].options).toEqual([
+ { id: "opt-1", date: "2025-01-15" },
+ ]);
+ });
+
it("should return an empty list when the space has no polls", async () => {
mockListPolls.mockResolvedValue({
polls: [],
@@ -1579,6 +1671,7 @@ describe("API v1 - /polls", () => {
it("should return aggregated vote results", async () => {
mockGetPollResults.mockResolvedValue({
pollId: "test-poll-id",
+ kind: "time",
status: "open",
participantCount: 5,
highScore: 4003,
@@ -1601,6 +1694,7 @@ describe("API v1 - /polls", () => {
duration: 30,
votes: [
{ type: "yes", count: 1 },
+ { type: "ifNeedBe", count: 0 },
{ type: "no", count: 2 },
],
score: 1001,
@@ -1610,7 +1704,11 @@ describe("API v1 - /polls", () => {
id: "opt-3",
startTime: new Date("2025-01-15T11:00:00Z"),
duration: 30,
- votes: [],
+ votes: [
+ { type: "yes", count: 0 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 0,
isTopChoice: false,
},
@@ -1632,7 +1730,26 @@ describe("API v1 - /polls", () => {
expect(json.data.status).toBe("open");
expect(json.data.participantCount).toBe(5);
expect(json.data.highScore).toBe(4003);
+ expect(json.data.kind).toBe("time");
expect(json.data.options).toHaveLength(3);
+ expect(json.data.options[0]).toEqual({
+ id: "opt-1",
+ startTime: "2025-01-15T09:00:00.000Z",
+ duration: 30,
+ votes: [
+ { type: "yes", count: 3 },
+ { type: "ifNeedBe", count: 1 },
+ { type: "no", count: 1 },
+ ],
+ score: 4003,
+ isTopChoice: true,
+ });
+ // Every vote type is present even when nobody chose it.
+ expect(json.data.options[2].votes).toEqual([
+ { type: "yes", count: 0 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ]);
expect(mockGetPollResults).toHaveBeenCalledWith({
pollId: "test-poll-id",
@@ -1640,9 +1757,57 @@ describe("API v1 - /polls", () => {
});
});
+ it("should return calendar dates for date poll results", async () => {
+ mockGetPollResults.mockResolvedValue({
+ pollId: "test-poll-id",
+ kind: "date",
+ status: "open",
+ participantCount: 2,
+ highScore: 2002,
+ options: [
+ {
+ id: "opt-1",
+ startTime: new Date("2025-01-15T00:00:00.000Z"),
+ duration: 0,
+ votes: [
+ { type: "yes", count: 2 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
+ score: 2002,
+ isTopChoice: true,
+ },
+ ],
+ });
+
+ const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(getPollResultsSuccessResponseSchema, json);
+ expect(json.data.kind).toBe("date");
+ expect(json.data.options[0]).toEqual({
+ id: "opt-1",
+ date: "2025-01-15",
+ votes: [
+ { type: "yes", count: 2 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
+ score: 2002,
+ isTopChoice: true,
+ });
+ });
+
it("should return the poll status for closed polls", async () => {
mockGetPollResults.mockResolvedValue({
pollId: "test-poll-id",
+ kind: "time",
status: "closed",
participantCount: 1,
highScore: 1001,
@@ -1651,7 +1816,11 @@ describe("API v1 - /polls", () => {
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 1 }],
+ votes: [
+ { type: "yes", count: 1 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 1001,
isTopChoice: true,
},
@@ -1674,6 +1843,7 @@ describe("API v1 - /polls", () => {
it("should handle ties for top choice", async () => {
mockGetPollResults.mockResolvedValue({
pollId: "test-poll-id",
+ kind: "time",
status: "open",
participantCount: 2,
highScore: 2002,
@@ -1682,7 +1852,11 @@ describe("API v1 - /polls", () => {
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 2 }],
+ votes: [
+ { type: "yes", count: 2 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 2002,
isTopChoice: true,
},
@@ -1690,7 +1864,11 @@ describe("API v1 - /polls", () => {
id: "opt-2",
startTime: new Date("2025-01-15T10:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 2 }],
+ votes: [
+ { type: "yes", count: 2 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 2002,
isTopChoice: true,
},
@@ -1716,6 +1894,7 @@ describe("API v1 - /polls", () => {
it("should prioritize total availability over yes votes", async () => {
mockGetPollResults.mockResolvedValue({
pollId: "test-poll-id",
+ kind: "time",
status: "open",
participantCount: 5,
highScore: 5003,
@@ -1724,7 +1903,11 @@ describe("API v1 - /polls", () => {
id: "opt-1",
startTime: new Date("2025-01-15T09:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 4 }],
+ votes: [
+ { type: "yes", count: 4 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 4004,
isTopChoice: false,
},
@@ -1735,6 +1918,7 @@ describe("API v1 - /polls", () => {
votes: [
{ type: "yes", count: 3 },
{ type: "ifNeedBe", count: 2 },
+ { type: "no", count: 0 },
],
score: 5003,
isTopChoice: true,
@@ -1762,6 +1946,7 @@ describe("API v1 - /polls", () => {
it("should use yes votes as tiebreaker when availability is equal", async () => {
mockGetPollResults.mockResolvedValue({
pollId: "test-poll-id",
+ kind: "time",
status: "open",
participantCount: 4,
highScore: 4004,
@@ -1773,6 +1958,7 @@ describe("API v1 - /polls", () => {
votes: [
{ type: "yes", count: 3 },
{ type: "ifNeedBe", count: 1 },
+ { type: "no", count: 0 },
],
score: 4003,
isTopChoice: false,
@@ -1781,7 +1967,11 @@ describe("API v1 - /polls", () => {
id: "opt-2",
startTime: new Date("2025-01-15T10:00:00Z"),
duration: 30,
- votes: [{ type: "yes", count: 4 }],
+ votes: [
+ { type: "yes", count: 4 },
+ { type: "ifNeedBe", count: 0 },
+ { type: "no", count: 0 },
+ ],
score: 4004,
isTopChoice: true,
},
@@ -1887,24 +2077,99 @@ describe("API v1 - /polls", () => {
});
});
- describe("Get poll participants", () => {
- it("should return participants", async () => {
+ describe("Caching", () => {
+ it("should mark every key-scoped response no-store", async () => {
+ mockGetPollParticipants.mockResolvedValue({
+ pollId: "test-poll-id",
+ participants: [],
+ nextCursor: null,
+ });
+ mockListPolls.mockResolvedValue({ polls: [], nextCursor: null });
+
+ const responses = await Promise.all([
+ app.request("/api/v1/polls/test-poll-id/participants", {
+ headers: { Authorization: `Bearer ${testApiKey}` },
+ }),
+ app.request("/api/v1/polls", {
+ headers: { Authorization: `Bearer ${testApiKey}` },
+ }),
+ app.request("/api/v1/polls/test-poll-id"),
+ ]);
+
+ for (const res of responses) {
+ expect(res.headers.get("Cache-Control")).toBe("no-store");
+ }
+ });
+ });
+
+ describe("List poll participants", () => {
+ const participants = [
+ {
+ id: "participant-1",
+ name: "Alice",
+ email: "[email protected]",
+ createdAt: new Date("2025-01-10T10:00:00Z"),
+ votes: [
+ { optionId: "opt-1", type: "yes" },
+ { optionId: "opt-2", type: "no" },
+ ],
+ },
+ {
+ id: "participant-2",
+ name: "Bob",
+ email: null,
+ createdAt: new Date("2025-01-10T11:00:00Z"),
+ votes: [{ optionId: "opt-1", type: "ifNeedBe" }],
+ },
+ ];
+
+ it("should return participants with their votes in the list shape", async () => {
+ mockGetPollParticipants.mockResolvedValue({
+ pollId: "test-poll-id",
+ participants,
+ nextCursor: null,
+ });
+
+ const res = await app.request("/api/v1/polls/test-poll-id/participants", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(getPollParticipantsSuccessResponseSchema, json);
+
+ expect(json.data).toHaveLength(2);
+ expect(json.data[0]).toEqual({
+ id: "participant-1",
+ name: "Alice",
+ email: "[email protected]",
+ createdAt: "2025-01-10T10:00:00.000Z",
+ votes: [
+ { optionId: "opt-1", type: "yes" },
+ { optionId: "opt-2", type: "no" },
+ ],
+ });
+ expect(json.data[1].email).toBeNull();
+ expect(json.nextCursor).toBeNull();
+
+ expect(mockGetPollParticipants).toHaveBeenCalledWith({
+ pollId: "test-poll-id",
+ spaceId: "test-space-id",
+ cursor: undefined,
+ limit: 50,
+ });
+ });
+
+ it("should pass through a vote type the schema does not know", async () => {
mockGetPollParticipants.mockResolvedValue({
pollId: "test-poll-id",
participants: [
- {
- id: "participant-1",
- name: "Alice",
- email: "[email protected]",
- createdAt: new Date("2025-01-10T10:00:00Z"),
- },
- {
- id: "participant-2",
- name: "Bob",
- email: null,
- createdAt: new Date("2025-01-10T11:00:00Z"),
- },
+ { ...participants[0], votes: [{ optionId: "opt-1", type: "maybe" }] },
],
+ nextCursor: null,
});
const res = await app.request("/api/v1/polls/test-poll-id/participants", {
@@ -1917,20 +2182,64 @@ describe("API v1 - /polls", () => {
expect(res.status).toBe(200);
const json = await res.json();
expectMatchesContract(getPollParticipantsSuccessResponseSchema, json);
+ expect(json.data[0].votes).toEqual([
+ { optionId: "opt-1", type: "maybe" },
+ ]);
+ });
- expect(json.data.pollId).toBe("test-poll-id");
- expect(json.data.participants).toHaveLength(2);
+ it("should pass the cursor and limit through and return the next cursor", async () => {
+ mockGetPollParticipants.mockResolvedValue({
+ pollId: "test-poll-id",
+ participants: [participants[1]],
+ nextCursor: "participant-2",
+ });
+
+ const res = await app.request(
+ "/api/v1/polls/test-poll-id/participants?cursor=participant-1&limit=1",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expectMatchesContract(getPollParticipantsSuccessResponseSchema, json);
+ expect(json.data.map((p: { id: string }) => p.id)).toEqual([
+ "participant-2",
+ ]);
+ expect(json.nextCursor).toBe("participant-2");
expect(mockGetPollParticipants).toHaveBeenCalledWith({
pollId: "test-poll-id",
spaceId: "test-space-id",
+ cursor: "participant-1",
+ limit: 1,
});
});
+ it("should return 400 when limit is out of range", async () => {
+ const res = await app.request(
+ "/api/v1/polls/test-poll-id/participants?limit=500",
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ },
+ );
+
+ await expectErrorEnvelope(res, { status: 400, code: "VALIDATION_ERROR" });
+ expect(mockGetPollParticipants).not.toHaveBeenCalled();
+ });
+
it("should return empty array when no participants", async () => {
mockGetPollParticipants.mockResolvedValue({
pollId: "test-poll-id",
participants: [],
+ nextCursor: null,
});
const res = await app.request("/api/v1/polls/test-poll-id/participants", {
@@ -1943,8 +2252,8 @@ describe("API v1 - /polls", () => {
expect(res.status).toBe(200);
const json = await res.json();
- expect(json.data.pollId).toBe("test-poll-id");
- expect(json.data.participants).toEqual([]);
+ expect(json.data).toEqual([]);
+ expect(json.nextCursor).toBeNull();
});
it("should return 404 when poll not found", async () => {
diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.ts
index 57fa24ab3..3e85c9526 100644
--- a/apps/web/src/app/api/v1/[...route]/route.ts
+++ b/apps/web/src/app/api/v1/[...route]/route.ts
@@ -48,6 +48,7 @@ import {
errorResponseSchema,
getPollParticipantsSuccessResponseSchema,
getPollResultsSuccessResponseSchema,
+ listParticipantsQuerySchema,
listPollsQuerySchema,
listPollsSuccessResponseSchema,
patchPollInputSchema,
@@ -72,6 +73,27 @@ const app = new Hono<Env>().basePath("/api/v1");
// before, so the frozen /api/private route is unaffected.
loadVendor("zod", { toOpenAPISchema: toOpenApiSchema });
+type PollKind = "date" | "time";
+
+// All-day options are stored as UTC midnight of the calendar date, so the
+// date is the first ten characters of the ISO string.
+function toOptionResponse(
+ kind: PollKind,
+ option: { id: string; startTime: Date; duration: number },
+) {
+ if (kind === "date") {
+ return {
+ id: option.id,
+ date: option.startTime.toISOString().slice(0, 10),
+ };
+ }
+ return {
+ id: option.id,
+ startTime: option.startTime.toISOString(),
+ duration: option.duration,
+ };
+}
+
function toPollResponseBody(poll: {
id: string;
title: string;
@@ -79,6 +101,7 @@ function toPollResponseBody(poll: {
location: string | null;
timeZone: string | null;
status: string;
+ kind: PollKind;
createdAt: Date;
user: { name: string; image: string | null } | null;
options: { id: string; startTime: Date; duration: number }[];
@@ -91,6 +114,7 @@ function toPollResponseBody(poll: {
location: poll.location,
timezone: poll.timeZone,
status: poll.status,
+ kind: poll.kind,
createdAt: poll.createdAt.toISOString(),
user: poll.user
? {
@@ -98,11 +122,9 @@ function toPollResponseBody(poll: {
image: poll.user.image,
}
: null,
- options: poll.options.map((option) => ({
- id: option.id,
- startTime: option.startTime.toISOString(),
- duration: option.duration,
- })),
+ options: poll.options.map((option) =>
+ toOptionResponse(poll.kind, option),
+ ),
adminUrl: absoluteUrl(`/poll/${poll.id}`),
inviteUrl: shortUrl(`/invite/${poll.id}`),
},
@@ -111,6 +133,17 @@ function toPollResponseBody(poll: {
app.use("*", wideEvent({ service: "api-v1" }));
+// Every response except the public spec is scoped to an API key, so nothing
+// in between may store it.
+app.use("/polls/*", async (c, next) => {
+ await next();
+ c.res.headers.set("Cache-Control", "no-store");
+});
+app.use("/polls", async (c, next) => {
+ await next();
+ c.res.headers.set("Cache-Control", "no-store");
+});
+
app.use("*", async (c, next) => {
if (isMaintenanceModeEnabled()) {
return c.json(
@@ -207,6 +240,18 @@ async function buildOpenApiSpec() {
"",
"If the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.",
"",
+ "## Dates and times",
+ "",
+ "Every poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timezone` (or the viewer's) for display. Timestamps such as `createdAt` are always ISO 8601 instants in UTC.",
+ "",
+ "## Enums",
+ "",
+ "Vote types are an open set. The built-in values are `yes`, `ifNeedBe` and `no`; new types may be added without a version change, so clients must tolerate values they do not recognise. `status` and `kind` are closed sets.",
+ "",
+ "## Lists",
+ "",
+ "Every list endpoint returns the items in `data` and a `nextCursor` beside it. Pass `nextCursor` as the `cursor` query parameter to fetch the next page; it is `null` on the last page.",
+ "",
"## Errors",
"",
'Every failure is `application/json` with the shape `{ "error": { "code", "message" } }`. `code` is stable and safe to branch on; `message` is human-readable and may change. `VALIDATION_ERROR` messages name each offending field.',
@@ -700,8 +745,11 @@ app.get(
describeRoute({
tags: ["Polls"],
summary: "Get poll results",
- description:
- "Retrieves aggregated voting results for a poll. Returns vote counts per option without individual participant data.",
+ description: [
+ "Retrieves aggregated voting results for a poll: vote counts per option without individual participant data. Use `GET /polls/:pollId/participants` for per-person availability.",
+ "",
+ "`votes` lists every vote type the poll offers with its count, zero included. `score` is an opaque ranking value: sort by it to order options from best to worst, and use `isTopChoice` or `highScore` to find the leading options. Its formula is not part of the contract, so do not decode it, compare it across polls or threshold on it.",
+ ].join("\n"),
security: [{ bearerAuth: [] }],
responses: {
200: {
@@ -744,11 +792,17 @@ app.get(
return c.json(
getPollResultsSuccessResponseSchema.parse({
data: {
- ...data,
+ pollId: data.pollId,
+ kind: data.kind,
+ status: data.status,
+ participantCount: data.participantCount,
options: data.options.map((option) => ({
- ...option,
- startTime: option.startTime.toISOString(),
+ ...toOptionResponse(data.kind, option),
+ votes: option.votes,
+ score: option.score,
+ isTopChoice: option.isTopChoice,
})),
+ highScore: data.highScore,
},
}),
);
@@ -761,9 +815,12 @@ app.get(
rateLimit,
describeRoute({
tags: ["Polls"],
- summary: "Get poll participants",
- description:
- "Retrieves all participants and their votes for a poll. The poll must belong to the space associated with the API key.",
+ summary: "List poll participants",
+ description: [
+ "Lists the participants of a poll with their votes, oldest response first. The poll must belong to the space associated with the API key.",
+ "",
+ "Each participant's `votes` pairs an `optionId` from the poll with the answer they gave, so this is the endpoint for per-person availability. 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: {
@@ -774,6 +831,14 @@ app.get(
},
},
},
+ 400: {
+ description: "Invalid query parameters",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+ },
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -787,11 +852,13 @@ app.get(
},
},
}),
+ validator("query", listParticipantsQuerySchema, validationHook),
async (c) => {
const { pollId } = c.req.param();
+ const { cursor, limit } = c.req.valid("query");
const { spaceId } = c.get("apiAuth");
- const data = await getPollParticipants({ pollId, spaceId });
+ const data = await getPollParticipants({ pollId, spaceId, cursor, limit });
if (!data) {
return c.json(
@@ -805,13 +872,14 @@ app.get(
return c.json(
getPollParticipantsSuccessResponseSchema.parse({
- data: {
- pollId: data.pollId,
- participants: data.participants.map((participant) => ({
- ...participant,
- createdAt: participant.createdAt.toISOString(),
- })),
- },
+ data: data.participants.map((participant) => ({
+ id: participant.id,
+ name: participant.name,
+ email: participant.email,
+ createdAt: participant.createdAt.toISOString(),
+ votes: participant.votes,
+ })),
+ nextCursor: data.nextCursor,
}),
);
},
diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.ts
index 6195313bf..4aad26a97 100644
--- a/apps/web/src/app/api/v1/schemas.ts
+++ b/apps/web/src/app/api/v1/schemas.ts
@@ -163,16 +163,51 @@ export const pollStatusSchema = z
.enum(["open", "closed", "scheduled", "canceled"])
.meta({ id: "PollStatus" });
-export const pollOptionSchema = z
+export const pollKindSchema = z.enum(["date", "time"]).meta({
+ id: "PollKind",
+ description:
+ "Whether the poll offers calendar dates (`date`) or time slots (`time`). Determines which option shape the poll uses: every option in a `date` poll has a `date`, every option in a `time` poll has a `startTime` and `duration`.",
+ example: "time",
+});
+
+export const dateOptionSchema = z
+ .object({
+ id: z.string().meta({ example: "opt_abc123" }),
+ date: z.iso.date().meta({
+ description:
+ "Calendar date in YYYY-MM-DD format. All-day options are floating dates with no time component and no timezone.",
+ example: "2025-01-15",
+ }),
+ })
+ .meta({
+ id: "DateOption",
+ description: "An all-day option. Only present in polls with `kind: date`.",
+ });
+
+export const timeOptionSchema = z
.object({
id: z.string().meta({ example: "opt_abc123" }),
- startTime: z.iso.datetime().meta({ example: "2025-01-15T09:00:00Z" }),
- duration: z.number().int().meta({
- description: "Duration in minutes. 0 indicates an all-day option.",
+ startTime: z.iso.datetime().meta({
+ description: "Start of the slot as an ISO 8601 instant in UTC.",
+ example: "2025-01-15T09:00:00.000Z",
+ }),
+ duration: z.int().positive().meta({
+ description: "Duration in minutes.",
example: 30,
}),
})
- .meta({ id: "PollOption" });
+ .meta({
+ id: "TimeOption",
+ description: "A time slot. Only present in polls with `kind: time`.",
+ });
+
+export const pollOptionSchema = z
+ .union([dateOptionSchema, timeOptionSchema])
+ .meta({
+ id: "PollOption",
+ description:
+ "A poll option. The shape follows the poll's `kind`: a `DateOption` for `date` polls, a `TimeOption` for `time` polls.",
+ });
export const pollUserSchema = z
.object({
@@ -194,6 +229,7 @@ const pollSchema = z
location: z.string().nullable().meta({ example: "Zoom" }),
timezone: z.string().nullable().meta({ example: "Europe/London" }),
status: pollStatusSchema,
+ kind: pollKindSchema,
createdAt: z.string().datetime().meta({ example: "2025-01-10T12:00:00Z" }),
user: pollUserSchema.nullable().meta({
description: "The poll organizer",
@@ -258,46 +294,71 @@ export const listPollsSuccessResponseSchema = z
})
.meta({ id: "ListPollsResponse" });
+// Open enum: the response schema accepts any string so a vote type added
+// later never fails serialization. The built-in set is documented, not enforced.
+export const voteTypeSchema = z.string().meta({
+ id: "VoteType",
+ description:
+ "A participant's answer for an option. The built-in types are `yes` (available), `ifNeedBe` (available if needed) and `no` (unavailable). New types may be added without a version change, so treat unknown values as a vote of an unfamiliar type rather than an error.",
+ example: "yes",
+});
+
export const voteCountSchema = z
.object({
- type: z.string().meta({
- description: "The vote type (e.g., yes, ifNeedBe, no)",
- example: "yes",
- }),
+ type: voteTypeSchema,
count: z.int().nonnegative().meta({
- description: "Number of votes of this type",
- example: 5,
+ description: "Number of participants who gave this answer.",
+ example: 3,
}),
})
.meta({ id: "VoteCount" });
+const optionResultFields = {
+ votes: z.array(voteCountSchema).meta({
+ description:
+ "One entry per vote type the poll offers, in display order, always present with `count: 0` when nobody chose it.",
+ }),
+ score: z.int().nonnegative().meta({
+ description:
+ "Opaque ranking value: higher is better. Only comparable between options in the same response. The formula is not part of the contract and may change; do not decode it into vote counts, compare it across polls or threshold on it. Use `votes` for counts.",
+ example: 5004,
+ }),
+ isTopChoice: z.boolean().meta({
+ description:
+ "Whether this option has the highest `score` in the poll. Several options share the flag when they tie. Always `false` when nobody has voted.",
+ example: true,
+ }),
+};
+
+export const dateOptionResultSchema = dateOptionSchema
+ .extend(optionResultFields)
+ .meta({
+ id: "DateOptionResult",
+ description:
+ "Results for an all-day option. Only present in polls with `kind: date`.",
+ });
+
+export const timeOptionResultSchema = timeOptionSchema
+ .extend(optionResultFields)
+ .meta({
+ id: "TimeOptionResult",
+ description:
+ "Results for a time slot. Only present in polls with `kind: time`.",
+ });
+
export const optionResultSchema = z
- .object({
- id: z.string().meta({ example: "opt_abc123" }),
- startTime: z.iso.datetime().meta({ example: "2025-01-15T09:00:00Z" }),
- duration: z.int().nonnegative().meta({
- description: "Duration in minutes. 0 indicates an all-day option.",
- example: 30,
- }),
- votes: z.array(voteCountSchema).meta({
- description: "Array of vote counts by type",
- }),
- score: z.int().nonnegative().meta({
- description:
- "Ranking score: (yes + ifNeedBe) * 1000 + yes. Total availability is primary, yes votes break ties.",
- example: 5004,
- }),
- isTopChoice: z.boolean().meta({
- description: "Whether this option has the highest score",
- example: true,
- }),
- })
- .meta({ id: "OptionResult" });
+ .union([dateOptionResultSchema, timeOptionResultSchema])
+ .meta({
+ id: "OptionResult",
+ description:
+ "Results for one option. The shape follows the poll's `kind`: a `DateOptionResult` for `date` polls, a `TimeOptionResult` for `time` polls.",
+ });
export const getPollResultsSuccessResponseSchema = z
.object({
data: z.object({
pollId: z.string().meta({ example: "p_123abc" }),
+ kind: pollKindSchema,
status: pollStatusSchema.meta({
description:
"Current poll status. Polls close automatically when all options are in the past.",
@@ -309,27 +370,53 @@ export const getPollResultsSuccessResponseSchema = z
}),
options: z.array(optionResultSchema),
highScore: z.int().nonnegative().meta({
- description: "Highest score across all options",
- example: 7,
+ description:
+ "The highest `score` among the options. Opaque like `score`: use it to identify the leading options, not as a measurement.",
+ example: 5004,
}),
}),
})
.meta({ id: "GetPollResultsResponse" });
+export const participantVoteSchema = z
+ .object({
+ optionId: z.string().meta({ example: "opt_abc123" }),
+ type: voteTypeSchema,
+ })
+ .meta({ id: "ParticipantVote" });
+
export const participantSchema = z
.object({
id: z.string().meta({ example: "participant_abc123" }),
name: z.string().meta({ example: "Jane Smith" }),
email: z.string().nullable().meta({ example: "[email protected]" }),
createdAt: z.iso.datetime().meta({ example: "2025-01-10T12:00:00Z" }),
+ votes: z.array(participantVoteSchema).meta({
+ description:
+ "The participant's vote for each option, keyed by `optionId`. An option missing from the list has no recorded vote from this participant.",
+ }),
})
.meta({ id: "Participant" });
+export const listParticipantsQuerySchema = z.object({
+ cursor: z.string().optional().meta({
+ description:
+ "Cursor for pagination. Pass the `nextCursor` value from the previous response to fetch the next page.",
+ example: "participant_abc123",
+ }),
+ limit: z.coerce.number().int().min(1).max(100).default(50).meta({
+ description: "Number of participants to return per page (1-100).",
+ example: 50,
+ }),
+});
+
export const getPollParticipantsSuccessResponseSchema = z
.object({
- data: z.object({
- pollId: z.string().meta({ example: "p_123abc" }),
- participants: z.array(participantSchema),
+ data: z.array(participantSchema),
+ nextCursor: z.string().nullable().meta({
+ description:
+ "Cursor to fetch the next page. `null` when there are no more results.",
+ example: "participant_abc123",
}),
})
.meta({ id: "GetPollParticipantsResponse" });
diff --git a/apps/web/src/features/poll/constants.ts b/apps/web/src/features/poll/constants.ts
index e496f4c19..b29c1aed1 100644
--- a/apps/web/src/features/poll/constants.ts
+++ b/apps/web/src/features/poll/constants.ts
@@ -1,5 +1,8 @@
export const MAX_POLL_OPTIONS = 100;
+// Display order of the built-in vote types.
+export const VOTE_TYPES = ["yes", "ifNeedBe", "no"] as const;
+
// Flashed by the create page with the new poll's id; the poll page opens
// the Share dialog when it matches.
export const SHARE_POLL_FLASH_KEY = "share-poll";
diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.ts
index 30f69ea69..0f8c05d26 100644
--- a/apps/web/src/features/poll/data.ts
+++ b/apps/web/src/features/poll/data.ts
@@ -1,8 +1,9 @@
import "server-only";
-import type { PollStatus, Prisma } from "@rallly/database";
+import type { PollStatus, Prisma, VoteType } from "@rallly/database";
import { prisma } from "@rallly/database";
import { getInstancePolicy } from "@/features/instance-policy/data";
+import { VOTE_TYPES } from "@/features/poll/constants";
import { isLegacyEditToken } from "@/features/poll/utils";
import { effectiveSpaceMemberWhere } from "@/features/space/member/utils";
import type {
@@ -50,6 +51,7 @@ export async function getPollResults({
},
select: {
id: true,
+ kind: true,
status: true,
options: {
select: {
@@ -81,35 +83,28 @@ export async function getPollResults({
return null;
}
- // Build vote counts map from groupBy results
- const votesByOption = new Map<
- string,
- Array<{ type: string; count: number }>
- >();
+ const countsByOption = new Map<string, Partial<Record<VoteType, number>>>();
for (const row of voteCounts) {
- let votes = votesByOption.get(row.optionId);
- if (!votes) {
- votes = [];
- votesByOption.set(row.optionId, votes);
+ let counts = countsByOption.get(row.optionId);
+ if (!counts) {
+ counts = {};
+ countsByOption.set(row.optionId, counts);
}
- votes.push({ type: row.type, count: row._count });
+ counts[row.type] = row._count;
}
- // Helper to get count for a specific vote type
- const getCount = (
- votes: Array<{ type: string; count: number }>,
- type: string,
- ) => votes.find((v) => v.type === type)?.count ?? 0;
-
- // Calculate scores for each option
- // Ranking: total availability (yes + ifNeedBe) is primary, yes votes as tiebreaker
- // Score formula: (yes + ifNeedBe) * 1000 + yes
+ // Ranking: total availability (yes + ifNeedBe) is primary, yes votes break
+ // ties. The formula is internal; the API documents score as opaque.
const optionResults = poll.options.map((option) => {
- const votes = votesByOption.get(option.id) ?? [];
- const yesCount = getCount(votes, "yes");
- const ifNeedBeCount = getCount(votes, "ifNeedBe");
- const score = (yesCount + ifNeedBeCount) * 1000 + yesCount;
+ const counts = countsByOption.get(option.id) ?? {};
+ // Dense: every vote type is present, in display order, zero included.
+ const votes = VOTE_TYPES.map((type) => ({
+ type,
+ count: counts[type] ?? 0,
+ }));
+ const score =
+ ((counts.yes ?? 0) + (counts.ifNeedBe ?? 0)) * 1000 + (counts.yes ?? 0);
return {
id: option.id,
@@ -131,6 +126,7 @@ export async function getPollResults({
return {
pollId: poll.id,
+ kind: poll.kind,
status: poll.status,
participantCount: poll._count.participants,
options,
@@ -138,12 +134,20 @@ export async function getPollResults({
};
}
+/**
+ * Participants in response order (oldest first) with their recorded votes.
+ * Pass `limit` to page with a cursor; omit it to return every participant.
+ */
export async function getPollParticipants({
pollId,
spaceId,
+ cursor,
+ limit,
}: {
pollId: string;
spaceId: AuthorizedSpaceId;
+ cursor?: string;
+ limit?: number;
}) {
const poll = await prisma.poll.findFirst({
where: {
@@ -159,10 +163,16 @@ export async function getPollParticipants({
name: true,
email: true,
createdAt: true,
+ votes: {
+ select: {
+ optionId: true,
+ type: true,
+ },
+ },
},
- orderBy: {
- createdAt: "asc",
- },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ ...(limit !== undefined && { take: limit + 1 }),
+ ...(cursor && { cursor: { id: cursor }, skip: 1 }),
},
},
});
@@ -171,9 +181,13 @@ export async function getPollParticipants({
return null;
}
+ const hasMore = limit !== undefined && poll.participants.length > limit;
+ const page = hasMore ? poll.participants.slice(0, limit) : poll.participants;
+
return {
pollId: poll.id,
- participants: poll.participants,
+ participants: page,
+ nextCursor: hasMore ? (page[page.length - 1]?.id ?? null) : null,
};
}
@@ -202,6 +216,7 @@ export async function listPolls({
location: true,
timeZone: true,
status: true,
+ kind: true,
createdAt: true,
user: {
select: {
@@ -519,6 +534,7 @@ export async function getPollWithOptions({
location: true,
timeZone: true,
status: true,
+ kind: true,
createdAt: true,
user: {
select: {
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index 0b1c33cf5..e2567abaa 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -64,6 +64,7 @@ export const createPoll = async ({
location: true,
timeZone: true,
status: true,
+ kind: true,
createdAt: true,
disableComments: true,
user: {
@@ -107,6 +108,7 @@ const pollResponseSelect = {
location: true,
timeZone: true,
status: true,
+ kind: true,
createdAt: true,
user: {
select: {