#4 added additional route for get request to shortUrl

parent 51fb545b
import express, {Express} from 'express';
import express, {Express, Request, Response} from 'express';
import {linksRouter} from './routes/links.router';
import {connectToDatabase} from './services/database.service';
import {collections, connectToDatabase} from './services/database.service';
const app: Express = express();
app.use(express.json());
......@@ -12,6 +12,25 @@ connectToDatabase()
app.listen(process.env.PORT, () => {
console.log(`Server started at http://localhost:${process.env.PORT}`);
});
app.get('/:shortUrl', async (req: Request, res: Response) => {
try {
const shortUrl = req.params.shortUrl;
const link = await collections.links?.findOne({
shortUrl: `${process.env.BASE_URL}/${shortUrl}`,
});
if (link) {
res.status(301).redirect(link.originalUrl);
} else {
res.status(404).send('Not found');
}
} catch (err: unknown) {
const error = err as Error;
console.log(error);
}
});
})
.catch((error: Error) => {
console.log('Database connection failed');
......
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