Skip to content

Commit

Permalink
fix implicit type conversion issue in options parser
Browse files Browse the repository at this point in the history
  • Loading branch information
baileympearson committed Feb 9, 2022
1 parent 991c0eb commit a9195e3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/connection_string.ts
Expand Up @@ -204,13 +204,24 @@ function getUint(name: string, value: unknown): number {
return parsedValue;
}


function toArray<T>(value: T): T[];
function toArray<T>(value: T[]): T[];
function toArray<T>(value: T | T[]): T[] {
return Array.isArray(value) ? value : [value];
}

function parseType(value: string): number | boolean | string {
try {
return getBoolean('', value);
} catch {
try {
return getInt('', value);
} catch {
return value;
}
}
}

function toRecord(value: string): Record<string, any> {
const record = Object.create(null);
const keyValuePairs = value.split(',');
Expand All @@ -219,18 +230,7 @@ function toRecord(value: string): Record<string, any> {
if (value == null) {
throw new MongoParseError('Cannot have undefined values in key value pairs');
}
try {
// try to get a boolean
record[key] = getBoolean('', value);
} catch {
try {
// try to get a number
record[key] = getInt('', value);
} catch {
// keep value as a string
record[key] = value;
}
}
record[key] = value;
}
return record;
}
Expand Down Expand Up @@ -632,7 +632,9 @@ export const OPTIONS = {
target: 'credentials',
transform({ options, values: [value] }): MongoCredentials {
if (typeof value === 'string') {
value = toRecord(value);
value = Object.fromEntries(
Object.entries(toRecord(value)).map(([key, value]) => [key, parseType(value)])
);
}
if (!isRecord(value)) {
throw new MongoParseError('AuthMechanismProperties must be an object');
Expand Down
6 changes: 6 additions & 0 deletions test/tools/uri_spec_runner.ts
Expand Up @@ -221,6 +221,12 @@ export function executeUriValidationTest(
.to.have.nested.property(expectedProp)
.deep.equal(optionValue);
break;
case 'maxStalenessSeconds':
expectedProp = 'readPreference.maxStalenessSeconds';
expect(options, `${errorMessage} ${optionKey} -> ${expectedProp}`)
.to.have.nested.property(expectedProp)
.deep.equal(optionValue);
break;

//** WRITE CONCERN OPTIONS **/
case 'w':
Expand Down

0 comments on commit a9195e3

Please sign in to comment.