Convert express logic to fastify logic

master
Raymonzut 5 years ago
parent 0dd0ac74e1
commit e9b9f01101
No known key found for this signature in database
GPG Key ID: 97CF2D8BE2C69FC7
  1. 23
      server/index.js
  2. 11
      server/routes/api/posts.js

@ -1,14 +1,23 @@
const express = require('express') const fastify = require('fastify')()
const cors = require('cors')
const app = express() fastify.register(require('fastify-cors'))
app.use(cors())
const posts = require('./routes/api/posts') 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 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()

@ -1,10 +1,9 @@
const express = require('express')
const fs = require('fs') const fs = require('fs')
const router = express.Router()
const posts_dir = 'posts/' const posts_dir = 'posts/'
const routes = new Map();
if (!fs.existsSync(posts_dir)) throw Error(`Missing ${posts_dir}`) if (!fs.existsSync(posts_dir)) throw Error(`Missing ${posts_dir}`)
let posts = readPosts(); let posts = readPosts();
@ -34,7 +33,7 @@ function notFoundResponse(res) {
res.status(404).send('Sorry, can not find that') 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') { if (req.query.sort === '-1' || req.query.sort === '1') {
const posts_sorted = posts.sort((a, b) => { const posts_sorted = posts.sort((a, b) => {
return new Date(a.date).getTime() - new Date(b.date).getTime() 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 const re = /[0-9A-Fa-f]{24}/g
if (!re.test(req.params.id)) { if (!re.test(req.params.id)) {
@ -58,4 +57,4 @@ router.get('/:id', async (req, res) => {
else res.send(results[0]) else res.send(results[0])
}) })
module.exports = router module.exports = routes

Loading…
Cancel
Save