Add ability to insert a new short URL

parent 04b50eb2
Pipeline #52217774 failed with stage
in 1 minute and 2 seconds
......@@ -9,6 +9,7 @@ const path = require('path')
const pg = require('pg')
const pgpatcher = require('pg-patcher')
const log = require('logfmtr').default()
const zid = require('zid')
// local
const env = require('./env.js')
......@@ -27,20 +28,51 @@ const pool = new pg.Pool({
function patch (callback) {
log.info({ level: databasePatchLevel }, 'patching-database')
const opts = {
dir: path.join(__dirname, '..', 'schema'),
logger: console.log.bind(console)
return new Promise((resolve, reject) => {
const opts = {
dir: path.join(__dirname, '..', 'schema'),
logger: console.log.bind(console)
}
pgpatcher(pool, databasePatchLevel, opts, (err) => {
if (err) {
return callback ? callback(err) : reject(err)
}
return callback ? callback() : resolve()
})
})
}
// ----------------------------------------------------------------------------
// URLs
const insUrlSql = `INSERT INTO url(code, url) VALUES($1, $2) RETURNING *`
async function createUrl(url) {
try {
const params = [ zid(6), url ]
const result = await pool.query(insUrlSql, params)
return {
ok: true,
payload: result.rows[0],
}
}
catch(err) {
console.error(err)
return {
ok: false,
msg: "Internal Server Error",
}
}
pgpatcher(pool, databasePatchLevel, opts, callback)
}
// ----------------------------------------------------------------------------
module.exports = {
// `pg.Pool`
// general
pool,
// patch
patch
patch,
// insUrl
createUrl
}
// ----------------------------------------------------------------------------
......@@ -16,6 +16,7 @@ const yid = require('yid')
const pkg = require('../package.json')
const env = require('./env.js')
const stats = require('./stats.js')
const api = require('./api.js')
// --------------------------------------------------------------------------------------------------------------------
// setup
......@@ -82,18 +83,31 @@ app.get(
(req, res) => {
stats.home.inc()
res.render('index', {
menu: 'home'
menu: 'home',
form: {},
})
}
)
app.post(
'/',
(req, res) => {
async (req, res) => {
stats.shorten.inc()
res.render('index', {
menu: 'home'
})
const result = await api.createUrl(req.body.url)
if (!result.ok) {
res.render('index', {
menu: 'home',
err: result.msg,
form: {
url: req.body.url,
},
})
return
}
// all okay
res.redirect(`${env.baseUrl}/${result.payload.code}+`)
}
)
......
......@@ -6,5 +6,7 @@ block content
h2 Shorten your URLs
p This service is free to use.
form(action="/" method="post")
input.p-6.m-3.border.border-grey-dark.rounded(name="url" placeholder="https://...")
input.p-6.m-3.border.border-grey-dark.rounded(name="url" placeholder="https://..." value=form.url)
input.bg-blue-dark.text-white.p-6.m-3.rounded(type="submit" value="Shorten")
if err
p.text-red= err
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