Skip to content

Commit

Permalink
Move around code
Browse files Browse the repository at this point in the history
  • Loading branch information
nbbeeken committed Nov 18, 2020
1 parent e42cdb3 commit ba4fe1f
Show file tree
Hide file tree
Showing 3 changed files with 141 additions and 145 deletions.
48 changes: 48 additions & 0 deletions src/connection_string.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import * as url from 'url';
import * as qs from 'querystring';
import * as dns from 'dns';
import { URL } from 'url';
import { ReadPreference } from './read_preference';
import { MongoParseError } from './error';
import type { AnyOptions, Callback } from './utils';
import type { ConnectionOptions } from './cmap/connection';
import type { Document } from './bson';
import type { CompressorName } from './cmap/wire_protocol/compression';
import type { MongoClientOptions, MongoOptions } from './mongo_client';

/**
* The following regular expression validates a connection string and breaks the
Expand Down Expand Up @@ -760,3 +762,49 @@ export function parseConnectionString(

callback(undefined, result);
}

// NEW PARSER WORK...

const HOSTS_REGEX = new RegExp(
'(?<protocol>mongodb(?:\\+srv|)):\\/\\/(?:(?<username>[^:]*)(?::(?<password>[^@]*))?@)?(?<hosts>[^\\/?]*)(?<rest>.*)'
);

function parseURI(uri: string): { srv: boolean; url: URL; hosts: string[] } {
const match = uri.match(HOSTS_REGEX);
if (!match) {
throw new MongoParseError(`Invalid connection string ${uri}`);
}

const protocol = match.groups?.protocol;
const username = match.groups?.username;
const password = match.groups?.password;
const hosts = match.groups?.hosts;
const rest = match.groups?.rest;

if (!protocol || !hosts) {
throw new MongoParseError('Invalid connection string, protocol and host(s) required');
}

const authString = username ? (password ? `${username}:${password}` : `${username}`) : '';
return {
srv: protocol.includes('srv'),
url: new URL(`${protocol.toLowerCase()}://${authString}@dummyHostname${rest}`),
hosts: hosts.split(',')
};
}

export function parseOptions(
uri: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
options: MongoClientOptions = {}
): Readonly<MongoOptions> {
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { srv, url, hosts } = parseURI(uri);
const mongoOptions: MongoOptions = ({ srv, hosts } as unknown) as MongoOptions;
// TODO(NODE-2699): option parse logic
return Object.freeze(mongoOptions);
} catch {
return Object.freeze({} as MongoOptions);
}
}
94 changes: 93 additions & 1 deletion src/mongo_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ import type { Topology } from './sdam/topology';
import type { ClientSession, ClientSessionOptions } from './sessions';
import type { OperationParent } from './operations/command';
import type { TagSet } from './sdam/server_description';
import { MongoOptions, parseOptions } from './mongo_client_options';
import type { ConnectionOptions as TLSConnectionOptions } from 'tls';
import type { TcpSocketConnectOpts as ConnectionOptions } from 'net';
import type { MongoCredentials } from './cmap/auth/mongo_credentials';
import { parseOptions } from './connection_string';

/** @public */
export enum LogLevel {
Expand Down Expand Up @@ -569,3 +572,92 @@ export class MongoClient extends EventEmitter implements OperationParent {
if (typeof callback === 'function') callback(undefined, true);
}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient');
}

/**
* Mongo Client Options
* @internal
*/
export interface MongoOptions
extends Required<BSONSerializeOptions>,
Omit<ConnectionOptions, 'port'>,
Omit<TLSConnectionOptions, 'port'>,
Required<
Pick<
MongoClientOptions,
| 'autoEncryption'
| 'compression'
| 'compressors'
| 'connectTimeoutMS'
| 'dbName'
| 'directConnection'
| 'domainsEnabled'
| 'driverInfo'
| 'forceServerObjectId'
| 'gssapiServiceName'
| 'ha'
| 'haInterval'
| 'heartbeatFrequencyMS'
| 'keepAlive'
| 'keepAliveInitialDelay'
| 'localThresholdMS'
| 'logger'
| 'maxIdleTimeMS'
| 'maxPoolSize'
| 'minPoolSize'
| 'monitorCommands'
| 'noDelay'
| 'numberOfRetries'
| 'pkFactory'
| 'promiseLibrary'
| 'raw'
| 'reconnectInterval'
| 'reconnectTries'
| 'replicaSet'
| 'retryReads'
| 'retryWrites'
| 'serverSelectionTimeoutMS'
| 'serverSelectionTryOnce'
| 'socketTimeoutMS'
| 'tlsAllowInvalidCertificates'
| 'tlsAllowInvalidHostnames'
| 'tlsInsecure'
| 'waitQueueMultiple'
| 'waitQueueTimeoutMS'
| 'zlibCompressionLevel'
>
> {
hosts: { host: string; port: number }[];
srv: boolean;
credentials: MongoCredentials;
readPreference: ReadPreference;
readConcern: ReadConcern;
writeConcern: WriteConcern;

/**
* # NOTE ABOUT TLS Options
*
* If set TLS enabled, equivalent to setting the ssl option.
*
* ### Additional options:
*
* | nodejs option | MongoDB equivalent | type |
* |:---------------------|--------------------------------------------------------- |:---------------------------------------|
* | `ca` | `sslCA`, `tlsCAFile` | `string \| Buffer \| Buffer[]` |
* | `crl` | `sslCRL` | `string \| Buffer \| Buffer[]` |
* | `cert` | `sslCert`, `tlsCertificateFile`, `tlsCertificateKeyFile` | `string \| Buffer \| Buffer[]` |
* | `key` | `sslKey`, `tlsCertificateKeyFile` | `string \| Buffer \| KeyObject[]` |
* | `passphrase` | `sslPass`, `tlsCertificateKeyFilePassword` | `string` |
* | `rejectUnauthorized` | `sslValidate` | `boolean` |
*
*/
tls: boolean;

/**
* Turn these options into a reusable options dictionary
*/
toJSON(): Record<string, any>;
/**
* Turn these options into a reusable connection URI
*/
toURI(): string;
}
144 changes: 0 additions & 144 deletions src/mongo_client_options.ts

This file was deleted.

0 comments on commit ba4fe1f

Please sign in to comment.