⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(api): add a project-scoped task relations endpoint
Juan8a3138dd1524
diff --git a/apps/api/src/task-relation/controllers/get-project-task-relations.ts b/apps/api/src/task-relation/controllers/get-project-task-relations.tsnew file mode 100644index 000000000..6cea98565--- /dev/null+++ b/apps/api/src/task-relation/controllers/get-project-task-relations.ts@@ -0,0 +1,37 @@+import { and, eq, inArray } from "drizzle-orm";+import db from "../../database";+import { taskRelationTable, taskTable } from "../../database/schema";++/**+ * Every relation joining two tasks in the project.+ *+ * The per-task endpoint cannot serve a list view, which would otherwise need+ * one request per row. Relations reaching outside the project are excluded+ * rather than returned with a dangling end: the view can only render a task it+ * is already showing, and the id alone would expose a task the caller may not+ * be able to open.+ */+async function getProjectTaskRelations(projectId: string) {+ const projectTaskIds = db+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(eq(taskTable.projectId, projectId));++ return db+ .select({+ id: taskRelationTable.id,+ sourceTaskId: taskRelationTable.sourceTaskId,+ targetTaskId: taskRelationTable.targetTaskId,+ relationType: taskRelationTable.relationType,+ createdAt: taskRelationTable.createdAt,+ })+ .from(taskRelationTable)+ .where(+ and(+ inArray(taskRelationTable.sourceTaskId, projectTaskIds),+ inArray(taskRelationTable.targetTaskId, projectTaskIds),+ ),+ );+}++export default getProjectTaskRelations;diff --git a/apps/api/src/task-relation/index.ts b/apps/api/src/task-relation/index.tsindex d90abcdd1..91873a6dd 100644--- a/apps/api/src/task-relation/index.ts+++ b/apps/api/src/task-relation/index.ts@@ -15,13 +15,16 @@ import { validateWorkspaceAccess } from "../utils/validate-workspace-access";import { workspaceAccess } from "../utils/workspace-access-middleware";import createTaskRelation from "./controllers/create-task-relation";import deleteTaskRelation from "./controllers/delete-task-relation";+import getProjectTaskRelations from "./controllers/get-project-task-relations";import getTaskRelations from "./controllers/get-task-relations";import {+ taskRelationListSchema,taskRelationSchema,taskRelationWithTasksListSchema,} from "./response";import {createTaskRelationBody,+ projectIdParam,taskIdParam,taskRelationParam,} from "./schema";@@ -113,6 +116,28 @@ const getTaskRelationsRoute = createRoute({},});+const getProjectTaskRelationsRoute = createRoute({+ method: "get",+ operationId: "getProjectTaskRelations",+ path: "/project/{projectId}",+ tags: ["Task Relations"],+ summary: "Get a project's task relations",+ description:+ "Get every relation joining two tasks in the project, without the task summaries the per-task endpoint returns. Intended for views that render many tasks at once and already hold them. Relations reaching outside the project are omitted.",+ middleware: [workspaceAccess.fromProject("projectId")] as const,+ request: { params: projectIdParam },+ responses: {+ 200: jsonResponse(+ "Relations between tasks in the project",+ taskRelationListSchema,+ ),+ 400: errorResponse(+ "Unknown project, or its workspace could not be determined",+ ),+ 403: errorResponse("No access to the project's workspace"),+ },+});+const createTaskRelationRoute = createRoute({method: "post",operationId: "createTaskRelation",@@ -164,6 +189,10 @@ const deleteTaskRelationRoute = createRoute({});const taskRelation = apiRouter<BaseVariables & { workspaceId: string }>()+ // Registered before "/{taskId}" so the literal segment is matched first.+ .openapi(getProjectTaskRelationsRoute, async (c) =>+ c.json(await getProjectTaskRelations(c.req.valid("param").projectId), 200),+ ).openapi(getTaskRelationsRoute, async (c) =>c.json(await getTaskRelations(c.req.valid("param").taskId, c.get("workspaceId")),diff --git a/apps/api/src/task-relation/response.ts b/apps/api/src/task-relation/response.tsindex 51205b47a..5ee21f3df 100644--- a/apps/api/src/task-relation/response.ts+++ b/apps/api/src/task-relation/response.ts@@ -38,3 +38,5 @@ export const taskRelationWithTasksSchema = taskRelationSchemaexport const taskRelationWithTasksListSchema = z.array(taskRelationWithTasksSchema,);++export const taskRelationListSchema = z.array(taskRelationSchema);diff --git a/apps/api/src/task-relation/schema.ts b/apps/api/src/task-relation/schema.tsindex 676aa75ae..0c1494668 100644--- a/apps/api/src/task-relation/schema.ts+++ b/apps/api/src/task-relation/schema.ts@@ -4,6 +4,8 @@ export const taskIdParam = z.object({ taskId: z.string() });export const taskRelationParam = z.object({ id: z.string() });+export const projectIdParam = z.object({ projectId: z.string() });+export const createTaskRelationBody = z.object({sourceTaskId: z.string(),targetTaskId: z.string(),diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex f4f27f221..796922646 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -2738,6 +2738,35 @@"updatedAt"]},+ "TaskRelation": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "sourceTaskId": {+ "type": "string"+ },+ "targetTaskId": {+ "type": "string"+ },+ "relationType": {+ "type": "string",+ "description": "How the two tasks relate: `subtask`, `blocks`, or `related`."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "sourceTaskId",+ "targetTaskId",+ "relationType",+ "createdAt"+ ]+ },"TaskRelationWithTasks": {"allOf": [{@@ -2814,35 +2843,6 @@"assigneeName"]},- "TaskRelation": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "sourceTaskId": {- "type": "string"- },- "targetTaskId": {- "type": "string"- },- "relationType": {- "type": "string",- "description": "How the two tasks relate: `subtask`, `blocks`, or `related`."- },- "createdAt": {- "type": "string",- "format": "date-time"- }- },- "required": [- "id",- "sourceTaskId",- "targetTaskId",- "relationType",- "createdAt"- ]- },"ExternalLink": {"type": "object","properties": {@@ -12992,6 +12992,64 @@}}},+ "/task-relation/project/{projectId}": {+ "get": {+ "operationId": "getProjectTaskRelations",+ "tags": [+ "Task Relations"+ ],+ "summary": "Get a project's task relations",+ "description": "Get every relation joining two tasks in the project, without the task summaries the per-task endpoint returns. Intended for views that render many tasks at once and already hold them. Relations reaching outside the project are omitted.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Relations between tasks in the project",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TaskRelation"+ }+ }+ }+ }+ },+ "400": {+ "description": "Unknown project, or its workspace could not be determined",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No access to the project's workspace",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/task-relation/{taskId}": {"get": {"operationId": "getTaskRelations",diff --git a/tests/api-integration/task-relation-project.test.ts b/tests/api-integration/task-relation-project.test.tsnew file mode 100644index 000000000..789e9a27a--- /dev/null+++ b/tests/api-integration/task-relation-project.test.ts@@ -0,0 +1,143 @@+import { beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++type RelationRow = typeof schema.taskRelationTable.$inferSelect;++let taskCounter = 0;++async function seedTask(+ userId: string,+ projectId: string,+ title: string,+ status = "to-do",+) {+ taskCounter += 1;+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId,+ userId,+ title,+ status,+ priority: "medium",+ number: taskCounter,+ position: taskCounter,+ })+ .returning();+ return task;+}++async function relate(+ sourceTaskId: string,+ targetTaskId: string,+ relationType = "subtask",+) {+ const [relation] = await db+ .insert(schema.taskRelationTable)+ .values({ sourceTaskId, targetTaskId, relationType })+ .returning();+ return relation;+}++async function fetchProjectRelations(projectId: string) {+ const { app } = createApp();+ return app.request(`/api/task-relation/project/${projectId}`);+}++describe("API integration: project task relations", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ taskCounter = 0;+ });++ it("returns the relations joining two tasks in the project", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });++ const parent = await seedTask(member.user.id, project.id, "Parent");+ const child = await seedTask(member.user.id, project.id, "Child");+ const blocker = await seedTask(member.user.id, project.id, "Blocker");++ const subtask = await relate(parent.id, child.id, "subtask");+ const blocks = await relate(blocker.id, parent.id, "blocks");++ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(200);+ const payload = (await response.json()) as RelationRow[];++ // Every type is returned; narrowing to subtasks is the caller's business.+ expect(payload.map((relation) => relation.id).sort()).toEqual(+ [subtask.id, blocks.id].sort(),+ );+ expect(+ payload.find((relation) => relation.id === subtask.id),+ ).toMatchObject({+ sourceTaskId: parent.id,+ targetTaskId: child.id,+ relationType: "subtask",+ });+ });++ it("omits a relation whose other end is in a different project", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const other = await createProjectFixture({+ workspaceId: member.workspace.id,+ slug: "other-project",+ });++ const parent = await seedTask(member.user.id, project.id, "Parent");+ const inside = await seedTask(member.user.id, project.id, "Inside");+ const outside = await seedTask(member.user.id, other.project.id, "Outside");++ const kept = await relate(parent.id, inside.id);+ await relate(parent.id, outside.id);++ const response = await fetchProjectRelations(project.id);+ const payload = (await response.json()) as RelationRow[];++ expect(payload.map((relation) => relation.id)).toEqual([kept.id]);+ });++ it("returns an empty list for a project with no relations", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });++ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual([]);+ });++ it("refuses a caller outside the project's workspace", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ await seedTask(owner.user.id, project.id, "Parent");++ const outsider = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(outsider.user);++ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(403);+ });+});