Skip to content

Commit d44cc9b

Browse files
committed
get original url from shortened url
1 parent 1d5ba2d commit d44cc9b

File tree

1 file changed

+19
-35
lines changed

1 file changed

+19
-35
lines changed
Lines changed: 19 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,27 @@
11
import { NextRequest, NextResponse } from 'next/server';
22

3-
// Function to handle POST requests
43
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
105

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 });
198
}
20-
}
219

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 });
3026
});
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-
}
4327
}

0 commit comments

Comments
 (0)