Move to PUT, other changes

This commit is contained in:
oitsjustjose 2020-07-06 10:18:57 -05:00
commit e294d98fdf
3 changed files with 26 additions and 18 deletions

View file

@ -11,7 +11,7 @@ export default (app: Application) => {
try {
const urlObj = await Urls.findOne({
shortid: req.params.shortid
});
})
if (urlObj) {
res.redirect(urlObj.url)
@ -19,28 +19,26 @@ export default (app: Application) => {
res.status(404).end()
}
} catch (ex) {
console.error(ex);
console.error(ex)
res.status(500).send({
error: ex
})
}
})
app.post('/add', async (req, res) => {
if (req.query.url) {
/* Save DB room, try to find one first: */
app.put('/', async (req, res) => {
if (req.body.url) {
const tmp = await Urls.findOne({
url: String(req.query.url)
url: String(req.body.url)
})
if (tmp) {
res.status(200).send(tmp)
res.json(tmp)
} else {
const urlObj = new Urls()
urlObj.shortid = shortid.generate()
urlObj.url = String(req.query.url)
await urlObj.save()
res.status(200).send(urlObj)
const newUrl = new Urls()
newUrl.url = String(req.body.url)
await newUrl.save()
res.json(newUrl)
}
} else {
res.status(422).end()

View file

@ -1,7 +1,12 @@
import mongoose, { Document, Schema, Types } from 'mongoose'
import shortid from 'shortid'
const UrlSchema: Schema = new Schema({
shortid: String,
shortid: {
type: String,
default: shortid.generate,
unique: true
},
url: String
})

View file

@ -5,14 +5,19 @@ window.addEventListener('load', () => {
form.addEventListener('submit', async (evt) => {
evt.preventDefault();
try {
const resp = await fetch(`/add?url=${urlIn.value}`, {
method: 'POST',
const resp = await fetch('/', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: url
"url": String(urlIn.value)
})
});
const json = await resp.json();
urlIn.value = `${location.origin}/${json.shortid}`;
if (resp.status == 200) {
const json = await resp.json();
urlIn.value = `${location.origin}/${json.shortid}`;
} else {
alert(`There was a server error: ${resp.statusText}`);
}
} catch (ex) {
alert(`There was an error processing your request: ${ex}`);
console.error(ex);