Convert express logic to fastify logic
This commit is contained in:
+16
-7
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user