Added condition to prevent adapters from being registered multiple times

This commit is contained in:
Ben Ashton 2021-03-02 14:25:40 -08:00
parent c15fa92174
commit cd8db56678

View File

@ -1,4 +1,5 @@
import { Database } from "./database.mjs";
import { wrapAdapter } from "./adapter_wrapper.mjs";
import { PawSQLiteError } from "./pawsqlite_error.mjs";
import { enableDebug } from "./log.mjs";
@ -20,55 +21,25 @@ export default {
return adapter.delete(dbName);
},
registerAdapter: function(adapter) {
adapters.push(wrapAdapter(adapter));
const wrapped = wrapAdapter(adapter);
if (getAdapter(wrapped.name)) {
throw new PawSQLiteError(`An adapter with the name: ${ wrapped.name } ` +
`Already exists`);
}
adapters.push(wrapped);
},
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) {
function getAdapter(adapterName, silent=false) {
const adapter = adapters.find((a) => a.name === adapterName);
if (!adapter) {
if (!(silent || adapter)) {
throw new PawSQLiteError(`Unknown Adapter: ${adapterName}`);
}