Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2022
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require('dotenv').config();
  2. const MONGO_URI = process.env['MONGO_URI'];
  3. const PORT = process.env['PORT'];
  4. const express = require('express');
  5. const mongoose = require('mongoose');
  6. const { Schema } = mongoose;
  7. const cors = require('cors');
  8. const app = express();
  9. const urlValidator = require('./urlValidator.js')
  10.  
  11. mongoose.connect(MONGO_URI);
  12.  
  13. const Url = mongoose.model('urls', new Schema({
  14.   original_url: { type: String, required: true },
  15.   short_url: { type: String, required: true }
  16. }))
  17.  
  18. // Basic Configuration
  19. const port = PORT || 3000;
  20.  
  21. app.use(cors());
  22. app.use(express.json());
  23. app.use(express.urlencoded({ extended: false }));
  24.  
  25. app.use('/public', express.static(`${process.cwd()}/public`));
  26.  
  27. app.get('/', function (req, res) {
  28.   res.sendFile(process.cwd() + '/views/index.html');
  29. });
  30.  
  31. // Your first API endpoint
  32. app.get('/api/hello', function (req, res) {
  33.   res.json({ greeting: 'hello API' });
  34. });
  35.  
  36. app.post('/api/shorturl', async (req, res) => {
  37.   const url = req.body.url
  38.   const validation = urlValidator(url)
  39.   if (!validation) return res.send({ error: 'invalid url' })
  40.   const isRepeateUrl = await Url.findOne({ original_url: url })
  41.   if (isRepeateUrl) return res.json({
  42.     original_url: isRepeateUrl.original_url,
  43.     short_url: isRepeateUrl.short_url
  44.   })
  45.   const latestUrl = await Url.find({}).sort({ short_url: 'desc' }).limit(1)
  46.   let newShortUrl = '1'
  47.   if (latestUrl[0]) newShortUrl = (parseInt(latestUrl[0].short_url) + 1) + ''
  48.   const newUrl = new Url({
  49.     original_url: url,
  50.     short_url: newShortUrl
  51.   })
  52.   let result
  53.   try {
  54.     result = await newUrl.save()
  55.   } catch (err) {
  56.     return console.error('ERRORR F', err)
  57.   }
  58.   return res.send({
  59.     original_url: result.original_url,
  60.     short_url: result.short_url
  61.   })
  62. })
  63.  
  64. app.get('/api/shorturl/:short_url?', async (req, res) => {
  65.   try {
  66.     const short_urlParam = req.params.short_url
  67.     const url = await Url.findOne({ short_url: Number(short_urlParam) }).exec()
  68.     console.log('URLLLLLLLLLLL', url)
  69.     if (url) return res.redirect(url.original_url)
  70.     return res.send({ message: 'Not Found' })
  71.   } catch (e) {
  72.     return console.error('LAST  ---- ', e)
  73.   }
  74.  
  75. })
  76.  
  77. app.listen(port, function () {
  78.   console.log(`Listening on port ${port}`);
  79. });
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement