I am working with TypeScript and trying to find a way to store sessions in mongoDB rather than in memory. After reading the documentation, I still couldn't figure it out (https://github.com/SerayaEryn/fastify-session). Can anyone guide me on how to achieve this?
Should I create a set method that accesses mongoDB to insert records with sessionId and also implement get and destroy methods? I have implemented them and they seem to be working fine. Is there anything wrong with my approach?
import fastifySession from 'fastify-session';
import mongoose from 'mongoose';
import Session from './schemas/sessionSchema';
// MongoDB connection setup
...
class Database {
constructor() {
this.connect();
this.sessionStore = new SessionStore();
}
sessionStore: fastifySession.SessionStore;
connect() {
// Connecting to MongoDB
}
}
class SessionStore implements fastifySession.SessionStore {
// Methods for set, get, and destroy sessions in mongoDB
...
export default new Database();
// Defining schema and model for session data in mongoDB
...
export default session;
// Setting up fastify server with cookies and session management
...
app.get('/', async (req) => {
return `hello`;
});
app.listen(PORT, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});