ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: client/gatsby-node.js (JavaScript)

Code before:
      espanol: String
      italian: String
      portuguese: String
    }
    type BilibiliIds {
      aid: Int
      bvid: String
      cid: Int
    }
    type Question {
      text: String
      answers: [Answer]
      solution: Int
    }
    type Answer {
      answer: String
      feedback: String
    }
    type RequiredResource {
      link: String
      raw: Boolean
      src: String
      crossDomain: Boolean
    }
    type Hooks {
      beforeAll: String
    }
    type Test {
      id: String
      text: String
      testString: String
      title: String
    }
    type FillInTheBlank {
      sentence: String
      blanks: [Blank]
    }
    type Blank {
      answer: String
      feedback: String
    }
    type Scene {
      setup: SceneSetup
      commands: [SceneCommands]
    }
    type SceneSetup {
      background: String
      characters: [SetupCharacter]
      audio: SetupAudio
      alwaysShowDialogue: Boolean
    }

Review comment (suggestion):
```suggestion
      beforeAll: String
      beforeEach: String
      afterAll: String
      afterEach: String
```

Code after:
      espanol: String
      italian: String
      portuguese: String
    }
    type BilibiliIds {
      aid: Int
      bvid: String
      cid: Int
    }
    type Question {
      text: String
      answers: [Answer]
      solution: Int
    }
    type Answer {
      answer: String
      feedback: String
    }
    type RequiredResource {
      link: String
      raw: Boolean
      src: String
      crossDomain: Boolean
    }
    type Hooks {
      beforeAll: String
      beforeEach: String
      afterAll: String
      afterEach: String
    }
    type Test {
      id: String
      text: String
      testString: String
      title: String
    }
    type FillInTheBlank {
      sentence: String
      blanks: [Blank]
    }
    type Blank {
      answer: String
      feedback: String
    }
    type Scene {
      setup: SceneSetup
      commands: [SceneCommands]
    }
    type SceneSetup {
      background: String
      characters: [SetupCharacter]
Repository: freeCodeCamp/freeCodeCamp
File: api/src/exam-environment/routes/exam-environment.ts (TypeScript)

Code before:
      continue;
    }

    const maybeModerations = await mapErr(
      this.prisma.examEnvironmentExamModeration.findMany({
        where: {
          examAttemptId: lastAttempt.id,
          NOT: { status: ExamEnvironmentExamModerationStatus.Pending }
        }
      })
    );

    if (maybeModerations.hasError) {
      logger.error(maybeModerations.error);
      this.Sentry.captureException(maybeModerations.error);
      void reply.code(500);
      return reply.send(
        ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeModerations.error))
      );
    }

    const moderations = maybeModerations.data;

    if (moderations.length > 0) {
      availableExam.canTake = false;
      availableExams.push(availableExam);
      continue;
    }

    availableExams.push(availableExam);
  }

  return reply.send({
    exams: availableExams
  });
}

/**
 * Gets all exam attempts owned by authz user.
 *
 * If an attempt is completed, the result is included.
 */
async function getExamAttemptsHandler(
  this: FastifyInstance,
  req: UpdateReqType<typeof schemas.examEnvironmentGetExamAttempts>,
  reply: FastifyReply
) {
  const logger = this.log.child({ req });
  logger.info({ userId: req.user?.id });

  const user = req.user!;

Review comment (suggestion):
I think you can do something like this:

```suggestion
      return reply.code(500).send(
        ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeModerations.error))
      );
```

Code after:
      exam.config.retakeTimeInMS;
    const isRetakeTimePassed = Date.now() > retakeDateInMS;

    if (!isRetakeTimePassed) {
      logger.info(`Time until retake: ${retakeDateInMS - Date.now()} [ms]`);
      availableExam.canTake = false;
      availableExams.push(availableExam);
      continue;
    }

    const maybeModerations = await mapErr(
      this.prisma.examEnvironmentExamModeration.findMany({
        where: {
          examAttemptId: { in: attemptsForExam.map(a => a.id) },
          status: ExamEnvironmentExamModerationStatus.Pending
        }
      })
    );

    if (maybeModerations.hasError) {
      logger.error(maybeModerations.error);
      this.Sentry.captureException(maybeModerations.error);
      void reply.code(500);
      return reply.send(
        ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeModerations.error))
      );
    }

    const moderations = maybeModerations.data;

    if (moderations.length > 0) {
      logger.info(`Exam Moderation records found: ${moderations.length}`);
      availableExam.canTake = false;
      availableExams.push(availableExam);
      continue;
    }

    availableExam.canTake = true;
    availableExams.push(availableExam);
  }

  return reply.send(availableExams);
}

/**
 * Gets all exam attempts owned by authz user.
 *
 * If an attempt is completed, the result is included.
 */
async function getExamAttemptsHandler(
  this: FastifyInstance,
Repository: freeCodeCamp/freeCodeCamp
File: api/src/exam-environment/routes/exam-environment.ts (TypeScript)

Code before:
    }

    examEnvironmentExamAttempts.push(examEnvironmentExamAttempt);
  }

  return reply.send(examEnvironmentExamAttempts);
}

/**
 * Gets all the relations for a given challenge and exam(s).
 */
export async function getExamMappingsByChallengeId(
  this: FastifyInstance,
  req: UpdateReqType<
    typeof schemas.examEnvironmentGetExamMappingsByChallengeId
  >,
  reply: FastifyReply
) {
  const logger = this.log.child({ req });
  const { challengeId } = req.params;

  logger.info({ challengeId });

  const maybeData = await mapErr(
    this.prisma.examEnvironmentChallenge.findMany({
      where: {
        challengeId
      }
    })
  );

  if (maybeData.hasError) {
    logger.error(maybeData.error);
    this.Sentry.captureException(maybeData.error);
    void reply.code(500);
    return reply.send(
      ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeData.error))
    );
  }

  const data = maybeData.data;

  return reply.send(data);
}


Review comment (suggestion):
I made a `GET /exam-environment/exam-challenge` request here with no query params and it returned the seeded challenge from the database. Is that intended? Agent says...

"When both conditions are `undefined`, Prisma ignores those fields, effectively making it an empty where clause:

```
this.prisma.examEnvironmentChallenge.findMany({
  where: {}
})
```

Which returns all records"

Looks like the client shouldn't make a request without an ID, but - "never trust the client" as they say.

Code after:
    }

    examEnvironmentExamAttempts.push(examEnvironmentExamAttempt);
  }

  return reply.send(examEnvironmentExamAttempts);
}

/**
 * Gets all the relations for a given challenge and exam(s).
 */
export async function getExamChallenge(
  this: FastifyInstance,
  req: UpdateReqType<typeof schemas.examEnvironmentGetExamChallenge>,
  reply: FastifyReply
) {
  const logger = this.log.child({ req });
  const { challengeId, examId } = req.query;

  logger.info({ challengeId, examId });

  const maybeData = await mapErr(
    this.prisma.examEnvironmentChallenge.findMany({
      where: {
        challengeId: challengeId ?? undefined,
        examId: examId ?? undefined
      }
    })
  );

  if (maybeData.hasError) {
    logger.error(maybeData.error);
    this.Sentry.captureException(maybeData.error);
    void reply.code(500);
    return reply.send(
      ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeData.error))
    );
  }

  const data = maybeData.data;

  return reply.send(data);
}
Repository: freeCodeCamp/freeCodeCamp
File: api/src/daily-coding-challenge/routes/daily-coding-challenge.test.ts (TypeScript)

Code before:
  yesterdaysChallenge
];

describe('/daily-coding-challenge', () => {
  setupServer();

  describe('GET /daily-coding-challenge/date/:date', () => {
    beforeEach(async () => {
      await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({
        data: mockChallenges
      });
    });

    afterEach(async () => {
      await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany();
    });

    it('should return 400 for an invalid date format', async () => {
      const res = await superRequest(
        '/daily-coding-challenge/date/invalid-format',
        {
          method: 'GET'
        }
      ).send({});

      expect(res.status).toBe(400);
      expect(res.body).toEqual({
        type: 'error',
        message: 'Invalid date format. Please use YYYY-MM-DD.'
      });
    });

    it('should return 404 for a date without a challenge', async () => {
      const res = await superRequest(
        `/daily-coding-challenge/date/${twoDaysAgoDateParam}`,
        {
          method: 'GET'
        }
      ).send({});

      expect(res.status).toBe(404);
      expect(res.body).toEqual({
        type: 'error',
        message: 'Challenge not found.'
      });
    });

    it('should return a challenge for a valid date', async () => {
      const res = await superRequest(
        `/daily-coding-challenge/date/${todayDateParam}`,
        {

Review comment (bug):
Do not mean to be pedantic but I think it would be better to check for valid format only and reject the rest. I mean negative checks are sometimes source of buggy logic.

Code after:
  yesterdaysChallenge
];

describe('/daily-coding-challenge', () => {
  setupServer();

  describe('GET /daily-coding-challenge/date/:date', () => {
    beforeEach(async () => {
      await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({
        data: mockChallenges
      });
    });

    afterEach(async () => {
      await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany();
    });

    it('should return 400 for an invalid date format', async () => {
      const invalidFormats = [
        'invalid-format',
        '2025-07',
        '07-18-2025',
        '25-07-18',
        '2025-7-18',
        '2025-07-8'
      ];

      for (const invalidFormat of invalidFormats) {
        const res = await superRequest(
          `/daily-coding-challenge/date/${invalidFormat}`,
          {
            method: 'GET'
          }
        ).send({});

        expect(res.status).toBe(400);
        expect(res.body).toEqual({
          type: 'error',
          message: 'Invalid date format. Please use YYYY-MM-DD.'
        });
      }
    });

    it('should return 404 for a date without a challenge', async () => {
      const res = await superRequest(
        `/daily-coding-challenge/date/${twoDaysAgoDateParam}`,
        {
          method: 'GET'
        }
      ).send({});
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/helpers/auth-helpers.test.ts (TypeScript)

Code before:
    await findOrCreateUser(fastify, email);

    expect(captureException).toHaveBeenCalledTimes(1);
    expect(captureException).toHaveBeenCalledWith(
      new Error(`Multiple user records found for: ${ids.join(', ')}`)
    );
  });

  it('should NOT send a message if there is only one user with the email', async () => {
    await fastify.prisma.user.create({ data: createUserInput(email) });

    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it('should NOT send a message if there are no users with the email', async () => {
    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it('should NOT create a user if there is an account with case-insensitive email matches', async () => {
    const upperCaseEmail = email.toUpperCase();

    // Create a user with uppercase email
    const existingUser = await fastify.prisma.user.create({
      data: createUserInput(email)
    });

    // Try to find or create with lowercase email
    const result = await findOrCreateUser(fastify, upperCaseEmail);

    // Should return the existing user, not create a new one
    expect(result.id).toBe(existingUser.id);

    // Verify only one user exists in the database
    const allUsers = await fastify.prisma.user.findMany({
      where: {
        email: {
          in: [upperCaseEmail, email]
        }
      }
    });
    expect(allUsers).toHaveLength(1);
  });
});


Review comment (suggestion):
```suggestion
    // Create a user with lowercase email
```

Code after:
    await findOrCreateUser(fastify, email);

    expect(captureException).toHaveBeenCalledTimes(1);
    expect(captureException).toHaveBeenCalledWith(
      new Error(`Multiple user records found for: ${ids.join(', ')}`)
    );
  });

  it('should NOT send a message if there is only one user with the email', async () => {
    await fastify.prisma.user.create({ data: createUserInput(email) });

    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it('should NOT send a message if there are no users with the email', async () => {
    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it("should NOT create a user if there is already an account with the lowercase version of the user's email", async () => {
    const upperCaseEmail = email.toUpperCase();

    // Create a user with lowercase email
    const existingUser = await fastify.prisma.user.create({
      data: createUserInput(email)
    });

    // Try to find or create with uppercase email
    const result = await findOrCreateUser(fastify, upperCaseEmail);

    // Should return the existing user, not create a new one
    expect(result.id).toBe(existingUser.id);

    // Verify only one user exists in the database
    const allUsers = await fastify.prisma.user.findMany({
      where: {
        email: {
          in: [upperCaseEmail, email]
        }
      }
    });
    expect(allUsers).toHaveLength(1);
  });
});
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/helpers/auth-helpers.test.ts (TypeScript)

Code before:
    );
  });

  it('should NOT send a message if there is only one user with the email', async () => {
    await fastify.prisma.user.create({ data: createUserInput(email) });

    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it('should NOT send a message if there are no users with the email', async () => {
    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it('should NOT create a user if there is an account with case-insensitive email matches', async () => {
    const upperCaseEmail = email.toUpperCase();

    // Create a user with uppercase email
    const existingUser = await fastify.prisma.user.create({
      data: createUserInput(email)
    });

    // Try to find or create with lowercase email
    const result = await findOrCreateUser(fastify, upperCaseEmail);

    // Should return the existing user, not create a new one
    expect(result.id).toBe(existingUser.id);

    // Verify only one user exists in the database
    const allUsers = await fastify.prisma.user.findMany({
      where: {
        email: {
          in: [upperCaseEmail, email]
        }
      }
    });
    expect(allUsers).toHaveLength(1);
  });
});


Review comment (suggestion):
```suggestion
    // Try to find or create with uppercase email
```

Code after:
    );
  });

  it('should NOT send a message if there is only one user with the email', async () => {
    await fastify.prisma.user.create({ data: createUserInput(email) });

    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it('should NOT send a message if there are no users with the email', async () => {
    await findOrCreateUser(fastify, email);

    expect(captureException).not.toHaveBeenCalled();
  });

  it("should NOT create a user if there is already an account with the lowercase version of the user's email", async () => {
    const upperCaseEmail = email.toUpperCase();

    // Create a user with lowercase email
    const existingUser = await fastify.prisma.user.create({
      data: createUserInput(email)
    });

    // Try to find or create with uppercase email
    const result = await findOrCreateUser(fastify, upperCaseEmail);

    // Should return the existing user, not create a new one
    expect(result.id).toBe(existingUser.id);

    // Verify only one user exists in the database
    const allUsers = await fastify.prisma.user.findMany({
      where: {
        email: {
          in: [upperCaseEmail, email]
        }
      }
    });
    expect(allUsers).toHaveLength(1);
  });
});
Repository: freeCodeCamp/freeCodeCamp
File: client/src/redux/fetch-user-saga.js (JavaScript)

Code before:
import { call, put, takeEvery, race, delay } from 'redux-saga/effects';
import { getSessionUser, getUserProfile } from '../utils/ajax';
import {
  fetchProfileForUserComplete,
  fetchProfileForUserError,
  fetchUserComplete,
  fetchUserError
} from './actions';

function* fetchSessionUser() {
  try {
    const { res, timeout } = yield race({
      res: call(getSessionUser),
      timeout: delay(5000)
    });

    if (timeout) {
      throw new Error('Request timed out after 5 seconds');
    }

    if (!res.response.ok) {
      throw new Error(
        `HTTP Error: ${res.response.status} ${res.response.statusText}`
      );
    }

    const { data: user } = res;
    yield put(fetchUserComplete({ user }));
  } catch (e) {
    console.log('failed to fetch user', e);
    yield put(fetchUserError(e));
  }
}

function* fetchOtherUser({ payload: maybeUser = '' }) {
  try {
    const maybeUserLC = maybeUser.toLowerCase();

    const { data: otherUser } = yield call(getUserProfile, maybeUserLC);
    yield put(fetchProfileForUserComplete({ user: otherUser }));
  } catch (e) {
    yield put(fetchProfileForUserError(e));
  }
}

export function createFetchUserSaga(types) {

Review comment (suggestion):
I am not sure if I am testing this poorly, but I added `res.code(500); return res.reply("Bad request");` to the `/user/get-session-user` endpoint, and navigates to `/settings`.

It is stuck on:

<img width="2879" height="1208" alt="image" src="https://github.com/user-attachments/assets/e18a099f-62f3-4eda-94f6-53d9d03ed9c7" />


Code after:
import { call, cancel, delay, fork, put, takeEvery } from 'redux-saga/effects';
import { getSessionUser, getUserProfile } from '../utils/ajax';
import {
  fetchProfileForUserComplete,
  fetchProfileForUserError,
  fetchUserComplete,
  fetchUserError,
  fetchUserTimeout
} from './actions';

function* fetchSessionUser() {
  const timeoutTask = yield fork(function* () {
    // The server should not take anywhere near 2 seconds to respond. If it
    // does, we assume the request has failed and dispatch a timeout action to
    // dismiss the loading state.
    yield delay(2000);
    yield put(fetchUserTimeout());
  });

  try {
    // This is on a longer timeout to make sure that users with slow connections
    // do, eventually, get signed in.
    const res = yield call(getSessionUser, AbortSignal.timeout(10000));

    const isSignedOut = res.response.status === 401;
    if (!res.response.ok && !isSignedOut) {
      throw new Error(
        `HTTP Error: ${res.response.status} ${res.response.statusText}`
      );
    }

    const { data: user } = res;
    yield put(fetchUserComplete({ user }));
  } catch (e) {
    console.log('failed to fetch user', e);
    yield put(fetchUserError(e));
  } finally {
    yield cancel(timeoutTask);
  }
}

function* fetchOtherUser({ payload: maybeUser = '' }) {
  try {
    const maybeUserLC = maybeUser.toLowerCase();

    const { data: otherUser } = yield call(getUserProfile, maybeUserLC);
Repository: freeCodeCamp/freeCodeCamp
File: client/src/redux/fetch-user-saga.js (JavaScript)

Code before:
import { call, put, takeEvery, race, delay } from 'redux-saga/effects';
import { getSessionUser, getUserProfile } from '../utils/ajax';
import {
  fetchProfileForUserComplete,
  fetchProfileForUserError,
  fetchUserComplete,
  fetchUserError
} from './actions';

function* fetchSessionUser() {
  try {
    const { res, timeout } = yield race({
      res: call(getSessionUser),
      timeout: delay(5000)
    });

    if (timeout) {
      throw new Error('Request timed out after 5 seconds');
    }

    if (!res.response.ok) {
      throw new Error(
        `HTTP Error: ${res.response.status} ${res.response.statusText}`
      );
    }

    const { data: user } = res;
    yield put(fetchUserComplete({ user }));
  } catch (e) {
    console.log('failed to fetch user', e);
    yield put(fetchUserError(e));
  }
}

function* fetchOtherUser({ payload: maybeUser = '' }) {
  try {
    const maybeUserLC = maybeUser.toLowerCase();

    const { data: otherUser } = yield call(getUserProfile, maybeUserLC);

Review comment (suggestion):
The only thing to note is it is entirely possible for the request to succeed, but take longer than 5s. In which case, the client ignores the success.

So, I suggest also aborting the fetch after 5s. _According to the Google, Chrome's fetch times out after 300s._

You should be able to remove all this timeout stuff here in place of an abort signal on the fetch...

Code after:
import { call, cancel, delay, fork, put, takeEvery } from 'redux-saga/effects';
import { getSessionUser, getUserProfile } from '../utils/ajax';
import {
  fetchProfileForUserComplete,
  fetchProfileForUserError,
  fetchUserComplete,
  fetchUserError,
  fetchUserTimeout
} from './actions';

function* fetchSessionUser() {
  const timeoutTask = yield fork(function* () {
    // The server should not take anywhere near 2 seconds to respond. If it
    // does, we assume the request has failed and dispatch a timeout action to
    // dismiss the loading state.
    yield delay(2000);
    yield put(fetchUserTimeout());
  });

  try {
    // This is on a longer timeout to make sure that users with slow connections
    // do, eventually, get signed in.
    const res = yield call(getSessionUser, AbortSignal.timeout(10000));

    const isSignedOut = res.response.status === 401;
    if (!res.response.ok && !isSignedOut) {
      throw new Error(
        `HTTP Error: ${res.response.status} ${res.response.statusText}`
      );
    }

    const { data: user } = res;
    yield put(fetchUserComplete({ user }));
  } catch (e) {
    console.log('failed to fetch user', e);
    yield put(fetchUserError(e));
  } finally {
    yield cancel(timeoutTask);
  }