Fastify is more and more popular and more performant than Express. I decide to learn Fastify to use it in a real project. All information about Fastify, you can find here
1) I create a directory fastifyBooks
mkdir fastifyBooks
cd fastifyBooks
npm init
2) When npm is initialized I can install fastify:
npm i fastify
3) It's time to create directory src in fastifyBooks and there I create my entry file app.js Here I will write my server.
mkdir src
cd src
touch app.js
4) Now I can use festify and I create a server in app.js
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' })
})
fastify.listen(3000, function (err) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
else{
console.log("server is on port 3000")
}
})
In this file, I use ES6 not CJ so I have this error when I want to start a server:
SyntaxError: Cannot use import statement outside a module
So I fix a bug, in package.json I put this line of code:
"type": "module",
And now my server works:
5) But I want also MongoDB in my little project so I install it:
npm install mongoose
6) In the directory fastifyBooks I create a directory config where I will put the file db.js
mkdir config
cd config
touch db.js
7) And I write a function to connect DB with server:
import mongoose from 'mongoose'
const db = "databaseàmoi";
const passwordDb="monpass"
const URI =`mongodb+srv://Deotyma:${passwordDb}@cluster0.uncn9.mongodb.net/${db}?retryWrites=true&w=majority`;
const MongoDBbooks = {
initialize: () => {
try {
const client = mongoose.connect(URI,
{
useNewUrlParser: true,
useUnifiedTopology: true
})
client.then(() => {return console.log(`successfully connected to DB: ${db}`)})
.catch((err)=> {console.log(err)})
} catch(err) {
throw Error(err)
}
}
}
export default MongoDBbooks;
7) Now I need to import it to app.js:
import MongoDBbooks from '../config/db.js';
the path is very important.
And now when I need to modify function witch run a server like that:
const start = async()=>{
try{
fastify.listen(3000);
MongoDBbooks.initialize();
}
catch(error){
fastify.log.error(err)
process.exit(1)
}
}
start();
At the same moment, I start a server and I initialise a connection with DB.
Now my application is ready for routes.
the example isn't bringing much to the table. More extensive real world example could be more beneficial.