Repository navigation
Expand file tree
/
Copy pathBK9.js
More file actions
94 lines (81 loc) · 2.78 KB
/
Copy pathBK9.js
File metadata and controls
94 lines (81 loc) · 2.78 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
// اذا واجهت اي مشكله ادخل قناة المطور واخبره بالمشكلة: https://whatsapp.com/channel/0029VaGPfAx17En4dklujt3n
const express = require('express');
const mongoose = require('mongoose');
const { nanoid } = require('nanoid');
const path = require('path');
require('dotenv').config({ path: './BK9.env' });
const app = express();
const PORT = process.env.PORT || 3000;
// الاتصال بقاعدة البيانات
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'خطأ في تم الاتصال بقاعدة البيانات:'));
db.once('open', () => {
console.log('تم الاتصال بقاعدة البيانات');
});
const urlSchema = new mongoose.Schema({
longURL: String,
shortURL: String,
});
const URL = mongoose.model('URL', urlSchema);
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.post('/api/BK9', async (req, res) => {
const { longURL, alias } = req.body;
let shortURL;
if (!alias) {
shortURL = nanoid(7);
} else {
const existingURL = await URL.findOne({ shortURL: alias });
if (existingURL) {
return res.status(400).json({ message: 'اسم التخصيص ماخوذ جرب اسما اخر.' });
}
shortURL = alias;
}
try {
const newURL = new URL({ longURL, shortURL });
await newURL.save();
res.json({ shortURL: `${req.protocol}://${req.get('host')}/${shortURL}` });
} catch (error) {
res.status(500).json({ message: 'خطأ في الخادم الداخلي' });
}
});
app.get('/:shortURL', async (req, res) => {
const { shortURL } = req.params;
try {
const url = await URL.findOne({ shortURL });
if (url) {
return res.redirect(url.longURL);
} else {
return res.status(404).send('لم يتم العثور عليه');
}
} catch (error) {
return res.status(500).json({ message: 'خطأ في الخادم الداخلي' });
}
});
app.get('/api/create', async (req, res) => {
const { url, alias } = req.query;
try {
let shortURL;
if (!alias) {
shortURL = nanoid(7);
} else {
const existingURL = await URL.findOne({ shortURL: alias });
if (existingURL) {
return res.status(400).json({ BK9: 'اسم التخصيص ماخوذ جرب اسما اخر.' });
}
shortURL = alias;
}
const newURL = new URL({ longURL: url, shortURL });
await newURL.save();
res.json({ BK9: `${req.protocol}://${req.get('host')}/${shortURL}` });
} catch (error) {
res.status(500).json({ BK9: 'خطأ في الخادم الداخلي' });
}
});
app.listen(PORT, () => {
console.log(`الخادم قيد التشغيل في http://localhost:${PORT}`);
});