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 shortid from 'shortid'
|
||||
import Urls from './schema'
|
||||
|
||||
export default (app: Application) => {
|
||||
|
||||
app.get('/', async(req, res) => {
|
||||
res.render('home')
|
||||
app.get('/', async (req, res) => {
|
||||
res.render('home.ejs')
|
||||
})
|
||||
|
||||
app.get('/:id', async (req, res) => {
|
||||
app.get('/:shortid', async (req, res) => {
|
||||
try {
|
||||
const urlObj = await Urls.findById(req.params.id);
|
||||
const urlObj = await Urls.findOne({
|
||||
shortid: req.params.shortid
|
||||
});
|
||||
|
||||
if (urlObj) {
|
||||
res.redirect(urlObj.url)
|
||||
} else {
|
||||
|
|
@ -24,11 +27,21 @@ export default (app: Application) => {
|
|||
})
|
||||
|
||||
app.post('/add', async (req, res) => {
|
||||
if (req.body.url) {
|
||||
const urlObj = new Urls()
|
||||
urlObj.url = req.body.url
|
||||
await urlObj.save()
|
||||
res.status(200).send(urlObj)
|
||||
if (req.query.url) {
|
||||
/* Save DB room, try to find one first: */
|
||||
const tmp = await Urls.findOne({
|
||||
url: String(req.query.url)
|
||||
})
|
||||
|
||||
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 {
|
||||
res.status(422).end()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue