Skip to content

Commit

Permalink
refactor!: remove enums in favor of const objects (#2741)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nbbeeken authored Feb 19, 2021
1 parent 85695c4 commit d52c00e
Show file tree
Hide file tree
Showing 16 changed files with 183 additions and 145 deletions.
10 changes: 9 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,15 @@
"strict": ["error", "global"],
"promise/no-native": "error",

"@typescript-eslint/no-explicit-any": "off"
"@typescript-eslint/no-explicit-any": "off",

"no-restricted-syntax": [
"error",
{
"selector": "TSEnumDeclaration",
"message": "Don't declare enums"
}
]
},
"overrides": [{
"files": ["*.d.ts"],
Expand Down
5 changes: 3 additions & 2 deletions src/cmap/message_stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
decompress,
uncompressibleCommands,
Compressor,
CompressorName
CompressorName,
CompressorId
} from './wire_protocol/compression';
import type { Document, BSONSerializeOptions } from '../bson';
import { BufferPool, Callback } from '../utils';
Expand Down Expand Up @@ -177,7 +178,7 @@ function processIncomingData(stream: MessageStream, callback: Callback<Buffer>)
messageHeader.fromCompressed = true;
messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);
messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);
const compressorID = message[MESSAGE_HEADER_SIZE + 8];
const compressorID: CompressorId = message[MESSAGE_HEADER_SIZE + 8] as CompressorId;
const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);

// recalculate based on wrapped opcode
Expand Down
14 changes: 8 additions & 6 deletions src/cmap/wire_protocol/compression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import type { OperationDescription } from '../message_stream';
import { Snappy } from '../../deps';

/** @public */
export enum Compressor {
none = 0,
snappy = 1,
zlib = 2
}
export const Compressor = Object.freeze({
none: 0,
snappy: 1,
zlib: 2
} as const);

export type CompressorId = typeof Compressor[keyof typeof Compressor];

/** @public */
export type CompressorName = keyof typeof Compressor;
Expand Down Expand Up @@ -59,7 +61,7 @@ export function compress(

// Decompress a message using the given compressor
export function decompress(
compressorID: Compressor,
compressorID: CompressorId,
compressedData: Buffer,
callback: Callback<Buffer>
): void {
Expand Down
4 changes: 2 additions & 2 deletions src/connection_string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
} from './mongo_client';
import { MongoCredentials } from './cmap/auth/mongo_credentials';
import type { TagSet } from './sdam/server_description';
import { Logger, LoggerLevel } from './logger';
import { Logger, LoggerLevelId } from './logger';
import { PromiseProvider } from './promise_provider';
import { createAutoEncrypter } from './operations/connect';

Expand Down Expand Up @@ -713,7 +713,7 @@ export const OPTIONS = {
loggerLevel: {
target: 'logger',
transform({ values: [value] }) {
return new Logger('MongoClient', { loggerLevel: value as LoggerLevel });
return new Logger('MongoClient', { loggerLevel: value as LoggerLevelId });
}
},
maxIdleTimeMS: {
Expand Down
24 changes: 12 additions & 12 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ import { RemoveUserOperation, RemoveUserOptions } from './operations/remove_user
import { RenameOperation, RenameOptions } from './operations/rename';
import {
SetProfilingLevelOperation,
ProfilingLevel,
SetProfilingLevelOptions
SetProfilingLevelOptions,
ProfilingLevelId
} from './operations/set_profiling_level';
import { executeOperation } from './operations/execute_operation';
import { EvalOperation, EvalOptions } from './operations/eval';
Expand Down Expand Up @@ -639,22 +639,22 @@ export class Db {
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
setProfilingLevel(level: ProfilingLevel): Promise<ProfilingLevel>;
setProfilingLevel(level: ProfilingLevel, callback: Callback<ProfilingLevel>): void;
setProfilingLevel(level: ProfilingLevelId): Promise<ProfilingLevelId>;
setProfilingLevel(level: ProfilingLevelId, callback: Callback<ProfilingLevelId>): void;
setProfilingLevel(
level: ProfilingLevel,
level: ProfilingLevelId,
options: SetProfilingLevelOptions
): Promise<ProfilingLevel>;
): Promise<ProfilingLevelId>;
setProfilingLevel(
level: ProfilingLevel,
level: ProfilingLevelId,
options: SetProfilingLevelOptions,
callback: Callback<ProfilingLevel>
callback: Callback<ProfilingLevelId>
): void;
setProfilingLevel(
level: ProfilingLevel,
options?: SetProfilingLevelOptions | Callback<ProfilingLevel>,
callback?: Callback<ProfilingLevel>
): Promise<ProfilingLevel> | void {
level: ProfilingLevelId,
options?: SetProfilingLevelOptions | Callback<ProfilingLevelId>,
callback?: Callback<ProfilingLevelId>
): Promise<ProfilingLevelId> | void {
if (typeof options === 'function') (callback = options), (options = {});

return executeOperation(
Expand Down
19 changes: 11 additions & 8 deletions src/deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,16 @@ try {
} catch {} // eslint-disable-line

/** @public */
export const enum AutoEncryptionLoggerLevels {
FatalError = 0,
Error = 1,
Warning = 2,
Info = 3,
Trace = 4
}
export const AutoEncryptionLoggerLevel = Object.freeze({
FatalError: 0,
Error: 1,
Warning: 2,
Info: 3,
Trace: 4
} as const);

/** @public */
export type AutoEncryptionLoggerLevelId = typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel];

/** @public */
export interface AutoEncryptionOptions {
Expand Down Expand Up @@ -146,7 +149,7 @@ export interface AutoEncryptionOptions {
bypassAutoEncryption?: boolean;
options?: {
/** An optional hook to catch logging messages from the underlying encryption engine */
logger?: (level: AutoEncryptionLoggerLevels, message: string) => void;
logger?: (level: AutoEncryptionLoggerLevelId, message: string) => void;
};
extraOptions?: {
/**
Expand Down
42 changes: 23 additions & 19 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ export {
GridFSBucket
};

// enums
export { ProfilingLevel } from './operations/set_profiling_level';
export { ServerType, TopologyType } from './sdam/common';
export { LoggerLevel } from './logger';
export { AutoEncryptionLoggerLevel } from './deps';
export { BatchType } from './bulk/common';
export { AuthMechanism } from './cmap/auth/defaultAuthProviders';
export { CURSOR_FLAGS } from './cursor/abstract_cursor';
export { Compressor } from './cmap/wire_protocol/compression';
export { ExplainVerbosity } from './explain';
export { ReadConcernLevel } from './read_concern';
export { ReadPreferenceMode } from './read_preference';

// type only exports below, these are removed from emitted JS
export type { AdminPrivate } from './admin';
export type { Instrumentation } from './apm';
export type { Document, BSONSerializeOptions } from './bson';
Expand All @@ -99,7 +113,7 @@ export type {
OperationTime,
ResumeOptions
} from './change_stream';
export type { AuthMechanism, AuthMechanismId } from './cmap/auth/defaultAuthProviders';
export type { AuthMechanismId } from './cmap/auth/defaultAuthProviders';
export type { MongoCredentials, MongoCredentialsOptions } from './cmap/auth/mongo_credentials';
export type {
WriteProtocolMessageType,
Expand Down Expand Up @@ -132,20 +146,19 @@ export type {
MessageStreamOptions
} from './cmap/message_stream';
export type { StreamDescription, StreamDescriptionOptions } from './cmap/stream_description';
export type { CompressorName, Compressor } from './cmap/wire_protocol/compression';
export type { CompressorName } from './cmap/wire_protocol/compression';
export type { CollectionPrivate, CollectionOptions } from './collection';
export type { AggregationCursorOptions } from './cursor/aggregation_cursor';
export type {
CursorCloseOptions,
CursorStreamOptions,
AbstractCursorOptions,
CURSOR_FLAGS,
CursorFlag
} from './cursor/abstract_cursor';
export type { DbPrivate, DbOptions } from './db';
export type { AutoEncryptionOptions, AutoEncryptionLoggerLevels, AutoEncrypter } from './deps';
export type { AutoEncryptionOptions, AutoEncryptionLoggerLevelId, AutoEncrypter } from './deps';
export type { AnyError, ErrorDescription } from './error';
export type { Explain, ExplainOptions, ExplainVerbosity, ExplainVerbosityLike } from './explain';
export type { Explain, ExplainOptions, ExplainVerbosityLike } from './explain';
export type {
GridFSBucketReadStream,
GridFSBucketReadStreamOptions,
Expand All @@ -159,14 +172,12 @@ export type {
TFileId,
GridFSBucketWriteStream
} from './gridfs-stream/upload';
export type { LoggerOptions, LoggerFunction, LoggerLevel } from './logger';
export type { LoggerOptions, LoggerFunction, LoggerLevelId } from './logger';
export type {
MongoClientPrivate,
MongoClientOptions,
WithSessionCallback,
PkFactory,
LogLevel,
LogLevelId,
Auth,
DriverInfo,
MongoOptions,
Expand Down Expand Up @@ -221,7 +232,7 @@ export type { ProfilingLevelOptions } from './operations/profiling_level';
export type { RemoveUserOptions } from './operations/remove_user';
export type { RenameOptions } from './operations/rename';
export type { RunCommandOptions } from './operations/run_command';
export type { ProfilingLevel, SetProfilingLevelOptions } from './operations/set_profiling_level';
export type { ProfilingLevelId, SetProfilingLevelOptions } from './operations/set_profiling_level';
export type { CollStatsOptions, DbStatsOptions } from './operations/stats';
export type {
UpdateResult,
Expand All @@ -230,22 +241,16 @@ export type {
UpdateStatement
} from './operations/update';
export type { ValidateCollectionOptions } from './operations/validate_collection';
export type {
ReadConcern,
ReadConcernLike,
ReadConcernLevel,
ReadConcernLevelId
} from './read_concern';
export type { ReadConcern, ReadConcernLike, ReadConcernLevelId } from './read_concern';
export type {
ReadPreferenceLike,
ReadPreferenceModeId,
ReadPreferenceMode,
ReadPreferenceOptions,
ReadPreferenceLikeOptions,
ReadPreferenceFromOptions,
HedgeOptions
} from './read_preference';
export type { ClusterTime, ServerType, TimerQueue, TopologyType } from './sdam/common';
export type { ClusterTime, ServerTypeId, TimerQueue, TopologyTypeId } from './sdam/common';
export type { TopologyDescriptionChangedEvent } from './sdam/events';
export type {
Monitor,
Expand Down Expand Up @@ -282,7 +287,7 @@ export type {
ServerSessionId,
WithTransactionCallback
} from './sessions';
export type { TransactionOptions, Transaction, TxnState } from './transactions';
export type { TransactionOptions, Transaction, TxnState, TxnStateId } from './transactions';
export type {
Callback,
ClientMetadata,
Expand All @@ -298,7 +303,6 @@ export type { InternalAbstractCursorOptions } from './cursor/abstract_cursor';
export type {
BulkOperationBase,
BulkOperationPrivate,
BatchType,
BatchTypeId,
FindOperators,
Batch
Expand Down
35 changes: 21 additions & 14 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { format as f } from 'util';
import { format } from 'util';
import { MongoError } from './error';

// Filters for classes
const classFilters: any = {};
let filteredClasses: any = {};
let level: LoggerLevel;
let level: LoggerLevelId;

// Save the process id
const pid = process.pid;
Expand All @@ -13,20 +13,27 @@ const pid = process.pid;
let currentLogger: LoggerFunction = console.warn;

/** @public */
export enum LoggerLevel {
ERROR = 'error',
WARN = 'warn',
INFO = 'info',
DEBUG = 'debug'
}
export const LoggerLevel = Object.freeze({
ERROR: 'error',
WARN: 'warn',
INFO: 'info',
DEBUG: 'debug',
error: 'error',
warn: 'warn',
info: 'info',
debug: 'debug'
} as const);

/** @public */
export type LoggerLevelId = typeof LoggerLevel[keyof typeof LoggerLevel];

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

/** @public */
export interface LoggerOptions {
logger?: LoggerFunction;
loggerLevel?: LoggerLevel;
loggerLevel?: LoggerLevelId;
}

/**
Expand Down Expand Up @@ -76,7 +83,7 @@ export class Logger {
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
) {
const dateTime = new Date().getTime();
const msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message);
const msg = format('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message);
const state = {
type: LoggerLevel.DEBUG,
message,
Expand All @@ -103,7 +110,7 @@ export class Logger {
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
) {
const dateTime = new Date().getTime();
const msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message);
const msg = format('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message);
const state = {
type: LoggerLevel.WARN,
message,
Expand All @@ -130,7 +137,7 @@ export class Logger {
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
) {
const dateTime = new Date().getTime();
const msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message);
const msg = format('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message);
const state = {
type: LoggerLevel.INFO,
message,
Expand All @@ -157,7 +164,7 @@ export class Logger {
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
) {
const dateTime = new Date().getTime();
const msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message);
const msg = format('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message);
const state = {
type: LoggerLevel.ERROR,
message,
Expand Down Expand Up @@ -238,7 +245,7 @@ export class Logger {
*
* @param newLevel - Set current log level (debug, warn, info, error)
*/
static setLevel(newLevel: LoggerLevel): void {
static setLevel(newLevel: LoggerLevelId): void {
if (
newLevel !== LoggerLevel.INFO &&
newLevel !== LoggerLevel.ERROR &&
Expand Down
Loading

0 comments on commit d52c00e

Please sign in to comment.