Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules/
node_modules/
.env
44 changes: 18 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,38 @@
# URL Shortener App

This is starter code for URL Shortener Project.
## Overview

Fork this repository and use the given files to start with.
The URL Shortener App is a web service that converts long website addresses into shorter, more manageable links. This makes URLs easier to share and remember.

## Idea
## Features

A URL shortener website is a service that converts long website addresses into shorter, more manageable links. Users input a lengthy URL, and the website generates a condensed version, making it easier to share and remember.
- **URL Shortening**: Users can input a lengthy URL, and the app will generate a shorter version.

## Interface
- **Custom Aliases**: Users can provide a custom alias for their shortened URL, or let the app generate a random one.

The application interface consists of one page which contains:
- **Redirection**: Accessing the short URL redirects the user to the original long URL.

* A form to shorten the URL, which takes two inputs:
- the long version of the url
- the alias of the url (defaults to a random string)
* A table which contains the previously shortened URLs.
- **404 Error Handling**: If a non-existent short URL is accessed, a 404 error page is displayed.

## Short URLs
- **URL Management**: A table on the main page lists all previously shortened URLs for easy reference.

The short URLs are written in this form:
## Short URL Format

The short URLs are structured as follows:

```

http://localhost:3000/{alias}

```

## Application Logic

* When a client tries to access the short URL, they should be redirected to the original long URL.
* If the client accesses a URL which doesn't exist, a `404` error should be displayed.
* There's no required authentication or authorization to generate short URLs.
## Usage

## Project Criteria
1\. **Submit URL**: Enter a long URL and optionally an alias in the provided form.

- [ ] The application runs locally without any crashes
- [ ] The application logic is implemented correctly
- [ ] The application uses server-side rendering
- [ ] The application uses a MongoDB database
2\. **Generate Short URL**: Submit the form to create a shortened URL.

## Project Evaluation (50 pts.)
3\. **Access Short URL**: Use the short URL to be redirected to the original long URL.

* Project Completeness (25 pts.)
* Clean Code and Modulation (15 pts.)
* Descriptive Git Commit Messages (10 pts.)
* Nice touches (5 pts. bonus)
4\. **Error Handling**: Encounter a 404 error if a short URL does not exist in the database.
23 changes: 21 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const mongoose = require('mongoose');
const indexRouter = require('./routes/index');
require('dotenv').config();


const app = express();

Expand All @@ -17,14 +19,31 @@ app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);




//Database Connection
const mongoURI = process.env.mongoURI
mongoose.connect(mongoURI)
.then(() => {
console.log("Connected Successfully to the Database.")
app.listen(3000)
})
.catch((err) => {
console.log(err)
})



// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});



// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
Expand Down
65 changes: 65 additions & 0 deletions controllers/URL_controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const URL = require('../models/URL_Model');


/* GET home page. */
const get_home = (req, res) => {
URL.find()
.then((links) => {
res.render('index', { title: 'Express', links });
})
.catch((err) => {
res.render('error', { error: "Failed to load home page" })
})

}


/* Save the data coming from the form in the Database */
const post_data = (req, res) => {

const long = req.body.urlInput
const alias = req.body.aliasInput
const url = new URL({ long, alias })
url.save()
.then(() => {
res.redirect('/')
console.log("Link added successfully to the Database.")
})
.catch((err) => {
res.render('error', { error: "Failed to save data to the database" })
})
}


/* Redirecting the user when clicking the short link */
const get_redirect = (req, res) => {
const alias = req.params.alias
URL.findOne({ alias })
.then((link) => {
console.log(link)
if (link) {
res.redirect(`${link.long}`)
} else {
res.render('error', { error: "Invalid alias" })
}
})
.catch((err) => {
res.render('error', { error: "Failed to redirect" })
})
}


/* Deleting URL from Database */
const delete_link = (req, res) => {
const alias = req.body.alias
URL.deleteOne({ alias })
.then(() => {
res.status(200).json("Done")
})
.catch((err) => {
console.log(err)
res.render('error', { error: "Failed to delete the item" })
})
}

module.exports = { get_home, post_data, get_redirect, delete_link }
12 changes: 12 additions & 0 deletions models/URL_Model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const mongoose = require('mongoose')

const Schema = mongoose.Schema

const URLSchema = new Schema({
long: { type: String, required: true, minLentgh: 5 },
alias: { type: String, required: true, minLentgh: 5 }
}, { timestamps: true })

URL = mongoose.model('URL', URLSchema)

module.exports = URL;
Loading