Skip to content

Commit 428dc62

Browse files
committed
refactor(api): add type guard for JSON schema validation and improve error handling in GET request
1 parent 8ac6668 commit 428dc62

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

app/api/get-schema/[name]/route.ts

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ function safeJoin(base: string, target: string): string | null {
1313
return null; // Path traversal detected or invalid path
1414
}
1515

16+
// Type guard function to validate JSON schema objects
17+
function isValidSchemaObject(value: unknown): value is Record<string, unknown> {
18+
return typeof value === 'object' && value !== null && !Array.isArray(value);
19+
}
20+
1621
// The standard Next.js App Router route handler type signature
1722
export async function GET(
1823
request: Request,
@@ -46,13 +51,27 @@ export async function GET(
4651
console.log(`Attempting to read schema file: ${filePath}`);
4752

4853
const fileContent: string = await fs.readFile(filePath, "utf-8");
49-
// Parse JSON with proper type assertion that satisfies ESLint
50-
const parsedContent = JSON.parse(fileContent);
51-
// Use type assertion after validation to satisfy ESLint
52-
const schemaJson: Record<string, unknown> =
53-
typeof parsedContent === 'object' && parsedContent !== null
54-
? parsedContent as Record<string, unknown>
55-
: {};
54+
55+
// Safely parse and validate the JSON schema
56+
let schemaJson: Record<string, unknown>;
57+
try {
58+
const parsed: unknown = JSON.parse(fileContent);
59+
60+
if (!isValidSchemaObject(parsed)) {
61+
return NextResponse.json(
62+
{ error: "Invalid schema format" },
63+
{ status: 400 }
64+
);
65+
}
66+
67+
schemaJson = parsed;
68+
} catch (parseError) {
69+
console.error("JSON parse error:", parseError);
70+
return NextResponse.json(
71+
{ error: "Invalid JSON format" },
72+
{ status: 400 }
73+
);
74+
}
5675

5776
return NextResponse.json(schemaJson);
5877
} catch (error: unknown) {

0 commit comments

Comments
 (0)