Skip to content

[BUG] /api/user/:username can return 500 if historical data file isn't a valid array #239

Description

@Tamcodes4

Description

scripts/fetch-user-info.js calls .sort() on fetched historical data without verifying it's actually an array. A malformed or partially-written per-user JSON file in leetcode-ranking-data causes the whole /api/user/:username endpoint to throw and 500.

Steps to Reproduce

  1. Manually set a user's history file in leetcode-ranking-data/user-data/<username>.json to {} (or any non-array value) instead of an array.
  2. Hit GET /api/user/<username> on the running server, or visit /user/<username> in the browser.
  3. Observe the 500 response / failed profile page.

Expected Behavior

A malformed history file should degrade gracefully to an empty history array, not break the endpoint.

Actual Behavior

{ "error": "Failed to fetch user details", "details": "history.sort is not a function" }

Root Cause

scripts/fetch-user-info.js:

const response = await fetch(rawUrl);
if (response.ok) {
  history = await response.json();
} else {
  console.warn(...);
}
...
history.sort((a, b) => new Date(a.date) - new Date(b.date));

If response.ok is true but the parsed JSON isn't an array, .sort throws and the error propagates up through the /api/user/:username route in server.js.

Suggested Fix

history = Array.isArray(history) ? history : [];

right after the fetch, before the sort call.

Affected Files

  • scripts/fetch-user-info.js

Metadata

Metadata

Assignees

Labels

BackendTask mainly involving backendlevel:beginnerIndicates the difficultytype:bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions