-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Better DB - Use ephermal id for testing
- Loading branch information
Showing
5 changed files
with
53 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
'use strict' | ||
|
||
const EE = require('events').EventEmitter | ||
|
||
class DB extends EE { | ||
constructor (opt) { | ||
super() | ||
this.data = {} | ||
this.maxAge = opt.maxAge | ||
this.last_used = {} | ||
setInterval(this._loop.bind(this), 100) | ||
} | ||
get (key) { | ||
if (!this.data[key]) return false | ||
this.last_used[key] = new Date().getTime() | ||
return this.data[key] | ||
} | ||
get keys() { | ||
return Object.keys(this.data) | ||
} | ||
peek (key) { | ||
return this.data[key] || false | ||
} | ||
set (key, value) { | ||
this.data[key] = value | ||
this.last_used[key] = new Date().getTime() | ||
} | ||
remove (key) { | ||
delete this.last_used[key] | ||
return delete this.data[key] | ||
} | ||
_loop () { | ||
const curTime = new Date().getTime() | ||
const evictTime = curTime - this.maxAge | ||
for (const key in this.data) { | ||
if (this.last_used[key] <= evictTime) { | ||
this.emit('evict', {key, value: this.data[key]}) | ||
this.remove(key) | ||
} | ||
} | ||
} | ||
} | ||
|
||
module.exports = DB |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters