|
1 | 1 | import * as url from 'url';
|
2 | 2 | import * as qs from 'querystring';
|
3 | 3 | import * as dns from 'dns';
|
| 4 | +import { URL } from 'url'; |
4 | 5 | import { ReadPreference } from './read_preference';
|
5 | 6 | import { MongoParseError } from './error';
|
6 | 7 | import type { AnyOptions, Callback } from './utils';
|
7 | 8 | import type { ConnectionOptions } from './cmap/connection';
|
8 | 9 | import type { Document } from './bson';
|
9 | 10 | import type { CompressorName } from './cmap/wire_protocol/compression';
|
| 11 | +import type { MongoClientOptions, MongoOptions } from './mongo_client'; |
10 | 12 |
|
11 | 13 | /**
|
12 | 14 | * The following regular expression validates a connection string and breaks the
|
@@ -760,3 +762,49 @@ export function parseConnectionString(
|
760 | 762 |
|
761 | 763 | callback(undefined, result);
|
762 | 764 | }
|
| 765 | + |
| 766 | +// NEW PARSER WORK... |
| 767 | + |
| 768 | +const HOSTS_REGEX = new RegExp( |
| 769 | + '(?<protocol>mongodb(?:\\+srv|)):\\/\\/(?:(?<username>[^:]*)(?::(?<password>[^@]*))?@)?(?<hosts>[^\\/?]*)(?<rest>.*)' |
| 770 | +); |
| 771 | + |
| 772 | +function parseURI(uri: string): { srv: boolean; url: URL; hosts: string[] } { |
| 773 | + const match = uri.match(HOSTS_REGEX); |
| 774 | + if (!match) { |
| 775 | + throw new MongoParseError(`Invalid connection string ${uri}`); |
| 776 | + } |
| 777 | + |
| 778 | + const protocol = match.groups?.protocol; |
| 779 | + const username = match.groups?.username; |
| 780 | + const password = match.groups?.password; |
| 781 | + const hosts = match.groups?.hosts; |
| 782 | + const rest = match.groups?.rest; |
| 783 | + |
| 784 | + if (!protocol || !hosts) { |
| 785 | + throw new MongoParseError('Invalid connection string, protocol and host(s) required'); |
| 786 | + } |
| 787 | + |
| 788 | + const authString = username ? (password ? `${username}:${password}` : `${username}`) : ''; |
| 789 | + return { |
| 790 | + srv: protocol.includes('srv'), |
| 791 | + url: new URL(`${protocol.toLowerCase()}://${authString}@dummyHostname${rest}`), |
| 792 | + hosts: hosts.split(',') |
| 793 | + }; |
| 794 | +} |
| 795 | + |
| 796 | +export function parseOptions( |
| 797 | + uri: string, |
| 798 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 799 | + options: MongoClientOptions = {} |
| 800 | +): Readonly<MongoOptions> { |
| 801 | + try { |
| 802 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 803 | + const { srv, url, hosts } = parseURI(uri); |
| 804 | + const mongoOptions: MongoOptions = ({ srv, hosts } as unknown) as MongoOptions; |
| 805 | + // TODO(NODE-2699): option parse logic |
| 806 | + return Object.freeze(mongoOptions); |
| 807 | + } catch { |
| 808 | + return Object.freeze({} as MongoOptions); |
| 809 | + } |
| 810 | +} |
0 commit comments