koa session store in mongodb
koa實現(xiàn)session保存mongodb案例
由于此模塊依賴 koa-session
, 首先安裝 koa-session
npm install koa-session
在啟動文件中加載模塊
const session = require('koa-session');
const SessionStore = require('./core/sessionStore'); //假設(shè)文件sessionStore.js 文件保存在 core的根目錄
配置session
app.keys = ['some secret hurr'];
// session 配置信息
const CONFIG = {
key: 'koa:sess',
maxAge: 86400000,
overwrite: true,
httpOnly: true,
signed: true,
rolling: false,
};
// 以中間件的方式使用session
app.use(session(CONFIG, app));
設(shè)置session保存mongodb中
以上的配置并沒有吧session信息保存在mongodb中,所以繼續(xù)...
在koa-session的說明中, 如果要吧session信息保存在數(shù)據(jù)庫中, 可以自己實現(xiàn):
https://github.com/koajs/session#external-session-stores
在CONFIG中增加store參數(shù):
const CONFIG = {
key: 'koa:sess',
maxAge: 86400000,
overwrite: true,
httpOnly: true,
signed: true,
rolling: false,
store: new SessionStore({
collection: 'navigation', //數(shù)據(jù)庫集合
connection: Mongoose, // 數(shù)據(jù)庫鏈接實例
expires: 86400, // 默認(rèn)時間為1天
name: 'session' // 保存session的表名稱
})
};
測試并使用session
你可以在你想要用session的地方獲取到session
demo:
app.use(async (ctx, next) => {
// 獲取session對象
const session = ctx.session;
// 給session賦值
session.userInfo = {
name:'anziguoer',
email:'anziguoer@163.com',
age : 28
}
next();
})
接下來你查看mongodb數(shù)據(jù)庫中是否以保存了你想要的值
sessionStore.js 文件源碼, 你可以復(fù)制代碼到你項目的任何目錄, 只要保存引用正確即可
const schema = {
_id: String,
data: Object,
updatedAt: {
default: new Date(),
expires: 86400, // 1 day
type: Date
}
};
export default class MongooseStore {
constructor ({
collection = 'sessions',
connection = null,
expires = 86400,
name = 'Session'
} = {}) {
if (!connection) {
throw new Error('params connection is not collection');
}
const updatedAt = { ...schema.updatedAt, expires };
const { Mongo, Schema } = connection;
this.session = Mongo.model(name, new Schema({ ...schema, updatedAt }));
}
async destroy (id) {
const { session } = this;
return session.remove({ _id: id });
}
async get (id) {
const { session } = this;
const { data } = await session.findById(id);
return data;
}
async set (id, data, maxAge, { changed, rolling }) {
if (changed || rolling) {
const { session } = this;
const record = { _id: id, data, updatedAt: new Date() };
await session.findByIdAndUpdate(id, record, { upsert: true, safe: true });
}
return data;
}
static create (opts) {
return new MongooseStore(opts);
}
}