Skip to content

Commit

Permalink
fix(packages/db): type safe & parse options (#1086)
Browse files Browse the repository at this point in the history
Co-authored-by: Isingrel <[email protected]>
  • Loading branch information
lukealford and isingrel authored Oct 22, 2023
1 parent c24374e commit c62e10f
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions packages/database/src/db/parseUri.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
// Thanks to Taso for doing things

const regex = new RegExp(
'^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([\\w\\d\\-\\u0100-\\uffff.%]*)(?::([0-9]+))?)?([^?#]+)?(?:\\?([^#]*))?$',
);
import { ConnectionOptions } from 'mysql2';
interface NPWDConnectionOptions extends ConnectionOptions {
driver: string;
}

export const parseUri = (connectionUri: string) => {
const splitMatchGroups = connectionUri.match(regex);

// Handle parsing for optional password auth
const authTgt = splitMatchGroups[2] ? splitMatchGroups[2].split(':') : [];

const removeForwardSlash = (str: string) => str.replace(/^\/+/, '');

if (connectionUri.includes('mysql://'))
return {
driver: splitMatchGroups[1],
user: authTgt[0] || undefined,
password: authTgt[1] || undefined,
host: splitMatchGroups[3],
port: parseInt(splitMatchGroups[4], 10),
database: removeForwardSlash(splitMatchGroups[5]),
params: splitMatchGroups[6],
if (connectionUri.includes('mysql://')) {
const parsedUrl = new URL(connectionUri);
const options: NPWDConnectionOptions = {
driver: parsedUrl.protocol,
host: parsedUrl.hostname,
port: parseInt(parsedUrl.port),
database: parsedUrl.pathname.slice(1),
user: parsedUrl.username,
password: parsedUrl.password,
};

parsedUrl.searchParams.forEach((value: string, key: keyof NPWDConnectionOptions) => {
try {
// Try to parse this as a JSON expression first
(options as Record<typeof key, any>)[key] = JSON.parse(value);
} catch (err) {
// Otherwise assume it is a plain string
(options as Record<typeof key, any>)[key] = value;
}
});
return options;
}

return connectionUri
.replace(/(?:host(?:name)|ip|server|data\s?source|addr(?:ess)?)=/gi, 'host=')
.replace(/(?:user\s?(?:id|name)?|uid)=/gi, 'user=')
Expand Down

0 comments on commit c62e10f

Please sign in to comment.