Skip to content

Commit 143e4cc

Browse files
committed
feat: remove callbacks from mongo_client.ts
1 parent 58282af commit 143e4cc

File tree

1 file changed

+78
-128
lines changed

1 file changed

+78
-128
lines changed

src/mongo_client.ts

Lines changed: 78 additions & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import type { SrvPoller } from './sdam/srv_polling';
2626
import { Topology, TopologyEvents } from './sdam/topology';
2727
import { ClientSession, ClientSessionOptions, ServerSessionPool } from './sessions';
2828
import {
29-
Callback,
3029
ClientMetadata,
3130
HostAddress,
3231
maybeCallback,
@@ -425,79 +424,60 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
425424
*
426425
* @see docs.mongodb.org/manual/reference/connection-string/
427426
*/
428-
connect(): Promise<this>;
429-
/** @deprecated Callbacks are deprecated and will be removed in the next major version. See [mongodb-legacy](https://github.com/mongodb-js/nodejs-mongodb-legacy) for migration assistance */
430-
connect(callback: Callback<this>): void;
431-
connect(callback?: Callback<this>): Promise<this> | void {
432-
if (callback && typeof callback !== 'function') {
433-
throw new MongoInvalidArgumentError('Method `connect` only accepts a callback');
427+
async connect(): Promise<this> {
428+
if (this.topology && this.topology.isConnected()) {
429+
return this;
434430
}
435431

436-
return maybeCallback(async () => {
437-
if (this.topology && this.topology.isConnected()) {
438-
return this;
439-
}
440-
441-
const options = this[kOptions];
432+
const options = this[kOptions];
442433

443-
if (typeof options.srvHost === 'string') {
444-
const hosts = await resolveSRVRecord(options);
434+
if (typeof options.srvHost === 'string') {
435+
const hosts = await resolveSRVRecord(options);
445436

446-
for (const [index, host] of hosts.entries()) {
447-
options.hosts[index] = host;
448-
}
437+
for (const [index, host] of hosts.entries()) {
438+
options.hosts[index] = host;
449439
}
440+
}
450441

451-
const topology = new Topology(options.hosts, options);
452-
// Events can be emitted before initialization is complete so we have to
453-
// save the reference to the topology on the client ASAP if the event handlers need to access it
454-
this.topology = topology;
455-
topology.client = this;
442+
const topology = new Topology(options.hosts, options);
443+
// Events can be emitted before initialization is complete so we have to
444+
// save the reference to the topology on the client ASAP if the event handlers need to access it
445+
this.topology = topology;
446+
topology.client = this;
456447

457-
topology.once(Topology.OPEN, () => this.emit('open', this));
448+
topology.once(Topology.OPEN, () => this.emit('open', this));
458449

459-
for (const event of MONGO_CLIENT_EVENTS) {
460-
topology.on(event, (...args: any[]) => this.emit(event, ...(args as any)));
461-
}
450+
for (const event of MONGO_CLIENT_EVENTS) {
451+
topology.on(event, (...args: any[]) => this.emit(event, ...(args as any)));
452+
}
462453

463-
const topologyConnect = async () => {
464-
try {
465-
await promisify(callback => topology.connect(options, callback))();
466-
} catch (error) {
467-
topology.close({ force: true });
468-
throw error;
469-
}
470-
};
471-
472-
if (this.autoEncrypter) {
473-
const initAutoEncrypter = promisify(callback => this.autoEncrypter?.init(callback));
474-
await initAutoEncrypter();
475-
await topologyConnect();
476-
await options.encrypter.connectInternalClient();
477-
} else {
478-
await topologyConnect();
454+
const topologyConnect = async () => {
455+
try {
456+
await promisify(callback => topology.connect(options, callback))();
457+
} catch (error) {
458+
topology.close({ force: true });
459+
throw error;
479460
}
461+
};
480462

481-
return this;
482-
}, callback);
463+
if (this.autoEncrypter) {
464+
const initAutoEncrypter = promisify(callback => this.autoEncrypter?.init(callback));
465+
await initAutoEncrypter();
466+
await topologyConnect();
467+
await options.encrypter.connectInternalClient();
468+
} else {
469+
await topologyConnect();
470+
}
471+
472+
return this;
483473
}
484474

485475
/**
486-
* Close the db and its underlying connections
476+
* Close the client and its underlying connections
487477
*
488478
* @param force - Force close, emitting no events
489-
* @param callback - An optional callback, a Promise will be returned if none is provided
490479
*/
491-
close(): Promise<void>;
492-
close(force: boolean): Promise<void>;
493-
/** @deprecated Callbacks are deprecated and will be removed in the next major version. See [mongodb-legacy](https://github.com/mongodb-js/nodejs-mongodb-legacy) for migration assistance */
494-
close(callback: Callback<void>): void;
495-
/** @deprecated Callbacks are deprecated and will be removed in the next major version. See [mongodb-legacy](https://github.com/mongodb-js/nodejs-mongodb-legacy) for migration assistance */
496-
close(force: boolean, callback: Callback<void>): void;
497-
close(
498-
forceOrCallback?: boolean | Callback<void>,
499-
callback?: Callback<void>
500-
): Promise<void> | void {
480+
async close(force = false): Promise<void> {
501481
// There's no way to set hasBeenClosed back to false
502482
Object.defineProperty(this.s, 'hasBeenClosed', {
503483
value: true,
@@ -506,58 +486,50 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
506486
writable: false
507487
});
508488

509-
if (typeof forceOrCallback === 'function') {
510-
callback = forceOrCallback;
511-
}
512-
513-
const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false;
489+
const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession());
490+
this.s.activeSessions.clear();
514491

515-
return maybeCallback(async () => {
516-
const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession());
517-
this.s.activeSessions.clear();
492+
await Promise.all(activeSessionEnds);
518493

519-
await Promise.all(activeSessionEnds);
494+
if (this.topology == null) {
495+
return;
496+
}
520497

521-
if (this.topology == null) {
522-
return;
498+
// If we would attempt to select a server and get nothing back we short circuit
499+
// to avoid the server selection timeout.
500+
const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred);
501+
const topologyDescription = this.topology.description;
502+
const serverDescriptions = Array.from(topologyDescription.servers.values());
503+
const servers = selector(topologyDescription, serverDescriptions);
504+
if (servers.length !== 0) {
505+
const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id);
506+
if (endSessions.length !== 0) {
507+
await this.db('admin')
508+
.command(
509+
{ endSessions },
510+
{ readPreference: ReadPreference.primaryPreferred, noResponse: true }
511+
)
512+
.catch(() => null); // outcome does not matter
523513
}
514+
}
524515

525-
// If we would attempt to select a server and get nothing back we short circuit
526-
// to avoid the server selection timeout.
527-
const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred);
528-
const topologyDescription = this.topology.description;
529-
const serverDescriptions = Array.from(topologyDescription.servers.values());
530-
const servers = selector(topologyDescription, serverDescriptions);
531-
if (servers.length !== 0) {
532-
const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id);
533-
if (endSessions.length !== 0) {
534-
await this.db('admin')
535-
.command(
536-
{ endSessions },
537-
{ readPreference: ReadPreference.primaryPreferred, noResponse: true }
538-
)
539-
.catch(() => null); // outcome does not matter
516+
// clear out references to old topology
517+
const topology = this.topology;
518+
this.topology = undefined;
519+
520+
await new Promise<void>((resolve, reject) => {
521+
topology.close({ force }, error => {
522+
if (error) return reject(error);
523+
const { encrypter } = this[kOptions];
524+
if (encrypter) {
525+
return encrypter.close(this, force, error => {
526+
if (error) return reject(error);
527+
resolve();
528+
});
540529
}
541-
}
542-
543-
// clear out references to old topology
544-
const topology = this.topology;
545-
this.topology = undefined;
546-
547-
await new Promise<void>((resolve, reject) => {
548-
topology.close({ force }, error => {
549-
if (error) return reject(error);
550-
const { encrypter } = this[kOptions];
551-
if (encrypter) {
552-
return encrypter.close(this, force, error => {
553-
if (error) return reject(error);
554-
resolve();
555-
});
556-
}
557-
resolve();
558-
});
530+
resolve();
559531
});
560-
}, callback);
532+
});
561533
}
562534

563535
/**
@@ -592,34 +564,12 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
592564
*
593565
* @see https://docs.mongodb.org/manual/reference/connection-string/
594566
*/
595-
static connect(url: string): Promise<MongoClient>;
596-
static connect(url: string, options: MongoClientOptions): Promise<MongoClient>;
597-
/** @deprecated Callbacks are deprecated and will be removed in the next major version. See [mongodb-legacy](https://github.com/mongodb-js/nodejs-mongodb-legacy) for migration assistance */
598-
static connect(url: string, callback: Callback<MongoClient>): void;
599-
/** @deprecated Callbacks are deprecated and will be removed in the next major version. See [mongodb-legacy](https://github.com/mongodb-js/nodejs-mongodb-legacy) for migration assistance */
600-
static connect(url: string, options: MongoClientOptions, callback: Callback<MongoClient>): void;
601-
static connect(
602-
url: string,
603-
options?: MongoClientOptions | Callback<MongoClient>,
604-
callback?: Callback<MongoClient>
605-
): Promise<MongoClient> | void {
606-
callback =
607-
typeof callback === 'function'
608-
? callback
609-
: typeof options === 'function'
610-
? options
611-
: undefined;
612-
613-
return maybeCallback(async () => {
614-
options = typeof options !== 'function' ? options : undefined;
615-
const client = new this(url, options);
616-
return client.connect();
617-
}, callback);
567+
static async connect(url: string, options?: MongoClientOptions): Promise<MongoClient> {
568+
const client = new this(url, options);
569+
return client.connect();
618570
}
619571

620572
/** Starts a new session on the server */
621-
startSession(): ClientSession;
622-
startSession(options: ClientSessionOptions): ClientSession;
623573
startSession(options?: ClientSessionOptions): ClientSession {
624574
const session = new ClientSession(
625575
this,
@@ -646,7 +596,7 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
646596
withSession(callback: WithSessionCallback): Promise<void>;
647597
withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise<void>;
648598
withSession(
649-
optionsOrOperation?: ClientSessionOptions | WithSessionCallback,
599+
optionsOrOperation: ClientSessionOptions | WithSessionCallback,
650600
callback?: WithSessionCallback
651601
): Promise<void> {
652602
const options = {

0 commit comments

Comments
 (0)