Unlink adapters. Add adapter registry

This commit is contained in:
Ben Ashton 2021-03-01 22:19:38 -08:00
parent 1886fe4f2c
commit 38df7f1053

View File

@ -2,9 +2,8 @@ import { Database } from "./database.mjs";
import { PawSQLiteError } from "./pawsqlite_error.mjs"; import { PawSQLiteError } from "./pawsqlite_error.mjs";
import { enableDebug } from "./log.mjs"; import { enableDebug } from "./log.mjs";
// Adapters
import { PSQLAdapter } from "./adapters/cordova_pawsqlite/psql_adapter.mjs"; const adapters = [];
import { WebSQLAdapter } from "./adapters/websql/websql_adapter.mjs";
export default { export default {
@ -20,22 +19,58 @@ export default {
return adapter.delete(dbName); return adapter.delete(dbName);
}, },
registerAdapter: function(adapter) {
adapters.push(wrapAdapter(adapter));
},
debug: enableDebug, debug: enableDebug,
Error: PawSQLiteError Error: PawSQLiteError
}; };
function getAdapter(adapterName) { function wrapAdapter() {
if (!adapterName) { const wrapped = {};
adapterName = "pawsqlite";
} else { ["name", "open", "close", "delete", "sql"].forEach((prop) => {
adapterName = adapterName.toLowerCase(); if (!(prop in adapter)) {
throw new PawSQLiteError(`Invalid adapter: missing property: ${ prop }`);
} }
if (adapterName === "pawsqlite") {
return PSQLAdapter; if (
} else if (adapterName === "websql") { prop === "name" && !(
return WebSQLAdapter; 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 { } 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}`); throw new PawSQLiteError(`Unknown Adapter: ${adapterName}`);
} }
return adapter;
} }