Skip to content

Commit

Permalink
chore: add a few typescript types (#1471)
Browse files Browse the repository at this point in the history
  • Loading branch information
TysonAndre authored Nov 28, 2021
1 parent f5d8b73 commit b817747
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 37 deletions.
4 changes: 2 additions & 2 deletions lib/autoPipelining.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,9 @@ export function executeWithAutoPipelining(
setImmediate(executeAutoPipeline, client, slotKey);
}

// Create the promise which will execute the
// Create the promise which will execute the command in the pipeline.
const autoPipelinePromise = new CustomPromise(function (resolve, reject) {
pipeline[kCallbacks].push(function (err, value) {
pipeline[kCallbacks].push(function (err: Error | null, value: any) {
if (err) {
reject(err);
return;
Expand Down
17 changes: 10 additions & 7 deletions lib/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,16 @@ export default class Command implements ICommand {

private static getFlagMap(): IFlagMap {
if (!this.flagMap) {
this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => {
map[flagName] = {};
Command.FLAGS[flagName].forEach((commandName) => {
map[flagName][commandName] = true;
});
return map;
}, {});
this.flagMap = Object.keys(Command.FLAGS).reduce(
(map: IFlagMap, flagName: string) => {
map[flagName] = {};
Command.FLAGS[flagName].forEach((commandName: string) => {
map[flagName][commandName] = true;
});
return map;
},
{}
);
}
return this.flagMap;
}
Expand Down
2 changes: 2 additions & 0 deletions lib/redis/RedisOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export interface IRedisOptions
enableAutoPipelining?: boolean;
autoPipeliningIgnoredCommands?: string[];
maxScriptsCachingTime?: number;
offlineQueue?: boolean;
commandQueue?: boolean;
}

export const DEFAULT_REDIS_OPTIONS: IRedisOptions = {
Expand Down
25 changes: 16 additions & 9 deletions lib/redis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
ReconnectOnError,
DEFAULT_REDIS_OPTIONS,
} from "./RedisOptions";
import { NetStream } from "../types";
import { NetStream, CallbackFunction, ICommandItem } from "../types";

const debug = Debug("redis");

Expand Down Expand Up @@ -339,7 +339,7 @@ Redis.prototype.connect = function (callback) {
this.connector.connect(function (type, err) {
_this.silentEmit(type, err);
}) as Promise<NetStream>,
function (err, stream) {
function (err: Error | null, stream?: NetStream) {
if (err) {
_this.flushQueue(err);
_this.silentEmit("error", err);
Expand Down Expand Up @@ -473,17 +473,24 @@ Redis.prototype.end = function () {
*
* @public
*/
Redis.prototype.duplicate = function (override) {
Redis.prototype.duplicate = function (override: IRedisOptions) {
return new Redis(Object.assign({}, this.options, override || {}));
};

Redis.prototype.recoverFromFatalError = function (commandError, err, options) {
Redis.prototype.recoverFromFatalError = function (
commandError,
err: Error | null,
options
) {
this.flushQueue(err, options);
this.silentEmit("error", err);
this.disconnect(true);
};

Redis.prototype.handleReconnection = function handleReconnection(err, item) {
Redis.prototype.handleReconnection = function handleReconnection(
err: Error,
item: ICommandItem
) {
let needReconnect: ReturnType<ReconnectOnError> = false;
if (this.options.reconnectOnError) {
needReconnect = this.options.reconnectOnError(err);
Expand Down Expand Up @@ -521,7 +528,7 @@ Redis.prototype.handleReconnection = function handleReconnection(err, item) {
* @param {object} options
* @private
*/
Redis.prototype.flushQueue = function (error, options) {
Redis.prototype.flushQueue = function (error: Error, options: IRedisOptions) {
options = defaults({}, options, {
offlineQueue: true,
commandQueue: true,
Expand Down Expand Up @@ -555,9 +562,9 @@ Redis.prototype.flushQueue = function (error, options) {
* @param {Function} callback
* @private
*/
Redis.prototype._readyCheck = function (callback) {
Redis.prototype._readyCheck = function (callback: CallbackFunction) {
const _this = this;
this.info(function (err, res) {
this.info(function (err: Error | null, res: string) {
if (err) {
return callback(err);
}
Expand Down Expand Up @@ -710,7 +717,7 @@ addTransactionSupport(Redis.prototype);
* ```
* @private
*/
Redis.prototype.sendCommand = function (command: Command, stream) {
Redis.prototype.sendCommand = function (command: Command, stream: NetStream) {
if (this.status === "wait") {
this.connect().catch(noop);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default class Script {
const result = container.sendCommand(evalsha);
if (isPromise(result)) {
return asCallback(
result.catch((err) => {
result.catch((err: Error) => {
if (err.toString().indexOf("NOSCRIPT") === -1) {
throw err;
}
Expand Down
8 changes: 4 additions & 4 deletions lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function addTransactionSupport(redis) {
}
const promise = exec.call(pipeline);
return asCallback(
promise.then(function (result) {
promise.then(function (result: any[]): any[] | null {
const execResult = result[result.length - 1];
if (typeof execResult === "undefined") {
throw new Error(
Expand All @@ -80,7 +80,7 @@ export function addTransactionSupport(redis) {
};

const { execBuffer } = pipeline;
pipeline.execBuffer = function (callback) {
pipeline.execBuffer = function (callback: CallbackFunction) {
if (this._transactions > 0) {
execBuffer.call(pipeline);
}
Expand All @@ -90,9 +90,9 @@ export function addTransactionSupport(redis) {
};

const { exec } = redis;
redis.exec = function (callback: CallbackFunction) {
redis.exec = function (callback: CallbackFunction): Promise<any[] | null> {
return asCallback(
exec.call(this).then(function (results) {
exec.call(this).then(function (results: any[] | null) {
if (Array.isArray(results)) {
results = wrapMultiResult(results);
}
Expand Down
41 changes: 27 additions & 14 deletions lib/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { parse as urllibParse } from "url";
import { defaults, noop, flatten } from "./lodash";
import { CallbackFunction } from "../types";
import Debug from "./debug";

import TLSProfiles from "../constants/TLSProfiles";
Expand Down Expand Up @@ -74,7 +75,7 @@ export function convertBufferToString(value: any, encoding?: string) {
* ```
* @private
*/
export function wrapMultiResult(arr) {
export function wrapMultiResult(arr: any[] | null): any[][] {
// When using WATCH/EXEC transactions, the EXEC will return
// a null instead of an array
if (!arr) {
Expand All @@ -94,7 +95,7 @@ export function wrapMultiResult(arr) {
}

/**
* Detect the argument is a int
* Detect if the argument is a int
*
* @param {string} value
* @return {boolean} Whether the value is a int
Expand All @@ -113,7 +114,7 @@ export function wrapMultiResult(arr) {
* ```
* @private
*/
export function isInt(value): value is string {
export function isInt(value: any): value is string {
const x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
Expand All @@ -129,7 +130,7 @@ export function isInt(value): value is string {
* { a: 'b', c: 'd' }
* ```
*/
export function packObject(array) {
export function packObject(array: any[]): Record<string, any> {
const result = {};
const length = array.length;

Expand All @@ -147,8 +148,8 @@ export function packObject(array) {
* @param {number} timeout
* @return {function}
*/
export function timeout(callback, timeout) {
let timer;
export function timeout(callback: CallbackFunction, timeout: number) {
let timer: NodeJS.Timeout;
const run = function () {
if (timer) {
clearTimeout(timer);
Expand All @@ -171,9 +172,11 @@ export function timeout(callback, timeout) {
* ['a', '1']
* ```
*/
export function convertObjectToArray(obj) {
export function convertObjectToArray<T>(
obj: Record<string, T>
): Array<string | T> {
const result = [];
const keys = Object.keys(obj);
const keys = Object.keys(obj); // Object.entries requires node 7+

for (let i = 0, l = keys.length; i < l; i++) {
result.push(keys[i], obj[keys[i]]);
Expand All @@ -188,12 +191,12 @@ export function convertObjectToArray(obj) {
* @return {array}
* @example
* ```js
* > convertObjectToArray(new Map([[1, '2']]))
* > convertMapToArray(new Map([[1, '2']]))
* [1, '2']
* ```
*/
export function convertMapToArray<K, V>(map: Map<K, V>): Array<K | V> {
const result = [];
const result: Array<K | V> = [];
let pos = 0;
map.forEach(function (value, key) {
result[pos] = key;
Expand All @@ -209,7 +212,7 @@ export function convertMapToArray<K, V>(map: Map<K, V>): Array<K | V> {
* @param {*} arg
* @return {string}
*/
export function toArg(arg) {
export function toArg(arg: any): string {
if (arg === null || typeof arg === "undefined") {
return "";
}
Expand All @@ -223,7 +226,11 @@ export function toArg(arg) {
* @param {string} friendlyStack - the stack that more meaningful
* @param {string} filterPath - only show stacks with the specified path
*/
export function optimizeErrorStack(error, friendlyStack, filterPath) {
export function optimizeErrorStack(
error: Error,
friendlyStack: string,
filterPath: string
) {
const stacks = friendlyStack.split("\n");
let lines = "";
let i;
Expand All @@ -246,7 +253,7 @@ export function optimizeErrorStack(error, friendlyStack, filterPath) {
* @param {string} url - the redis protocol url
* @return {Object}
*/
export function parseURL(url) {
export function parseURL(url: string) {
if (isInt(url)) {
return { port: url };
}
Expand Down Expand Up @@ -291,13 +298,19 @@ export function parseURL(url) {
return result;
}

interface TLSOptions {
port: number;
host: string;
[key: string]: any;
}

/**
* Resolve TLS profile shortcut in connection options
*
* @param {Object} options - the redis connection options
* @return {Object}
*/
export function resolveTLSProfile(options) {
export function resolveTLSProfile(options: TLSOptions): TLSOptions {
let tls = options?.tls;

if (typeof tls === "string") tls = { profile: tls };
Expand Down

0 comments on commit b817747

Please sign in to comment.