Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict'
- const express = require("express")
- const fs = require('fs')
- const shortid = require('shortid')
- const pgp = require('pg-promise')()
- const app = express()
- const herokuUrl = 'http://localhost/'
- const cn = {
- host: 'localhost',
- port: 5432,
- database: 'postgres',
- user: 'postgres',
- password: ''
- }
- let db = pgp(cn)
- app.use(express.static('.'))
- function createUrl(req, res){
- let url = req.params[0]
- let id = shortid.generate()
- let query = "insert into theurls values(\'" +id+"\',\'"+url+"\')"
- db.none(query)
- .then(function(){
- res.json({
- "original_url": herokuUrl + url,
- "short_url": herokuUrl + id
- })
- })
- .catch(function(error){
- res.end(error)
- })
- }
- function getUrl (req, res){
- let query = "select url from theurls where id=\'"+req.params.aID+"\'"
- db.result(query)
- .then(function(data){
- let result = /^http/.test(data.rows[0].url)
- if(!result){
- res.redirect('http://'+data.rows[0].url)
- }else{
- res.redirect(data.rows[0].url)
- }
- })
- .catch(function(error){
- res.end(error)
- })
- }
- app.get("/new/*", createUrl)
- app.get('/:aID', getUrl)
- app.get('/', function(req, res){
- res.set('content-type','text/html')
- res.send(fs.readFileSync(__dirname + '/index.html','utf8'))
- })
- app.listen(process.env.PORT || 80, function(){
- console.log('server listening')
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement