92 lines
2.2 KiB
JavaScript
92 lines
2.2 KiB
JavaScript
const express = require('express');
|
|
const mongoose = require('mongoose');
|
|
const shortid = require('shortid');
|
|
const Url = require('./models/Url');
|
|
require('dotenv').config();
|
|
|
|
const app = express();
|
|
const port = 9043;
|
|
|
|
// Middleware to parse JSON
|
|
app.use(express.json());
|
|
|
|
// MongoDB connection
|
|
mongoose.connect('mongodb://127.0.0.1:27017/shorturl');
|
|
|
|
const db = mongoose.connection;
|
|
db.on('error', console.error.bind(console, 'connection error:'));
|
|
db.once('open', () => {
|
|
console.log('Connected to MongoDB');
|
|
});
|
|
|
|
// Supported domains
|
|
const supportedDomains = [
|
|
's.dcord.lol',
|
|
's.peer.rest',
|
|
's.njs.lol', // default domain
|
|
's.dlinux.pro'
|
|
];
|
|
|
|
// Middleware to check API key
|
|
const validateApiKey = (req, res, next) => {
|
|
const apiKey = req.headers['x-api-key'];
|
|
if (apiKey && apiKey === process.env.API_KEY) {
|
|
next();
|
|
} else {
|
|
res.status(403).json({ error: 'Forbidden' });
|
|
}
|
|
};
|
|
|
|
// Route to create a short URL
|
|
app.post('/api/shorturl', validateApiKey, async (req, res) => {
|
|
const { longUrl, domain } = req.body;
|
|
|
|
if (!longUrl) {
|
|
return res.status(400).json({ error: 'Invalid URL' });
|
|
}
|
|
|
|
// Validate domain, default to 's.dcord.rest' if not provided or invalid
|
|
const selectedDomain = supportedDomains.includes(domain) ? domain : 's.dlinux.pro';
|
|
|
|
try {
|
|
let url = await Url.findOne({ longUrl });
|
|
|
|
if (url) {
|
|
return res.json({ shortUrl: `https://${selectedDomain}/${url.shortId}` });
|
|
}
|
|
|
|
const shortId = shortid.generate();
|
|
url = new Url({
|
|
longUrl,
|
|
shortId,
|
|
});
|
|
|
|
await url.save();
|
|
res.json({ shortUrl: `https://${selectedDomain}/${shortId}` });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.status(500).json({ error: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Route to handle redirect
|
|
app.get('/:shortId', async (req, res) => {
|
|
const { shortId } = req.params;
|
|
|
|
try {
|
|
const url = await Url.findOne({ shortId });
|
|
|
|
if (url) {
|
|
return res.redirect(301, url.longUrl);
|
|
}
|
|
|
|
res.status(404).json({ error: 'URL not found' });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.status(500).json({ error: 'Server error' });
|
|
}
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server running on port ${port}`);
|
|
}); |