Skip to content

Commit

Permalink
refactor: transform utils to TypeScript (#715)
Browse files Browse the repository at this point in the history
  • Loading branch information
luin committed Oct 8, 2018
1 parent eb68e9a commit 9f4cfd2
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 37 deletions.
42 changes: 21 additions & 21 deletions lib/connectors/SentinelConnector/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {createConnection, Socket} from 'net'
import {sample} from '../../utils/lodash'
import {CONNECTION_CLOSED_ERROR_MSG, packObject} from '../../utils/index'
import {CONNECTION_CLOSED_ERROR_MSG, packObject} from '../../utils'
import {TLSSocket} from 'tls'
import {ITcpConnectionOptions, isIIpcConnectionOptions} from '../StandaloneConnector'
import SentinelIterator from './SentinelIterator'
Expand All @@ -17,7 +17,7 @@ interface IAddressFromResponse {
}

type NodeCallback<T = void> = (err: Error | null, result?: T) => void
type PreferredSlaves =
type PreferredSlaves =
((slaves: Array<IAddressFromResponse>) => IAddressFromResponse) |
Array<{port: string, ip: string, prio?: number}> |
{port: string, ip: string, prio?: number}
Expand Down Expand Up @@ -65,28 +65,28 @@ export default class SentinelConnector extends AbstractConnector {
public connect (callback: NodeCallback<Socket | TLSSocket>, eventEmitter: ErrorEmitter): void {
this.connecting = true
this.retryAttempts = 0

let lastError
const _this = this
connectToNext()

function connectToNext() {
if (!_this.sentinelIterator.hasNext()) {
_this.sentinelIterator.reset(false)
const retryDelay = typeof _this.options.sentinelRetryStrategy === 'function'
? _this.options.sentinelRetryStrategy(++_this.retryAttempts)
: null

let errorMsg = typeof retryDelay !== 'number'
? 'All sentinels are unreachable and retry is disabled.'
: `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`

if (lastError) {
errorMsg += ` Last error: ${lastError.message}`
}

debug(errorMsg)

const error = new Error(errorMsg)
if (typeof retryDelay === 'number') {
setTimeout(connectToNext, retryDelay)
Expand All @@ -96,7 +96,7 @@ export default class SentinelConnector extends AbstractConnector {
}
return
}

const endpoint = _this.sentinelIterator.next()
_this.resolve(endpoint, function (err, resolved) {
if (!_this.connecting) {
Expand All @@ -113,11 +113,11 @@ export default class SentinelConnector extends AbstractConnector {
const errorMsg = err
? 'failed to connect to sentinel ' + endpointAddress + ' because ' + err.message
: 'connected to sentinel ' + endpointAddress + ' successfully, but got an invalid reply: ' + resolved

debug(errorMsg)

eventEmitter('sentinelError', new Error(errorMsg))

if (err) {
lastError = err
}
Expand All @@ -126,7 +126,7 @@ export default class SentinelConnector extends AbstractConnector {
})
}
}

private updateSentinels (client, callback: NodeCallback): void {
client.sentinel('sentinels', this.options.name, (err, result) => {
if (err) {
Expand All @@ -137,7 +137,7 @@ export default class SentinelConnector extends AbstractConnector {
return callback(null)
}

result.map<IAddressFromResponse>(packObject).forEach(sentinel => {
result.map<IAddressFromResponse>(packObject as (value: any) => IAddressFromResponse).forEach(sentinel => {
const flags = sentinel.flags ? sentinel.flags.split(',') : []
if (flags.indexOf('disconnected') === -1 && sentinel.ip && sentinel.port) {
const endpoint = addressResponseToAddress(sentinel)
Expand All @@ -150,7 +150,7 @@ export default class SentinelConnector extends AbstractConnector {
callback(null)
})
}

private resolveMaster (client, callback: NodeCallback<ITcpConnectionOptions>): void {
client.sentinel('get-master-addr-by-name', this.options.name, (err, result) => {
if (err) {
Expand All @@ -166,7 +166,7 @@ export default class SentinelConnector extends AbstractConnector {
})
})
}

private resolveSlave (client, callback: NodeCallback<ITcpConnectionOptions | null>): void {
client.sentinel('slaves', this.options.name, (err, result) => {
client.disconnect()
Expand All @@ -178,14 +178,14 @@ export default class SentinelConnector extends AbstractConnector {
return callback(null, null)
}

const availableSlaves = result.map<IAddressFromResponse>(packObject).filter(slave => (
const availableSlaves = result.map<IAddressFromResponse>(packObject as (value: any) => IAddressFromResponse).filter(slave => (
slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)
))

callback(null, selectPreferredSentinel(availableSlaves, this.options.preferredSlaves))
})
}

private resolve (endpoint, callback: NodeCallback<ITcpConnectionOptions>): void {
if (typeof Redis === 'undefined') {
Redis = require('../../redis')
Expand All @@ -199,10 +199,10 @@ export default class SentinelConnector extends AbstractConnector {
connectTimeout: this.options.connectTimeout,
dropBufferSupport: true
})

// ignore the errors since resolve* methods will handle them
client.on('error', noop)

if (this.options.role === 'slave') {
this.resolveSlave(client, callback)
} else {
Expand Down Expand Up @@ -243,7 +243,7 @@ function selectPreferredSentinel (availableSlaves: IAddressFromResponse[], prefe
}
return 0
})

// loop over preferred slaves and return the first match
for (let p = 0; p < preferredSlavesArray.length; p++) {
for (let a = 0; a < availableSlaves.length; a++) {
Expand Down
32 changes: 16 additions & 16 deletions lib/utils/index.js → lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ var _ = require('./lodash');
* @return {Boolean} Whether the two buffers are equal
* @private
*/
exports.bufferEqual = function (a, b) {
export function bufferEqual (a, b) {
if (typeof a.equals === 'function') {
return a.equals(b);
}
Expand Down Expand Up @@ -41,7 +41,7 @@ exports.bufferEqual = function (a, b) {
* ```
* @private
*/
exports.convertBufferToString = function (value, encoding) {
export function convertBufferToString (value, encoding) {
if (value instanceof Buffer) {
return value.toString(encoding);
}
Expand All @@ -51,7 +51,7 @@ exports.convertBufferToString = function (value, encoding) {
for (var i = 0; i < length; ++i) {
res[i] = value[i] instanceof Buffer && encoding === 'utf8'
? value[i].toString()
: exports.convertBufferToString(value[i], encoding);
: convertBufferToString(value[i], encoding);
}
return res;
}
Expand All @@ -71,7 +71,7 @@ exports.convertBufferToString = function (value, encoding) {
* ```
* @private
*/
exports.wrapMultiResult = function (arr) {
export function wrapMultiResult (arr) {
// When using WATCH/EXEC transactions, the EXEC will return
// a null instead of an array
if (!arr) {
Expand Down Expand Up @@ -110,7 +110,7 @@ exports.wrapMultiResult = function (arr) {
* ```
* @private
*/
exports.isInt = function (value) {
export function isInt (value) {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
};
Expand All @@ -126,7 +126,7 @@ exports.isInt = function (value) {
* { a: 'b', c: 'd' }
* ```
*/
exports.packObject = function (array) {
export function packObject (array) {
var result = {};
var length = array.length;

Expand All @@ -144,7 +144,7 @@ exports.packObject = function (array) {
* @param {number} timeout
* @return {function}
*/
exports.timeout = function (callback, timeout) {
export function timeout (callback, timeout) {
var timer;
var run = function () {
if (timer) {
Expand All @@ -168,7 +168,7 @@ exports.timeout = function (callback, timeout) {
* ['a', '1']
* ```
*/
exports.convertObjectToArray = function (obj) {
export function convertObjectToArray (obj) {
var result = [];
var keys = Object.keys(obj);

Expand All @@ -189,7 +189,7 @@ exports.convertObjectToArray = function (obj) {
* [1, '2']
* ```
*/
exports.convertMapToArray = function (map) {
export function convertMapToArray (map) {
var result = [];
var pos = 0;
map.forEach(function (value, key) {
Expand All @@ -206,7 +206,7 @@ exports.convertMapToArray = function (map) {
* @param {*} arg
* @return {string}
*/
exports.toArg = function (arg) {
export function toArg (arg) {
if (arg === null || typeof arg === 'undefined') {
return '';
}
Expand All @@ -220,7 +220,7 @@ exports.toArg = function (arg) {
* @param {string} friendlyStack - the stack that more meaningful
* @param {string} filterPath - only show stacks with the specified path
*/
exports.optimizeErrorStack = function (error, friendlyStack, filterPath) {
export function optimizeErrorStack (error, friendlyStack, filterPath) {
var stacks = friendlyStack.split('\n');
var lines = '';
var i;
Expand All @@ -243,8 +243,8 @@ exports.optimizeErrorStack = function (error, friendlyStack, filterPath) {
* @param {string} url - the redis protocol url
* @return {Object}
*/
exports.parseURL = function (url) {
if (exports.isInt(url)) {
export function parseURL (url) {
if (isInt(url)) {
return { port: url };
}
var parsed = urllib.parse(url, true, true);
Expand All @@ -254,7 +254,7 @@ exports.parseURL = function (url) {
parsed = urllib.parse(url, true, true);
}

var result = {};
var result: any = {};
if (parsed.auth) {
result.password = parsed.auth.split(':')[1];
}
Expand Down Expand Up @@ -285,7 +285,7 @@ exports.parseURL = function (url) {
* @param {number} [from=0] - start index
* @return {}
*/
exports.sample = function (array, from) {
export function sample (array, from) {
var length = array.length;
if (typeof from !== 'number') {
from = 0;
Expand All @@ -299,4 +299,4 @@ exports.sample = function (array, from) {
/**
* Error message for connection being disconnected
*/
exports.CONNECTION_CLOSED_ERROR_MSG = 'Connection is closed.';
export const CONNECTION_CLOSED_ERROR_MSG = 'Connection is closed.';

0 comments on commit 9f4cfd2

Please sign in to comment.