-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
69 lines (56 loc) · 1.72 KB
/
main.js
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
const express = require ("express");
const shortUrlModel=require("./models/short_url.js")
const {nanoid}=require("nanoid");//to create link for our url of random characters
const mongoose=require("mongoose");
const {z}=require("zod");
const inputschema=z.object({longUrl:z.string().url()})
mongoose.connect(process.env.dburl).then(()=>{console.log("connected to DB")})
//mogodb dosent rows and columns, the are called collections
// check input schema
const app=express();
app.use(express.json());
app.post("/short-url",((req,res)=>{
const body=req.body;
const validation=inputschema.safeParse(body);
if(!validation.success){
return res.status(422).json(
{
message:"Invalid url"
});
}
const urlId=nanoid(6);
// console.log(urlId);
// console.log(req.hostname);
const shortUrl=`https://${req.hostname}/${urlId}`;
// console.log(shortUrl);
const newshorturl=new shortUrlModel({
longUrl:body.longUrl,
shortUrl:urlId
});
newshorturl.save().then(()=>{
res.json({shortUrl})
}).catch(()=>{
res.status(500).json({message:"Error creating short url"});
});
}
)
)
app.get("/:shorturlid",(req,res)=>{
const short_url_id=req.params.shorturlid;
shortUrlModel.findOne({
shortUrl:short_url_id
}).then((doc)=>{
if(!doc){
return res.status(404).json({message:"link not found"})
};
res.redirect(doc.longUrl);
}).catch(()=>{
res.status(500).json({message:"An Error Occured"});
})
})
app.listen(3000,function(){
console.log("server running!!!");
})
//robot to view db
//search for [comonjs, ES modules];
//understand object relational mapper[prisma,mysql,mogodb]