Created
December 9, 2018 09:04
-
-
Save flymop/afa193e4e237677ce256070b08983a88 to your computer and use it in GitHub Desktop.
simple tools to shorten url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const app = express() | |
const sqlite = require('sqlite3') | |
const bodyPraser = require('body-parser') | |
app.use(bodyPraser.urlencoded({extended: false})) | |
app.use(bodyPraser.json()) | |
const PORT = 8114 | |
let db = new sqlite.Database('./shorturl.db' , sqlite.OPEN_READWRITE | sqlite.OPEN_CREATE , (err)=> { | |
if (err) { | |
console.err('error to connect sqlite') | |
} | |
console.log('connect to sqlite success') | |
}) | |
db.run("create table if not exists short_url(short_url varchar(50),url varchar(50))") | |
let insertOrUpdate = function(short_url, url, res) { | |
db.get(`select * from short_url where short_url='${short_url}'`, (err, row)=>{ | |
if (row) { | |
db.run(`update short_url set url='${url}' where short_url='${short_url}'`, (err) =>{ | |
if (err) { | |
res.status(500).json({error: err.message}) | |
} | |
}) | |
} else { | |
db.run(`insert into short_url(short_url,url) values ('${short_url}','${url}')`, (err) =>{ | |
if (err) { | |
res.status(500).json({error: err.message}) | |
} | |
}) | |
} | |
})} | |
app.post('/set/', function(req, res, next) { | |
let url = req.body.url | |
// let shortedURL = req.body.shortedURL || Math.random().toString(36).substring(2,8) | |
let shortedURL = req.body.shortedURL | |
console.log(url) | |
console.log(shortedURL) | |
insertOrUpdate(shortedURL, url) | |
res.status(200).json({error: 'success'}) | |
}) | |
app.get('/:shortedURL', function(req, res,next) { | |
let shortedURL = req.params.shortedURL | |
db.get(`select url from short_url where short_url='${shortedURL}' limit 1`, (err,row) =>{ | |
if (err) { | |
console.error('fail to find record' + err.message) | |
} | |
console.log(`url = ${row.url}` ) | |
res.redirect(row.url) | |
}) | |
}) | |
app.listen(PORT, () =>{ | |
console.log("url shorten service start on port " + PORT) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment