Skip to content

Commit d52c00e

Browse files
authored
refactor!: remove enums in favor of const objects (#2741)
Changes remaining enums to const objects and exports all user relevant "enums" from index.ts. Enums are frozen to ensure they remain static. Added a lint rule to prevent further enums. Corrected mistake in sourcemap emit settings. NODE-2973
1 parent 85695c4 commit d52c00e

16 files changed

+183
-145
lines changed

.eslintrc.json

+9-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,15 @@
3232
"strict": ["error", "global"],
3333
"promise/no-native": "error",
3434

35-
"@typescript-eslint/no-explicit-any": "off"
35+
"@typescript-eslint/no-explicit-any": "off",
36+
37+
"no-restricted-syntax": [
38+
"error",
39+
{
40+
"selector": "TSEnumDeclaration",
41+
"message": "Don't declare enums"
42+
}
43+
]
3644
},
3745
"overrides": [{
3846
"files": ["*.d.ts"],

src/cmap/message_stream.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import {
77
decompress,
88
uncompressibleCommands,
99
Compressor,
10-
CompressorName
10+
CompressorName,
11+
CompressorId
1112
} from './wire_protocol/compression';
1213
import type { Document, BSONSerializeOptions } from '../bson';
1314
import { BufferPool, Callback } from '../utils';
@@ -177,7 +178,7 @@ function processIncomingData(stream: MessageStream, callback: Callback<Buffer>)
177178
messageHeader.fromCompressed = true;
178179
messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);
179180
messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);
180-
const compressorID = message[MESSAGE_HEADER_SIZE + 8];
181+
const compressorID: CompressorId = message[MESSAGE_HEADER_SIZE + 8] as CompressorId;
181182
const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
182183

183184
// recalculate based on wrapped opcode

src/cmap/wire_protocol/compression.ts

+8-6
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@ import type { OperationDescription } from '../message_stream';
55
import { Snappy } from '../../deps';
66

77
/** @public */
8-
export enum Compressor {
9-
none = 0,
10-
snappy = 1,
11-
zlib = 2
12-
}
8+
export const Compressor = Object.freeze({
9+
none: 0,
10+
snappy: 1,
11+
zlib: 2
12+
} as const);
13+
14+
export type CompressorId = typeof Compressor[keyof typeof Compressor];
1315

1416
/** @public */
1517
export type CompressorName = keyof typeof Compressor;
@@ -59,7 +61,7 @@ export function compress(
5961

6062
// Decompress a message using the given compressor
6163
export function decompress(
62-
compressorID: Compressor,
64+
compressorID: CompressorId,
6365
compressedData: Buffer,
6466
callback: Callback<Buffer>
6567
): void {

src/connection_string.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
} from './mongo_client';
2626
import { MongoCredentials } from './cmap/auth/mongo_credentials';
2727
import type { TagSet } from './sdam/server_description';
28-
import { Logger, LoggerLevel } from './logger';
28+
import { Logger, LoggerLevelId } from './logger';
2929
import { PromiseProvider } from './promise_provider';
3030
import { createAutoEncrypter } from './operations/connect';
3131

@@ -713,7 +713,7 @@ export const OPTIONS = {
713713
loggerLevel: {
714714
target: 'logger',
715715
transform({ values: [value] }) {
716-
return new Logger('MongoClient', { loggerLevel: value as LoggerLevel });
716+
return new Logger('MongoClient', { loggerLevel: value as LoggerLevelId });
717717
}
718718
},
719719
maxIdleTimeMS: {

src/db.ts

+12-12
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ import { RemoveUserOperation, RemoveUserOptions } from './operations/remove_user
4444
import { RenameOperation, RenameOptions } from './operations/rename';
4545
import {
4646
SetProfilingLevelOperation,
47-
ProfilingLevel,
48-
SetProfilingLevelOptions
47+
SetProfilingLevelOptions,
48+
ProfilingLevelId
4949
} from './operations/set_profiling_level';
5050
import { executeOperation } from './operations/execute_operation';
5151
import { EvalOperation, EvalOptions } from './operations/eval';
@@ -639,22 +639,22 @@ export class Db {
639639
* @param options - Optional settings for the command
640640
* @param callback - An optional callback, a Promise will be returned if none is provided
641641
*/
642-
setProfilingLevel(level: ProfilingLevel): Promise<ProfilingLevel>;
643-
setProfilingLevel(level: ProfilingLevel, callback: Callback<ProfilingLevel>): void;
642+
setProfilingLevel(level: ProfilingLevelId): Promise<ProfilingLevelId>;
643+
setProfilingLevel(level: ProfilingLevelId, callback: Callback<ProfilingLevelId>): void;
644644
setProfilingLevel(
645-
level: ProfilingLevel,
645+
level: ProfilingLevelId,
646646
options: SetProfilingLevelOptions
647-
): Promise<ProfilingLevel>;
647+
): Promise<ProfilingLevelId>;
648648
setProfilingLevel(
649-
level: ProfilingLevel,
649+
level: ProfilingLevelId,
650650
options: SetProfilingLevelOptions,
651-
callback: Callback<ProfilingLevel>
651+
callback: Callback<ProfilingLevelId>
652652
): void;
653653
setProfilingLevel(
654-
level: ProfilingLevel,
655-
options?: SetProfilingLevelOptions | Callback<ProfilingLevel>,
656-
callback?: Callback<ProfilingLevel>
657-
): Promise<ProfilingLevel> | void {
654+
level: ProfilingLevelId,
655+
options?: SetProfilingLevelOptions | Callback<ProfilingLevelId>,
656+
callback?: Callback<ProfilingLevelId>
657+
): Promise<ProfilingLevelId> | void {
658658
if (typeof options === 'function') (callback = options), (options = {});
659659

660660
return executeOperation(

src/deps.ts

+11-8
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,16 @@ try {
6868
} catch {} // eslint-disable-line
6969

7070
/** @public */
71-
export const enum AutoEncryptionLoggerLevels {
72-
FatalError = 0,
73-
Error = 1,
74-
Warning = 2,
75-
Info = 3,
76-
Trace = 4
77-
}
71+
export const AutoEncryptionLoggerLevel = Object.freeze({
72+
FatalError: 0,
73+
Error: 1,
74+
Warning: 2,
75+
Info: 3,
76+
Trace: 4
77+
} as const);
78+
79+
/** @public */
80+
export type AutoEncryptionLoggerLevelId = typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel];
7881

7982
/** @public */
8083
export interface AutoEncryptionOptions {
@@ -146,7 +149,7 @@ export interface AutoEncryptionOptions {
146149
bypassAutoEncryption?: boolean;
147150
options?: {
148151
/** An optional hook to catch logging messages from the underlying encryption engine */
149-
logger?: (level: AutoEncryptionLoggerLevels, message: string) => void;
152+
logger?: (level: AutoEncryptionLoggerLevelId, message: string) => void;
150153
};
151154
extraOptions?: {
152155
/**

src/index.ts

+23-19
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,20 @@ export {
7373
GridFSBucket
7474
};
7575

76+
// enums
77+
export { ProfilingLevel } from './operations/set_profiling_level';
78+
export { ServerType, TopologyType } from './sdam/common';
79+
export { LoggerLevel } from './logger';
80+
export { AutoEncryptionLoggerLevel } from './deps';
81+
export { BatchType } from './bulk/common';
82+
export { AuthMechanism } from './cmap/auth/defaultAuthProviders';
83+
export { CURSOR_FLAGS } from './cursor/abstract_cursor';
84+
export { Compressor } from './cmap/wire_protocol/compression';
85+
export { ExplainVerbosity } from './explain';
86+
export { ReadConcernLevel } from './read_concern';
87+
export { ReadPreferenceMode } from './read_preference';
88+
89+
// type only exports below, these are removed from emitted JS
7690
export type { AdminPrivate } from './admin';
7791
export type { Instrumentation } from './apm';
7892
export type { Document, BSONSerializeOptions } from './bson';
@@ -99,7 +113,7 @@ export type {
99113
OperationTime,
100114
ResumeOptions
101115
} from './change_stream';
102-
export type { AuthMechanism, AuthMechanismId } from './cmap/auth/defaultAuthProviders';
116+
export type { AuthMechanismId } from './cmap/auth/defaultAuthProviders';
103117
export type { MongoCredentials, MongoCredentialsOptions } from './cmap/auth/mongo_credentials';
104118
export type {
105119
WriteProtocolMessageType,
@@ -132,20 +146,19 @@ export type {
132146
MessageStreamOptions
133147
} from './cmap/message_stream';
134148
export type { StreamDescription, StreamDescriptionOptions } from './cmap/stream_description';
135-
export type { CompressorName, Compressor } from './cmap/wire_protocol/compression';
149+
export type { CompressorName } from './cmap/wire_protocol/compression';
136150
export type { CollectionPrivate, CollectionOptions } from './collection';
137151
export type { AggregationCursorOptions } from './cursor/aggregation_cursor';
138152
export type {
139153
CursorCloseOptions,
140154
CursorStreamOptions,
141155
AbstractCursorOptions,
142-
CURSOR_FLAGS,
143156
CursorFlag
144157
} from './cursor/abstract_cursor';
145158
export type { DbPrivate, DbOptions } from './db';
146-
export type { AutoEncryptionOptions, AutoEncryptionLoggerLevels, AutoEncrypter } from './deps';
159+
export type { AutoEncryptionOptions, AutoEncryptionLoggerLevelId, AutoEncrypter } from './deps';
147160
export type { AnyError, ErrorDescription } from './error';
148-
export type { Explain, ExplainOptions, ExplainVerbosity, ExplainVerbosityLike } from './explain';
161+
export type { Explain, ExplainOptions, ExplainVerbosityLike } from './explain';
149162
export type {
150163
GridFSBucketReadStream,
151164
GridFSBucketReadStreamOptions,
@@ -159,14 +172,12 @@ export type {
159172
TFileId,
160173
GridFSBucketWriteStream
161174
} from './gridfs-stream/upload';
162-
export type { LoggerOptions, LoggerFunction, LoggerLevel } from './logger';
175+
export type { LoggerOptions, LoggerFunction, LoggerLevelId } from './logger';
163176
export type {
164177
MongoClientPrivate,
165178
MongoClientOptions,
166179
WithSessionCallback,
167180
PkFactory,
168-
LogLevel,
169-
LogLevelId,
170181
Auth,
171182
DriverInfo,
172183
MongoOptions,
@@ -221,7 +232,7 @@ export type { ProfilingLevelOptions } from './operations/profiling_level';
221232
export type { RemoveUserOptions } from './operations/remove_user';
222233
export type { RenameOptions } from './operations/rename';
223234
export type { RunCommandOptions } from './operations/run_command';
224-
export type { ProfilingLevel, SetProfilingLevelOptions } from './operations/set_profiling_level';
235+
export type { ProfilingLevelId, SetProfilingLevelOptions } from './operations/set_profiling_level';
225236
export type { CollStatsOptions, DbStatsOptions } from './operations/stats';
226237
export type {
227238
UpdateResult,
@@ -230,22 +241,16 @@ export type {
230241
UpdateStatement
231242
} from './operations/update';
232243
export type { ValidateCollectionOptions } from './operations/validate_collection';
233-
export type {
234-
ReadConcern,
235-
ReadConcernLike,
236-
ReadConcernLevel,
237-
ReadConcernLevelId
238-
} from './read_concern';
244+
export type { ReadConcern, ReadConcernLike, ReadConcernLevelId } from './read_concern';
239245
export type {
240246
ReadPreferenceLike,
241247
ReadPreferenceModeId,
242-
ReadPreferenceMode,
243248
ReadPreferenceOptions,
244249
ReadPreferenceLikeOptions,
245250
ReadPreferenceFromOptions,
246251
HedgeOptions
247252
} from './read_preference';
248-
export type { ClusterTime, ServerType, TimerQueue, TopologyType } from './sdam/common';
253+
export type { ClusterTime, ServerTypeId, TimerQueue, TopologyTypeId } from './sdam/common';
249254
export type { TopologyDescriptionChangedEvent } from './sdam/events';
250255
export type {
251256
Monitor,
@@ -282,7 +287,7 @@ export type {
282287
ServerSessionId,
283288
WithTransactionCallback
284289
} from './sessions';
285-
export type { TransactionOptions, Transaction, TxnState } from './transactions';
290+
export type { TransactionOptions, Transaction, TxnState, TxnStateId } from './transactions';
286291
export type {
287292
Callback,
288293
ClientMetadata,
@@ -298,7 +303,6 @@ export type { InternalAbstractCursorOptions } from './cursor/abstract_cursor';
298303
export type {
299304
BulkOperationBase,
300305
BulkOperationPrivate,
301-
BatchType,
302306
BatchTypeId,
303307
FindOperators,
304308
Batch

src/logger.ts

+21-14
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { format as f } from 'util';
1+
import { format } from 'util';
22
import { MongoError } from './error';
33

44
// Filters for classes
55
const classFilters: any = {};
66
let filteredClasses: any = {};
7-
let level: LoggerLevel;
7+
let level: LoggerLevelId;
88

99
// Save the process id
1010
const pid = process.pid;
@@ -13,20 +13,27 @@ const pid = process.pid;
1313
let currentLogger: LoggerFunction = console.warn;
1414

1515
/** @public */
16-
export enum LoggerLevel {
17-
ERROR = 'error',
18-
WARN = 'warn',
19-
INFO = 'info',
20-
DEBUG = 'debug'
21-
}
16+
export const LoggerLevel = Object.freeze({
17+
ERROR: 'error',
18+
WARN: 'warn',
19+
INFO: 'info',
20+
DEBUG: 'debug',
21+
error: 'error',
22+
warn: 'warn',
23+
info: 'info',
24+
debug: 'debug'
25+
} as const);
26+
27+
/** @public */
28+
export type LoggerLevelId = typeof LoggerLevel[keyof typeof LoggerLevel];
2229

2330
/** @public */
2431
export type LoggerFunction = (message?: any, ...optionalParams: any[]) => void;
2532

2633
/** @public */
2734
export interface LoggerOptions {
2835
logger?: LoggerFunction;
29-
loggerLevel?: LoggerLevel;
36+
loggerLevel?: LoggerLevelId;
3037
}
3138

3239
/**
@@ -76,7 +83,7 @@ export class Logger {
7683
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
7784
) {
7885
const dateTime = new Date().getTime();
79-
const msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message);
86+
const msg = format('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message);
8087
const state = {
8188
type: LoggerLevel.DEBUG,
8289
message,
@@ -103,7 +110,7 @@ export class Logger {
103110
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
104111
) {
105112
const dateTime = new Date().getTime();
106-
const msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message);
113+
const msg = format('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message);
107114
const state = {
108115
type: LoggerLevel.WARN,
109116
message,
@@ -130,7 +137,7 @@ export class Logger {
130137
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
131138
) {
132139
const dateTime = new Date().getTime();
133-
const msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message);
140+
const msg = format('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message);
134141
const state = {
135142
type: LoggerLevel.INFO,
136143
message,
@@ -157,7 +164,7 @@ export class Logger {
157164
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
158165
) {
159166
const dateTime = new Date().getTime();
160-
const msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message);
167+
const msg = format('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message);
161168
const state = {
162169
type: LoggerLevel.ERROR,
163170
message,
@@ -238,7 +245,7 @@ export class Logger {
238245
*
239246
* @param newLevel - Set current log level (debug, warn, info, error)
240247
*/
241-
static setLevel(newLevel: LoggerLevel): void {
248+
static setLevel(newLevel: LoggerLevelId): void {
242249
if (
243250
newLevel !== LoggerLevel.INFO &&
244251
newLevel !== LoggerLevel.ERROR &&

0 commit comments

Comments
 (0)