我正在尝试为express.js节点应用实现会话存储 我的问题是:
这是我到目前为止提出的咖啡脚本,使用猫鼬,因为我这是我为应用程序选择的orm
express = require 'express'
mongoose = require "mongoose"
util = require "util"
# define session schema
SessionSchema = new mongoose.Schema
sid : { type: String, required: true, unique: true }
data : { type: String, default: '{}' }
expires : { type: Date, index: true }
module.exports =
class SessionStore extends express.session.Store
constructor: (options) ->
console.log "creating new session store"
options ?= {}
# refresh interval
options.interval ?= 60000
options.url ?= "mongodb://localhost/session"
# create dedicated session connection
connection = mongoose.createConnection options.url
# create session model
@Session = connection.model 'Session', SessionSchema
# remove expired session every cycles
removeExpires = => @Session.remove expires: { '$lte': new Date() }
setInterval removeExpires, options.interval
get: (sid, fn) ->
@Session.findOne sid: sid, (err, session) ->
if session?
try
fn null, JSON.parse session.data
catch err
fn err
else
fn err, session
set: (sid, data, fn) ->
doc =
sid: sid
data: JSON.stringify data
expires: data.cookie.expires
try
@Session.update sid: sid, doc, upsert: true, fn
catch err
fn err
destroy: (sid, fn) ->
@Session.remove { sid: sid }, fn
all: (fn) ->
@Session.find { expires: { '$gte': new Date() } }, [ 'sid' ], (err, sessions) ->
if sessions?
fn null, (session.sid for session in sessions)
else
fn err
clear: (fn) -> @Session.drop fn
length: (fn) -> @Session.count {}, fn
答案 0 :(得分:1)
我对节点很陌生,所以请稍等一下。
虽然不是直接面向会话,但我认为remember me tutorial on dailyjs会有所帮助。特别是他验证登录令牌的最后一段代码。
另外,我认为最好将JSON解析并存储为对象。如果您事先处理解析,应该更容易访问不同的cookie位。