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
7 changes: 7 additions & 0 deletions apps/api/src/features/routines/routine.errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** Defines expected business errors raised by routine operations. */
export class InvalidRoutineExerciseSelectionError extends Error {
constructor() {
super('One or more exercises are not available to this user.');
this.name = 'InvalidRoutineExerciseSelectionError';
}
}
103 changes: 89 additions & 14 deletions apps/api/src/features/routines/routine.routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,109 @@ import { describe, expect, it, vi } from 'vitest';
import { createSessionMiddleware } from '../auth/session/session.middleware.js';
import { establishAuthenticatedTestSession } from '../../test/authenticated-session.test-helper.js';
import { testSessionConfiguration } from '../../test/fixtures/session-configuration.fixture.js';
import { InvalidRoutineExerciseSelectionError } from './routine.errors.js';
import { createRoutineRouter } from './routine.routes.js';

const userId = '26d34dc0-8e4c-4bd0-9e3b-7b839b44e486';
const routineList = [
{
id: 'c38794ef-9a4a-40d8-8cdc-7f7416a53120',
name: 'Upper Body',
description: null,
exerciseCount: 3,
scheduledDays: [1, 3, 5],
createdAt: '2026-08-24T18:00:00.000Z',
updatedAt: '2026-08-24T19:00:00.000Z',
},
];
const routineSummary = {
id: 'c38794ef-9a4a-40d8-8cdc-7f7416a53120',
name: 'Upper Body',
description: null,
exerciseCount: 3,
scheduledDays: [1, 3, 5],
createdAt: '2026-08-24T18:00:00.000Z',
updatedAt: '2026-08-24T19:00:00.000Z',
};
const routineList = [routineSummary];
const createRoutineInput = {
name: 'Upper Body',
exercises: [
{
exerciseId: '9f4b5a8e-2c3d-4f10-8a11-000000000001',
position: 0,
sets: 3,
targetReps: 10,
weight: 25,
weightUnit: 'lb',
},
],
};

function createTestApp(
createRoutine = vi.fn(() => Promise.resolve(routineSummary)),
listRoutines = vi.fn(() => Promise.resolve(routineList)),
) {
const app = express();
app.use(express.json());
app.use(
createSessionMiddleware(
new session.MemoryStore(),
testSessionConfiguration,
),
);
app.use(establishAuthenticatedTestSession());
app.use('/routines', createRoutineRouter({ listRoutines }));
app.use('/routines', createRoutineRouter({ createRoutine, listRoutines }));

return { app, listRoutines };
return { app, createRoutine, listRoutines };
}

describe('POST /routines', () => {
it('rejects anonymous and invalid requests', async () => {
const { app, createRoutine } = createTestApp();

const anonymous = await request(app)
.post('/routines')
.send(createRoutineInput);
const invalid = await request(app)
.post('/routines')
.set('x-test-authenticated-user-id', userId)
.send({ name: 'Upper Body', exercises: [] });

expect(anonymous.status).toBe(401);
expect(invalid.status).toBe(400);
expect(invalid.body).toEqual({ error: 'invalid_request' });
expect(createRoutine).not.toHaveBeenCalled();
});

it('creates a routine for the authenticated user', async () => {
const { app, createRoutine } = createTestApp();

const response = await request(app)
.post('/routines')
.set('x-test-authenticated-user-id', userId)
.send(createRoutineInput);

expect(response.status).toBe(201);
expect(response.body).toEqual(routineSummary);
expect(createRoutine).toHaveBeenCalledWith(userId, {
...createRoutineInput,
exercises: [
{
...createRoutineInput.exercises[0],
restBetweenSetsSeconds: 0,
restAfterExerciseSeconds: 0,
},
],
schedules: [],
});
});

it('rejects exercises unavailable to the authenticated user', async () => {
const createRoutine = vi.fn(() =>
Promise.reject(new InvalidRoutineExerciseSelectionError()),
);
const { app } = createTestApp(createRoutine);

const response = await request(app)
.post('/routines')
.set('x-test-authenticated-user-id', userId)
.send(createRoutineInput);

expect(response.status).toBe(400);
expect(response.body).toEqual({ error: 'invalid_exercise_selection' });
});
});

describe('GET /routines', () => {
it('rejects anonymous requests', async () => {
const { app, listRoutines } = createTestApp();
Expand All @@ -62,7 +134,10 @@ describe('GET /routines', () => {
});

it('returns an empty list for a user without routines', async () => {
const { app } = createTestApp(vi.fn(() => Promise.resolve([])));
const { app } = createTestApp(
undefined,
vi.fn(() => Promise.resolve([])),
);

const response = await request(app)
.get('/routines')
Expand Down
32 changes: 32 additions & 0 deletions apps/api/src/features/routines/routine.routes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/** Defines authenticated routine-list API routes. */
import {
createRoutineInputSchema,
routineListResponseSchema,
routineSummarySchema,
type CreateRoutineInput,
type RoutineSummary,
} from '@goforlift/contracts';
import { Router } from 'express';
Expand All @@ -9,16 +12,45 @@ import {
getAuthenticatedUserId,
requireAuthentication,
} from '../auth/guards/authentication.middleware.js';
import { InvalidRoutineExerciseSelectionError } from './routine.errors.js';

type RoutineRouterDependencies = {
createRoutine: (
userId: string,
input: CreateRoutineInput,
) => Promise<RoutineSummary>;
listRoutines: (userId: string) => Promise<RoutineSummary[]>;
};

export function createRoutineRouter({
createRoutine,
listRoutines,
}: RoutineRouterDependencies) {
const router = Router();

router.post('/', requireAuthentication, async (request, response, next) => {
const inputResult = createRoutineInputSchema.safeParse(request.body);

if (!inputResult.success) {
response.status(400).json({ error: 'invalid_request' });
return;
}

try {
const userId = getAuthenticatedUserId(request);
const routine = await createRoutine(userId, inputResult.data);

response.status(201).json(routineSummarySchema.parse(routine));
} catch (error) {
if (error instanceof InvalidRoutineExerciseSelectionError) {
response.status(400).json({ error: 'invalid_exercise_selection' });
return;
}

next(error);
}
});

router.get('/', requireAuthentication, async (request, response, next) => {
try {
const userId = getAuthenticatedUserId(request);
Expand Down
138 changes: 134 additions & 4 deletions apps/api/src/features/routines/routine.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,140 @@
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { describe, expect, it, vi } from 'vitest';

import { routines } from '../../db/schema/index.js';
import { listRoutinesForUser } from './routine.service.js';
import {
routineExercises,
routineSchedules,
routines,
} from '../../db/schema/index.js';
import { InvalidRoutineExerciseSelectionError } from './routine.errors.js';
import {
createRoutineForUser,
listRoutinesForUser,
} from './routine.service.js';

const userId = '26d34dc0-8e4c-4bd0-9e3b-7b839b44e486';
const exerciseId = '9f4b5a8e-2c3d-4f10-8a11-000000000001';

describe('createRoutineForUser', () => {
it('creates the routine, exercises, and schedules in one transaction', async () => {
const createdAt = new Date('2026-08-24T18:00:00.000Z');
const updatedAt = new Date('2026-08-24T19:00:00.000Z');
const createdRoutine = {
id: 'c38794ef-9a4a-40d8-8cdc-7f7416a53120',
name: 'Upper Body',
description: null,
createdAt,
updatedAt,
};
const returning = vi.fn().mockResolvedValue([createdRoutine]);
const routineValues = vi.fn(() => ({ returning }));
const exerciseValues = vi.fn().mockResolvedValue(undefined);
const scheduleValues = vi.fn().mockResolvedValue(undefined);
const insert = vi.fn((table) => {
if (table === routines) return { values: routineValues };
if (table === routineExercises) return { values: exerciseValues };
if (table === routineSchedules) return { values: scheduleValues };
throw new Error('Unexpected table.');
});
const where = vi.fn().mockResolvedValue([{ id: exerciseId }]);
const transaction = {
select: vi.fn(() => ({
from: vi.fn(() => ({ where })),
})),
insert,
};
const database = {
transaction: vi.fn(
async <Result>(
callback: (activeTransaction: typeof transaction) => Promise<Result>,
) => callback(transaction),
),
} as unknown as NodePgDatabase;

const result = await createRoutineForUser(database, userId, {
name: createdRoutine.name,
exercises: [
{
exerciseId,
position: 0,
sets: 3,
targetReps: 10,
weight: 25,
weightUnit: 'lb',
restBetweenSetsSeconds: 60,
restAfterExerciseSeconds: 90,
},
],
schedules: [{ dayOfWeek: 3, localTime: '18:30:00' }],
});

expect(routineValues).toHaveBeenCalledWith({
userId,
name: createdRoutine.name,
description: null,
});
expect(exerciseValues).toHaveBeenCalledWith([
expect.objectContaining({
routineId: createdRoutine.id,
exerciseId,
weight: '25',
}),
]);
expect(scheduleValues).toHaveBeenCalledWith([
{
routineId: createdRoutine.id,
dayOfWeek: 3,
localTime: '18:30:00',
},
]);
expect(result).toEqual({
id: createdRoutine.id,
name: createdRoutine.name,
description: null,
exerciseCount: 1,
scheduledDays: [3],
createdAt: createdAt.toISOString(),
updatedAt: updatedAt.toISOString(),
});
});

it('rejects unavailable exercises before inserting a routine', async () => {
const insert = vi.fn();
const transaction = {
select: vi.fn(() => ({
from: vi.fn(() => ({ where: vi.fn().mockResolvedValue([]) })),
})),
insert,
};
const database = {
transaction: vi.fn(
async <Result>(
callback: (activeTransaction: typeof transaction) => Promise<Result>,
) => callback(transaction),
),
} as unknown as NodePgDatabase;

await expect(
createRoutineForUser(database, userId, {
name: 'Upper Body',
exercises: [
{
exerciseId,
position: 0,
sets: 3,
targetReps: 10,
weight: 25,
weightUnit: 'lb',
restBetweenSetsSeconds: 0,
restAfterExerciseSeconds: 0,
},
],
schedules: [],
}),
).rejects.toBeInstanceOf(InvalidRoutineExerciseSelectionError);
expect(insert).not.toHaveBeenCalled();
});
});

describe('listRoutinesForUser', () => {
it('returns serialized routine summaries from the owner-scoped query', async () => {
Expand All @@ -28,8 +160,6 @@ describe('listRoutinesForUser', () => {
const from = vi.fn(() => ({ leftJoin: firstLeftJoin }));
const select = vi.fn(() => ({ from }));
const database = { select } as unknown as NodePgDatabase;
const userId = '26d34dc0-8e4c-4bd0-9e3b-7b839b44e486';

const result = await listRoutinesForUser(database, userId);

expect(select).toHaveBeenCalledOnce();
Expand Down
Loading