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

View File

@@ -26,13 +26,14 @@ function hash(z, x, y) {
module.exports = MBTiles;
MBTiles.utils = require('./utils');
var cache = {};
// Provides access to an mbtiles database file.
// - uri: A parsed URL hash, the only relevant part is `pathname`.
// - callback: Will be called when the resources have been acquired
// or acquisition failed.
require('util').inherits(MBTiles, require('events').EventEmitter)
function MBTiles(uri, callback) {
var mbtiles = this;
if (typeof callback !== 'function') callback = noop;
if (typeof uri === 'string') uri = url.parse(uri);
if (!uri.pathname) {
@@ -46,20 +47,42 @@ function MBTiles(uri, callback) {
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;
Step(function() {
mbtiles._db = new sqlite3.cached.Database(mbtiles.filename, this);
}, function(err) {
if (err) return callback(err);
if (err) return error(err);
mbtiles._setup(this);
}, function(err) {
if (err) return callback(err);
if (err) return error(err);
fs.stat(mbtiles.filename, this);
}, function(err, stat) {
if (err) return callback(err);
if (err) return error(err);
mbtiles._stat = stat;
mbtiles.open = true;
return callback(null, mbtiles);
mbtiles.emit('open', null, mbtiles);
});
return undefined;