You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.7 KiB
76 lines
1.7 KiB
import { Database } from "./database.mjs"; |
|
import { PawSQLiteError } from "./pawsqlite_error.mjs"; |
|
import { enableDebug } from "./log.mjs"; |
|
|
|
|
|
const adapters = []; |
|
|
|
|
|
export default { |
|
open: async function(dbName, options = {}) { |
|
const adapter = getAdapter(options.adapter); |
|
|
|
let db = new Database(dbName, adapter); |
|
await db.open(); |
|
return db; |
|
}, |
|
delete: function(dbName, options = {}) { |
|
const adapter = getAdapter(options.adapter); |
|
|
|
return adapter.delete(dbName); |
|
}, |
|
registerAdapter: function(adapter) { |
|
adapters.push(wrapAdapter(adapter)); |
|
}, |
|
debug: enableDebug, |
|
Error: PawSQLiteError |
|
}; |
|
|
|
|
|
function wrapAdapter(adapter) { |
|
const wrapped = {}; |
|
|
|
["name", "open", "close", "delete", "sql"].forEach((prop) => { |
|
if (!(prop in adapter)) { |
|
throw new PawSQLiteError(`Invalid adapter: missing property: ${ prop }`); |
|
} |
|
|
|
if ( |
|
prop === "name" && !( |
|
typeof adapter[prop] === "string" || |
|
adapter[prop] instanceof String |
|
) || |
|
prop !== "name" && ( |
|
typeof adapter[prop] !== "function" |
|
) |
|
) { |
|
throw new PawSQLiteError("Invalid adapter: invalid type for property: " + |
|
prop); |
|
} |
|
|
|
if (typeof adapter[prop] === "function") { |
|
wrapped[prop] = async (...args) => { |
|
try { |
|
return await adapter[prop](...args); |
|
} catch (err) { |
|
throw PawSQLiteError.from(err); |
|
} |
|
}; |
|
} else { |
|
wrapped[prop] = adapter[prop]; |
|
} |
|
}); |
|
|
|
return wrapped; |
|
} |
|
|
|
|
|
function getAdapter(adapterName) { |
|
const adapter = adapters.find((a) => a.name === adapterName); |
|
|
|
if (!adapter) { |
|
throw new PawSQLiteError(`Unknown Adapter: ${adapterName}`); |
|
} |
|
|
|
return adapter; |
|
} |