Implement routes, use ShortID
This commit is contained in:
parent
2b45cef3f7
commit
0cea1dcf76
1 changed files with 23 additions and 10 deletions
|
|
@ -1,15 +1,18 @@
|
||||||
import { Application } from 'express'
|
import { Application } from 'express'
|
||||||
|
import shortid from 'shortid'
|
||||||
import Urls from './schema'
|
import Urls from './schema'
|
||||||
|
|
||||||
export default (app: Application) => {
|
export default (app: Application) => {
|
||||||
|
app.get('/', async (req, res) => {
|
||||||
app.get('/', async(req, res) => {
|
res.render('home.ejs')
|
||||||
res.render('home')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get('/:id', async (req, res) => {
|
app.get('/:shortid', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const urlObj = await Urls.findById(req.params.id);
|
const urlObj = await Urls.findOne({
|
||||||
|
shortid: req.params.shortid
|
||||||
|
});
|
||||||
|
|
||||||
if (urlObj) {
|
if (urlObj) {
|
||||||
res.redirect(urlObj.url)
|
res.redirect(urlObj.url)
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -24,11 +27,21 @@ export default (app: Application) => {
|
||||||
})
|
})
|
||||||
|
|
||||||
app.post('/add', async (req, res) => {
|
app.post('/add', async (req, res) => {
|
||||||
if (req.body.url) {
|
if (req.query.url) {
|
||||||
const urlObj = new Urls()
|
/* Save DB room, try to find one first: */
|
||||||
urlObj.url = req.body.url
|
const tmp = await Urls.findOne({
|
||||||
await urlObj.save()
|
url: String(req.query.url)
|
||||||
res.status(200).send(urlObj)
|
})
|
||||||
|
|
||||||
|
if (tmp) {
|
||||||
|
res.status(200).send(tmp)
|
||||||
|
} else {
|
||||||
|
const urlObj = new Urls()
|
||||||
|
urlObj.shortid = shortid.generate()
|
||||||
|
urlObj.url = String(req.query.url)
|
||||||
|
await urlObj.save()
|
||||||
|
res.status(200).send(urlObj)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
res.status(422).end()
|
res.status(422).end()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue