咱們公司的大佬,搭建了一套基於koa2的node框架,雖說是重複造輪子,但適用當前場景的輪子纔是最好的,況且不少人還造不出輪子呢~ 大佬搭建的框架命名爲 Sponse
,其中有不少出色的設計,這裏對 session
的設計作個總結(實際上是爲了本身加深印象,學習大佬的設計)前端
Sponse意思是海綿,而咱們這套框架就如同海綿同樣,經過不斷吸取其餘框架的優秀設計豐滿本身node
作開發的小夥伴對這兩個應該在熟悉不過了,這兩個一塊兒構建起先後端狀態的聯繫,常見的如維護用戶登陸狀態,用戶登陸後,須要在服務端記錄下該用戶的登陸狀態,前端纔可使用須要登陸態的接口,此時,瀏覽器中的 cookie
就是查詢用戶是否登陸的憑證,在服務端,一般是將用戶狀態信息存儲在緩存中,簡單說,就是基於 cookie的session
redis
優秀的架構中,調用方式必須是友好的json
指望可以經過上下文直接調用,如:獲取session對象 ctx.session
; 設置session的值 ctx.session.name = name
後端
總體實現邏輯以下api
詳細代碼以下:瀏覽器
首先構建一個session對象緩存
核心方法:bash
save
用於同步cookiechanged
用於檢測session對象是否發生修改,爲了同步更新緩存中的值export class Session {
private _ctx;
isNew: boolean;
_json; // session對象的json串,用於比較session對象是否發生變化
constructor(ctx, obj) {
this._ctx = ctx;
if (!obj) this.isNew = true;
else {
for (const k in obj) {
this[k] = obj[k];
}
}
}
/**
* Save session changes by
* performing a Set-Cookie.
*
* @api private
*/
save() {
const ctx = this._ctx;
const json = this._json || JSON.stringify(this.inspect());
const sid = ctx.sessionId;
const opts = ctx.cookieOption;
const key = ctx.sessionKey;
if (ctx.cookies.get(key) !== sid) {
// 設置cookies的值
ctx.cookies.set(key, sid, opts);
}
return json;
};
/**
* JSON representation of the session.
*
* @return {Object}
* @api public
*/
inspect() {
const self = this;
const obj = {};
Object.keys(this).forEach(function (key) {
if ('isNew' === key) return;
if ('_' === key[0]) return;
obj[key] = self[key];
});
return obj;
}
/**
* Check if the session has changed relative to the `prev`
* JSON value from the request.
*
* @param {String} [prev]
* @return {Boolean}
* @api private
*/
changed(prev) {
if (!prev) return true;
this._json = JSON.stringify(this.inspect());
return this._json !== prev;
};
}
複製代碼
koa 固然是離不開中間件了,洋蔥模型酷炫到不行,很是方便的解決了session對象與緩存的同步cookie
decorator(app) {
app.keys = ['signed-key'];
const CONFIG = {
key: app.config.name + '.sess', /** (string) cookie key (default is koa:sess) */
cookie: {
// maxAge: 1000, /** (number) maxAge in ms (default is 1 days) */
overwrite: false, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
}
};
app.use(async (ctx, next) => {
let sess: Session;
let sid;
let json;
ctx.cookieOption = CONFIG.cookie;
ctx.sessionKey = CONFIG.key;
ctx.sessionId = null;
// 獲取cookie 對應的值, 即sessionID,就是緩存中的key
sid = ctx.cookies.get(CONFIG.key, ctx.cookieOption);
// 獲取session值
if (sid) {
try {
// 若key存在,則從緩存中獲取對應的值
json = await app.redisClient.get(sid);
} catch (e) {
console.log('從緩存中讀取session失敗: %s\n', e);
json = null;
}
}
// 實例化session
if (json) {
// 若緩存中有值,則基於緩存中的值構建session對象
ctx.sessionId = sid;
try {
sess = new Session(ctx, json);
} catch (err) {
if (!(err instanceof SyntaxError)) throw err;
sess = new Session(ctx, null);
}
} else {
sid = ctx.sessionId = sid || Uuid.gen();
sess = new Session(ctx, null);
}
// 爲了便於使用,將session掛載到上下文,這樣就能夠 ctx.session 這麼使用了
Object.defineProperty(ctx, 'session', {
get: function () {
return sess;
},
set: function (val) {
if (null === val) return sess = null;
if ('object' === typeof val) return sess = new Session(this, val);
throw new Error('this.session can only be set as null or an object.');
}
});
try {
await next();
} catch (err) {
throw err;
} finally {
if (null === sess) {
// 設置session=null表示清空session
ctx.cookies.set(CONFIG.key, '', ctx.cookieOption);
} else if (sess.changed(json)) {
// 檢查 session 是否發生變化,如有變化,更新緩存中的值
json = sess.save();
await app.redisClient.set(sid, json);
app.redisClient.ttl(sid);
// 設置redis值過時時間爲60分鐘
app.redisClient.expire(sid, 7200);
} else {
// session 續期
app.redisClient.expire(sid, 7200);
}
}
});
複製代碼
多多學習~ 點點進步~