Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. 'use strict'
  2.  
  3. const express = require("express")
  4. const fs = require('fs')
  5. const shortid = require('shortid')
  6. const pgp = require('pg-promise')()
  7.  
  8. const app = express()
  9. const herokuUrl = 'http://localhost/'
  10.  
  11. const cn = {
  12. host: 'localhost',
  13. port: 5432,
  14. database: 'postgres',
  15. user: 'postgres',
  16. password: ''
  17. }
  18. let db = pgp(cn)
  19.  
  20. app.use(express.static('.'))
  21.  
  22. function createUrl(req, res){
  23. let url = req.params[0]
  24. let id = shortid.generate()
  25. let query = "insert into theurls values(\'" +id+"\',\'"+url+"\')"
  26.  
  27. db.none(query)
  28. .then(function(){
  29. res.json({
  30. "original_url": herokuUrl + url,
  31. "short_url": herokuUrl + id
  32. })
  33. })
  34. .catch(function(error){
  35. res.end(error)
  36. })
  37.  
  38.  
  39. }
  40.  
  41. function getUrl (req, res){
  42. let query = "select url from theurls where id=\'"+req.params.aID+"\'"
  43. db.result(query)
  44. .then(function(data){
  45. let result = /^http/.test(data.rows[0].url)
  46.  
  47. if(!result){
  48. res.redirect('http://'+data.rows[0].url)
  49. }else{
  50. res.redirect(data.rows[0].url)
  51. }
  52. })
  53. .catch(function(error){
  54. res.end(error)
  55. })
  56. }
  57.  
  58. app.get("/new/*", createUrl)
  59. app.get('/:aID', getUrl)
  60.  
  61. app.get('/', function(req, res){
  62. res.set('content-type','text/html')
  63. res.send(fs.readFileSync(__dirname + '/index.html','utf8'))
  64. })
  65.  
  66. app.listen(process.env.PORT || 80, function(){
  67. console.log('server listening')
  68. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement