Skip to content

Instantly share code, notes, and snippets.

@rikkimax
Created January 2, 2014 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rikkimax/8216999 to your computer and use it in GitHub Desktop.
Save rikkimax/8216999 to your computer and use it in GitHub Desktop.
Session storage utilising Dvorm and Vibe.
module common.session;
import dvorm;
@dbname("Session")
class SessionModel {
@id {
string key;
string name;
}
string value;
mixin OrmModel!SessionModel;
static SessionModel[] getSessionById(string id) {
return SessionModel.query()
.key_eq(id)
.find();
}
static void removeBySessionid(string id) {
foreach(sm; getSessionById(id)) {
sm.remove();
}
}
}
module common.sessionstorage;
import common.session;
import vibe.http.session;
import std.conv : to;
import std.variant;
class DbSessionStore : SessionStore {
Session create() {
return createSessionInstance(null);
}
/// Opens an existing session.
Session open(string id) {
return createSessionInstance(id);
}
/// Sets a name/value pair for a given session.
void set(string id, string name, Variant value) {
SessionModel sm = new SessionModel;
sm.key = id;
sm.name = name;
sm.value = value.get!string();
sm.save();
}
/// Returns the value for a given session key.
Variant get(string id, string name, Variant defaultVal = null) {
if (id !is null && name !is null) {
SessionModel[] sm = SessionModel.find(id, name);
if (sm.length == 1) {
return Variant(sm[0].value);
} else {
return defaultVal;
}
}
return defaultVal;
}
/// Determines if a certain session key is set.
bool isKeySet(string id, string key) const {
return SessionModel.find(id, key).length == 1;
}
/// Terminates the given sessiom.
void destroy(string id) {
if (id != "")
SessionModel.removeBySessionid(id);
}
/// Iterates all key/value pairs stored in the given session.
int delegate(int delegate(ref string key, ref Variant value)) iterateSession(string id) {
int iterator(int delegate(ref string key, ref Variant value) del) {
foreach(ref sm; SessionModel.getSessionById(id)) {
auto value = Variant(sm.value);
if (auto ret = del(sm.name, value) != 0)
return ret;
}
return 0;
}
return &iterator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment