|
1 | 1 | import { NextRequest, NextResponse } from 'next/server'; |
2 | 2 |
|
3 | | -// Function to handle POST requests |
4 | 3 | export async function POST(request: NextRequest) { |
5 | | - try { |
6 | | - const { url } = await request.json(); |
7 | | - if (!url || typeof url !== 'string') { |
8 | | - throw new Error(`Invalid URL format ${url}`); |
9 | | - } |
| 4 | + const { url } = await request.json().catch(() => ({})); // ✅ Simplified JSON parsing |
10 | 5 |
|
11 | | - const shortenedUrl = await shortenUrl(url); |
12 | | - return NextResponse.json({ shortenedUrl }, { status: 200 }); |
13 | | - } catch (error) { |
14 | | - console.error('Failed to shorten URL:', error); |
15 | | - return NextResponse.json( |
16 | | - { error: error instanceof Error ? error.message : 'Invalid request' }, |
17 | | - { status: 400 } |
18 | | - ); |
| 6 | + if (typeof url !== 'string' || !url.trim()) { |
| 7 | + return NextResponse.json({ error: 'Invalid URL format' }, { status: 400 }); |
19 | 8 | } |
20 | | -} |
21 | 9 |
|
22 | | -// Function to call the backend API |
23 | | -async function shortenUrl(url: string): Promise<string> { |
24 | | - try { |
25 | | - const requestBody = { url }; |
26 | | - const response = await fetch('http://localhost:3000/shorten-url', { |
27 | | - method: 'POST', |
28 | | - headers: { 'Content-Type': 'application/json' }, |
29 | | - body: JSON.stringify(requestBody), |
| 10 | + return fetch('http://localhost:3000/shorten-url', { |
| 11 | + method: 'POST', |
| 12 | + headers: { 'Content-Type': 'application/json' }, |
| 13 | + body: JSON.stringify({ url }), |
| 14 | + }) |
| 15 | + .then(async (res) => { |
| 16 | + if (!res.ok) |
| 17 | + throw new Error((await res.json()).error || 'Failed to shorten URL'); |
| 18 | + return res.json(); |
| 19 | + }) |
| 20 | + .then((data) => |
| 21 | + NextResponse.json({ shortenedUrl: data.shortenedUrl }, { status: 200 }) |
| 22 | + ) |
| 23 | + .catch((error) => { |
| 24 | + console.error('Error shortening URL:', error); |
| 25 | + return NextResponse.json({ error: error.message }, { status: 400 }); |
30 | 26 | }); |
31 | | - |
32 | | - if (!response.ok) { |
33 | | - const errorResponse = await response.json(); |
34 | | - throw new Error(errorResponse.error || 'Failed to shorten URL'); |
35 | | - } |
36 | | - |
37 | | - const data = await response.json(); |
38 | | - return data; |
39 | | - } catch (error) { |
40 | | - console.error('Error shortening URL:', error); |
41 | | - throw error; |
42 | | - } |
43 | 27 | } |
0 commit comments