【问题标题】:What to write set/get/destroy methods on fastify-session to store the session into MongoDB?在 fastify-session 上编写 set/get/destroy 方法以将会话存储到 MongoDB 中?
【发布时间】:2021-02-28 17:10:31
【问题描述】:

我正在使用 TypeScript。

我想将会话存储到 mongoDB 中。不在记忆中。 我阅读了文档,但我无法弄清楚。 (https://github.com/SerayaEryn/fastify-session)

如何将会话存储到 mongoDB 中?

编写访问mongoDB并使用sessionId插入记录的set方法? 获取和销毁

我写的。对我来说似乎效果很好。有什么问题吗?

import fastifySession from 'fastify-session';
import mongoose from 'mongoose';
import Session from './schemas/sessionSchema';

mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);

class Database {
    constructor() {
        this.connect();
        this.sessionStore = new SessionStore();
    }

    sessionStore: fastifySession.SessionStore;

    connect() {
        mongoose.connect('mongodb://127.0.0.1:27017/mydb')
            .then(() => {
                console.log('Database conneciton successful');
            })
            .catch((err) => {
                console.log(`Database connection error ${err}`)
            })
    }
}

class SessionStore implements fastifySession.SessionStore {

    set(sessionId: string, session: any, callback: (err?: Error) => void) {
        console.log('set');
        Session.findOneAndUpdate({ _id: sessionId }, { _id: sessionId, session: JSON.stringify(session) }, { upsert: true })
            .then(() => {
                callback();
            })
            .catch(callback);
    }

    get(sessionId: string, callback: (err?: Error, session?: any) => void) {
        console.log('get');
        Session.findOne({ _id: sessionId })
            .then((result) => {
                if (result) {
                    callback(undefined, JSON.parse(result.session));

                } else {
                    callback();
                }
            })
            .catch(callback);
    }

    destroy(sessionId: string, callback: (err?: Error) => void) {
        console.log('destroy');
        Session.findOneAndDelete({ _id: sessionId })
            .then(() => { callback(); })
            .catch(callback);
    }
}

export default new Database();

import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const sessionSchema = new Schema(
    {
        _id: { type: String },
        expires: { type: Date },
        session: { type: String }
    }
);

const session = mongoose.model<ISessionDocument>('Session', sessionSchema);

interface ISessionDocument extends mongoose.Document {
    _id: string,
    expires: Date,
    session: string
}

export default session;
import fastify from 'fastify';
import fastifyCookie from 'fastify-cookie';
import fastifySession from 'fastify-session';

import database from './database';

const PORT = 8080;
const app = fastify();

app.register(fastifyCookie);
app.register(fastifySession, {
    secret: 'mysecretmysecretmysecretmysecret',
    cookie: { secure: false },
    // false for develop on HTTP.

    store: database.sessionStore
});

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}`);
});

【问题讨论】:

  • 你能分享你的代码吗?
  • 感谢回复!
  • 我添加了一部分代码

标签: mongodb typescript fastify


【解决方案1】:

您是否尝试过使用“connect-monogo”?使用 connect-monogo 包你可以配置 fastify-session 的 store 选项:

app.register(fastifySession, {
    cookieName: 'YOUR_SESSION_COOKIE_NAME',
    secret: 'YOUR_SESSION_SECRET",
    saveUninitialized: false,
    cookie: {
        path: '/',
        secure: process.env.NODE_ENV === 'production',
        maxAge: MAX_SESSION_AGE,
    },
    store: new MongoStore({
        mongoUrl: 'YOUR_MONGODB_URL',
    }),
});

【讨论】:

    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多