Add ability to get the URL and redirect or render a page

parent 4b55ac73
Pipeline #52263958 passed with stage
in 2 minutes and 18 seconds
......@@ -45,7 +45,7 @@ function patch (callback) {
// ----------------------------------------------------------------------------
// URLs
const insUrlSql = `INSERT INTO url(code, url) VALUES($1, $2) RETURNING *`
const insUrlSql = 'INSERT INTO url(code, url) VALUES($1, $2) RETURNING *'
async function createUrl (url) {
try {
......@@ -64,6 +64,26 @@ async function createUrl (url) {
}
}
const getUrlSql = 'SELECT * FROM url WHERE code = $1'
async function getUrl (url) {
try {
const params = [ url ]
const result = await pool.query(getUrlSql, params)
return {
ok: true,
msg: result.rows.length ? 'Retrieved' : 'Not Found',
payload: result.rows.length ? result.rows[0] : null
}
} catch (err) {
console.error(err)
return {
ok: false,
msg: 'Internal Server Error'
}
}
}
// ----------------------------------------------------------------------------
module.exports = {
......@@ -71,7 +91,8 @@ module.exports = {
pool,
patch,
// insUrl
createUrl
createUrl,
getUrl
}
// ----------------------------------------------------------------------------
......@@ -111,6 +111,38 @@ app.post(
}
)
app.get(
'/:code',
async (req, res, next) => {
// firstly, see if we need to knock the last '+' off
let codeOrPage = 'code'
let code = req.params.code
if (req.params.code.endsWith('+')) {
codeOrPage = 'page'
code = code.slice(0, code.length - 1)
}
// get this URL
const result = await api.getUrl(code)
if (!result.ok) {
next(new Error(result.msg))
return
}
// if not found
if (!result.payload) {
res.status(404).send('404 - Not Found')
return
}
if (codeOrPage === 'code') {
res.redirect(result.payload.url, 301)
} else {
res.send('page')
}
}
)
app.get(
'/stats',
(req, res, next) => {
......
......@@ -9,7 +9,7 @@ const pkg = require('../package.json')
const isProd = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging'
const isDev = !isProd
const apex = pkg.name
const apex = process.env.APEX || pkg.name
const protocol = process.env.PROTOCOL || 'https'
const baseUrl = `${protocol}://${apex}`
const port = process.env.PORT || 3000
......
......@@ -7,7 +7,8 @@
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "standard"
"test": "standard",
"fix": "standard --fix"
},
"dependencies": {
"body-parser": "^1.18.3",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment