Compare commits

...

2 Commits

2 changed files with 47 additions and 40 deletions

36
src/adapter_wrapper.mjs Normal file
View File

@ -0,0 +1,36 @@
export 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;
}

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}`);
}