From e9b9f011019d7038e07b6c2349266d214be16f5e Mon Sep 17 00:00:00 2001 From: Raymonzut <40148684+Raymonzut@users.noreply.github.com> Date: Thu, 14 May 2020 20:07:43 +0200 Subject: [PATCH] Convert express logic to fastify logic --- server/index.js | 23 ++++++++++++++++------- server/routes/api/posts.js | 11 +++++------ 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/server/index.js b/server/index.js index 847d3a4..528c95e 100644 --- a/server/index.js +++ b/server/index.js @@ -1,14 +1,23 @@ -const express = require('express') -const cors = require('cors') +const fastify = require('fastify')() -const app = express() - -app.use(cors()) +fastify.register(require('fastify-cors')) const posts = require('./routes/api/posts') -app.use('/posts', posts) +// Assuming they are all get requests +for (let [route, resolver] of posts.entries()) { + fastify.get('/posts' + route, resolver) +} const port = process.env.PORT || 5000 -app.listen(port, () => console.log(`Server started on port ${port}`)) +const start = async () => { + try { + await fastify.listen(port) + console.log(`Launched on port ${port} 🚀`) + } catch (err) { + fastify.log.error(err) + process.exit(1) + } +} +start() diff --git a/server/routes/api/posts.js b/server/routes/api/posts.js index a58a0a6..acef258 100644 --- a/server/routes/api/posts.js +++ b/server/routes/api/posts.js @@ -1,10 +1,9 @@ -const express = require('express') const fs = require('fs') -const router = express.Router() - const posts_dir = 'posts/' +const routes = new Map(); + if (!fs.existsSync(posts_dir)) throw Error(`Missing ${posts_dir}`) let posts = readPosts(); @@ -34,7 +33,7 @@ function notFoundResponse(res) { res.status(404).send('Sorry, can not find that') } -router.get('/', async (req, res) => { +routes.set('', async (req, res) => { if (req.query.sort === '-1' || req.query.sort === '1') { const posts_sorted = posts.sort((a, b) => { return new Date(a.date).getTime() - new Date(b.date).getTime() @@ -45,7 +44,7 @@ router.get('/', async (req, res) => { } }) -router.get('/:id', async (req, res) => { +routes.set('/:id', async (req, res) => { const re = /[0-9A-Fa-f]{24}/g if (!re.test(req.params.id)) { @@ -58,4 +57,4 @@ router.get('/:id', async (req, res) => { else res.send(results[0]) }) -module.exports = router +module.exports = routes