-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
82 lines (67 loc) · 1.82 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Hono } from "hono";
import "dotenv/config";
import { nanoid } from "nanoid";
import { logger } from "hono/logger";
import { validateUrl } from "./utils/validateUrl";
import Url from "./models/url.model";
import { redis } from ".";
const app = new Hono();
app.use("*", logger());
// Short URL Generator
app.post('/short', async (c) => {
const { origUrl } = await c.req.json();
const base = process.env.BASE || 'http://localhost:3000';
const urlId = nanoid();
if (!validateUrl(origUrl)) {
return c.json({ error: "Invalid Original Url" }, 400);
}
try {
let url = await Url.findOne({ origUrl });
if (url) {
return c.json(url, 200);
} else {
const shortUrl = `${base}/${urlId}`;
url = new Url({
origUrl,
shortUrl,
urlId
});
await url.save();
return c.json(url, 201);
}
} catch (err: any) {
console.error(`Error in short url generator: ${err.message}`);
return c.json({ error: "Internal Server Error" }, 500);
}
});
app.get('/:urlId', async (c) => {
const urlId = c.req.param("urlId");
try {
const cachedUrl = await redis.get(urlId);
if (cachedUrl) {
await redis.incr(`${urlId}_clicks`);
return c.redirect(cachedUrl);
}
const url = await Url.findOne({ urlId });
if (!url) {
return c.notFound();
}
await redis.set(urlId, url.origUrl);
await redis.set(`${urlId}_clicks`, url.clicks);
await Url.updateOne(
{
urlId,
},
{ $inc: { clicks: 1 } }
);
await redis.incr(`${urlId}_clicks`);
return c.redirect(url.origUrl);
} catch (err: any) {
console.error(`Error in get url: ${err.message}`);
return c.json({ error: "Internal Server Error" }, 500);
}
});
app.get('/', (c) => {
return c.text("URL shortener service");
});
export default app;