convert to eventemitter format with caching

This commit is contained in:
Konstantin Käfer
2011-07-08 21:40:40 +02:00
parent 4abe725ed8
commit a647e84431
+29 -6
View File
@@ -26,13 +26,14 @@ function hash(z, x, y) {
module.exports = MBTiles; module.exports = MBTiles;
MBTiles.utils = require('./utils'); MBTiles.utils = require('./utils');
var cache = {};
// Provides access to an mbtiles database file. // Provides access to an mbtiles database file.
// - uri: A parsed URL hash, the only relevant part is `pathname`. // - uri: A parsed URL hash, the only relevant part is `pathname`.
// - callback: Will be called when the resources have been acquired // - callback: Will be called when the resources have been acquired
// or acquisition failed. // or acquisition failed.
require('util').inherits(MBTiles, require('events').EventEmitter)
function MBTiles(uri, callback) { function MBTiles(uri, callback) {
var mbtiles = this;
if (typeof callback !== 'function') callback = noop;
if (typeof uri === 'string') uri = url.parse(uri); if (typeof uri === 'string') uri = url.parse(uri);
if (!uri.pathname) { if (!uri.pathname) {
@@ -46,20 +47,42 @@ function MBTiles(uri, callback) {
delete uri.host; delete uri.host;
} }
if (!cache[uri.pathname]) {
cache[uri.pathname] = this;
this._open(uri);
}
var mbtiles = cache[uri.pathname];
if (!mbtiles.open) {
mbtiles.once('open', callback);
} else {
callback(null, mbtiles);
}
return undefined;
}
MBTiles.prototype._open = function(uri) {
var mbtiles = this;
function error(err) {
process.nextTick(function() {
mbtiles.emit('open', err);
});
}
this.filename = uri.pathname; this.filename = uri.pathname;
Step(function() { Step(function() {
mbtiles._db = new sqlite3.cached.Database(mbtiles.filename, this); mbtiles._db = new sqlite3.cached.Database(mbtiles.filename, this);
}, function(err) { }, function(err) {
if (err) return callback(err); if (err) return error(err);
mbtiles._setup(this); mbtiles._setup(this);
}, function(err) { }, function(err) {
if (err) return callback(err); if (err) return error(err);
fs.stat(mbtiles.filename, this); fs.stat(mbtiles.filename, this);
}, function(err, stat) { }, function(err, stat) {
if (err) return callback(err); if (err) return error(err);
mbtiles._stat = stat; mbtiles._stat = stat;
mbtiles.open = true; mbtiles.open = true;
return callback(null, mbtiles); mbtiles.emit('open', null, mbtiles);
}); });
return undefined; return undefined;