From 017b9d159dcbf348e00600790ac46ee209f74c1e Mon Sep 17 00:00:00 2001 From: Jesse Chan Date: Mon, 2 Nov 2020 19:32:33 +0800 Subject: [PATCH] server: replace explicit binds with arrow functions --- server/models/DiskUsage.ts | 6 +-- server/models/FeedReader.ts | 6 +-- server/models/HistoryEra.ts | 40 +++++-------------- server/services/feedService.ts | 12 +++--- server/services/historyService.ts | 20 ++++------ .../interfaces/clientGatewayService.ts | 15 ++----- server/services/notificationService.ts | 7 +--- .../services/rTorrent/clientRequestManager.ts | 15 +++---- server/services/taxonomyService.ts | 16 +++----- server/services/torrentService.ts | 21 ++++------ 10 files changed, 55 insertions(+), 103 deletions(-) diff --git a/server/models/DiskUsage.ts b/server/models/DiskUsage.ts index 8c619b9a..b07a5656 100644 --- a/server/models/DiskUsage.ts +++ b/server/models/DiskUsage.ts @@ -37,7 +37,7 @@ class DiskUsage extends (EventEmitter as new () => TypedEmitter // start polling disk usage when the first listener is added this.on('newListener', (event) => { if (this.listenerCount('DISK_USAGE_CHANGE') === 0 && event === 'DISK_USAGE_CHANGE') { - this.updateInterval = setInterval(this.updateDisks.bind(this), INTERVAL_UPDATE); + this.updateInterval = setInterval(this.updateDisks, INTERVAL_UPDATE); } }); @@ -53,7 +53,7 @@ class DiskUsage extends (EventEmitter as new () => TypedEmitter }); } - updateDisks() { + updateDisks = () => { if (!isPlatformSupported()) { return Promise.reject(); } @@ -64,7 +64,7 @@ class DiskUsage extends (EventEmitter as new () => TypedEmitter this.emit('DISK_USAGE_CHANGE', this.getDiskUsage()); } }); - } + }; getDiskUsage(): DiskUsageSummary { return { diff --git a/server/models/FeedReader.ts b/server/models/FeedReader.ts index 61eb793e..ffacecb0 100644 --- a/server/models/FeedReader.ts +++ b/server/models/FeedReader.ts @@ -35,7 +35,7 @@ class FeedReader { return this.items; } - handleFeedItems(items: Array) { + handleFeedItems = (items: Array) => { const nextLength = this.items.length + items.length; if (nextLength >= this.options.maxHistory) { const diff = nextLength - this.options.maxHistory; @@ -45,7 +45,7 @@ class FeedReader { this.items = this.items.concat(items); this.options.onNewItems(this.options, items); - } + }; initReader() { this.reader = new FeedSub(this.options.url, { @@ -56,7 +56,7 @@ class FeedReader { forceInterval: true, }); - this.reader.on('items', this.handleFeedItems.bind(this)); + this.reader.on('items', this.handleFeedItems); this.reader.on('error', (error) => { console.log('Feed reader error:', error); }); diff --git a/server/models/HistoryEra.ts b/server/models/HistoryEra.ts index 659835eb..58734a02 100644 --- a/server/models/HistoryEra.ts +++ b/server/models/HistoryEra.ts @@ -40,7 +40,7 @@ class HistoryEra { cleanupInterval = config.dbCleanInterval; } - this.startAutoCleanup(cleanupInterval, this.db); + this.autoCleanupInterval = setInterval(this.cleanup, cleanupInterval); } loadDatabase(userId: UserInDatabase['_id'], dbName: string) { @@ -91,10 +91,10 @@ class HistoryEra { } } - cleanup(db: this['db']) { - this.removeOutdatedData(db); - db.persistence.compactDatafile(); - } + cleanup = () => { + this.removeOutdatedData(this.db); + this.db.persistence.compactDatafile(); + }; getData(callback: (snapshots: Array | null, error?: Error) => void) { const minTimestamp = Date.now() - this.opts.maxTime; @@ -147,40 +147,18 @@ class HistoryEra { } if (nextEraUpdateInterval) { - this.startNextEraUpdate(nextEraUpdateInterval, this.db); + this.nextEraUpdateInterval = setInterval(this.updateNextEra, nextEraUpdateInterval); } } - startAutoCleanup(interval: number, db: this['db']): void { - this.autoCleanupInterval = setInterval(this.cleanup.bind(this, db), interval); - } - - startNextEraUpdate(interval: number, currentDB: this['db']): void { - this.nextEraUpdateInterval = setInterval(this.updateNextEra.bind(this, currentDB), interval); - } - - stopAutoCleanup(): void { - if (this.autoCleanupInterval != null) { - clearInterval(this.autoCleanupInterval); - delete this.autoCleanupInterval; - } - } - - stopNextEraUpdate(): void { - if (this.nextEraUpdateInterval != null) { - clearInterval(this.nextEraUpdateInterval); - delete this.nextEraUpdateInterval; - } - } - - updateNextEra(currentDB: this['db']): void { + updateNextEra = (): void => { if (this.opts.nextEraUpdateInterval == null) { return; } const minTimestamp = Date.now() - this.opts.nextEraUpdateInterval; - currentDB.find({timestamp: {$gte: minTimestamp}}, (err: Error, snapshots: Array) => { + this.db.find({timestamp: {$gte: minTimestamp}}, (err: Error, snapshots: Array) => { if (err || this.opts.nextEra == null) { return; } @@ -198,7 +176,7 @@ class HistoryEra { upload: Number(Number(upTotal / snapshots.length).toFixed(1)), }); }); - } + }; } export default HistoryEra; diff --git a/server/services/feedService.ts b/server/services/feedService.ts index f9aaeb28..6d559cc3 100644 --- a/server/services/feedService.ts +++ b/server/services/feedService.ts @@ -227,7 +227,7 @@ class FeedService extends BaseService { }); } - handleNewItems(feedReaderOptions: FeedReaderOptions, feedItems: Array): void { + handleNewItems = (feedReaderOptions: FeedReaderOptions, feedItems: Array): void => { this.getPreviouslyMatchedUrls() .then((previouslyMatchedUrls) => { const {feedID, feedLabel} = feedReaderOptions; @@ -285,9 +285,9 @@ class FeedService extends BaseService { }); }) .catch(console.error); - } + }; - init() { + private init() { this.db.find({}, (err: Error, docs: Array) => { if (err) { return; @@ -348,7 +348,7 @@ class FeedService extends BaseService { }); } - loadDatabase(): Datastore { + private loadDatabase(): Datastore { if (this.db != null) { return this.db; } @@ -389,7 +389,7 @@ class FeedService extends BaseService { }); } - startNewFeed(feed: Feed) { + private startNewFeed(feed: Feed) { const {_id: feedID, label: feedLabel, url, interval} = feed; if (typeof feedID !== 'string' || typeof url !== 'string') { @@ -401,7 +401,7 @@ class FeedService extends BaseService { } this.feedReaders.push( - new FeedReader({feedID, feedLabel, url, interval, maxHistory: 100, onNewItems: this.handleNewItems.bind(this)}), + new FeedReader({feedID, feedLabel, url, interval, maxHistory: 100, onNewItems: this.handleNewItems}), ); return true; diff --git a/server/services/historyService.ts b/server/services/historyService.ts index cc0b2f28..358e4c14 100644 --- a/server/services/historyService.ts +++ b/server/services/historyService.ts @@ -90,10 +90,6 @@ class HistoryService extends BaseService { nextEra = snapshot; }); - this.fetchCurrentTransferSummary = this.fetchCurrentTransferSummary.bind(this); - this.handleFetchTransferSummaryError = this.handleFetchTransferSummaryError.bind(this); - this.handleFetchTransferSummarySuccess = this.handleFetchTransferSummarySuccess.bind(this); - this.onServicesUpdated = () => { this.fetchCurrentTransferSummary(); }; @@ -109,16 +105,16 @@ class HistoryService extends BaseService { } } - fetchCurrentTransferSummary() { + fetchCurrentTransferSummary = () => { if (this.pollTimeout != null) { clearTimeout(this.pollTimeout); } this.services?.clientGatewayService ?.fetchTransferSummary() - .then(this.handleFetchTransferSummarySuccess.bind(this)) - .catch(this.handleFetchTransferSummaryError.bind(this)); - } + .then(this.handleFetchTransferSummarySuccess) + .catch(this.handleFetchTransferSummaryError); + }; getTransferSummary() { return { @@ -149,7 +145,7 @@ class HistoryService extends BaseService { }); } - handleFetchTransferSummarySuccess(nextTransferSummary: TransferSummary) { + handleFetchTransferSummarySuccess = (nextTransferSummary: TransferSummary) => { const summaryDiff = jsonpatch.compare(this.transferSummary, nextTransferSummary); this.emit('TRANSFER_SUMMARY_DIFF_CHANGE', { @@ -167,9 +163,9 @@ class HistoryService extends BaseService { this.deferFetchTransferSummary(); this.emit('FETCH_TRANSFER_SUMMARY_SUCCESS'); - } + }; - handleFetchTransferSummaryError() { + handleFetchTransferSummaryError = () => { let nextInterval = config.torrentClientPollInterval || 2000; // If more than 2 consecutive errors have occurred, then we delay the next request. @@ -181,7 +177,7 @@ class HistoryService extends BaseService { this.deferFetchTransferSummary(nextInterval); this.emit('FETCH_TRANSFER_SUMMARY_ERROR'); - } + }; } export default HistoryService; diff --git a/server/services/interfaces/clientGatewayService.ts b/server/services/interfaces/clientGatewayService.ts index ac448980..4d7efb0c 100644 --- a/server/services/interfaces/clientGatewayService.ts +++ b/server/services/interfaces/clientGatewayService.ts @@ -32,13 +32,6 @@ interface ClientGatewayServiceEvents { abstract class ClientGatewayService extends BaseService { hasError = false; - constructor(...args: ConstructorParameters) { - super(...args); - - this.processClientRequestError = this.processClientRequestError.bind(this); - this.processClientRequestSuccess = this.processClientRequestSuccess.bind(this); - } - /** * Adds torrents by file * @@ -184,23 +177,23 @@ abstract class ClientGatewayService extends BaseService; - processClientRequestSuccess(response: T): T { + processClientRequestSuccess = (response: T): T => { if (this.hasError == null || this.hasError === true) { this.hasError = false; this.emit('CLIENT_CONNECTION_STATE_CHANGE'); } return response; - } + }; - processClientRequestError(error: Error) { + processClientRequestError = (error: Error) => { if (!this.hasError) { this.hasError = true; this.emit('CLIENT_CONNECTION_STATE_CHANGE'); } return Promise.reject(error); - } + }; } export default ClientGatewayService; diff --git a/server/services/notificationService.ts b/server/services/notificationService.ts index e9d4a333..a496920a 100644 --- a/server/services/notificationService.ts +++ b/server/services/notificationService.ts @@ -1,5 +1,4 @@ import Datastore from 'nedb'; -import debounce from 'lodash/debounce'; import path from 'path'; import type {Notification, NotificationCount, NotificationFetchOptions} from '@shared/types/Notification'; @@ -20,8 +19,6 @@ class NotificationService extends BaseService { constructor(...args: ConstructorParameters) { super(...args); - this.emitUpdate = debounce(this.emitUpdate.bind(this), 100); - this.onServicesUpdated = () => { this.countNotifications(); }; @@ -77,12 +74,12 @@ class NotificationService extends BaseService { }); } - emitUpdate() { + emitUpdate = () => { this.emit('NOTIFICATION_COUNT_CHANGE', { id: Date.now(), data: this.count, }); - } + }; getNotificationCount() { return this.count; diff --git a/server/services/rTorrent/clientRequestManager.ts b/server/services/rTorrent/clientRequestManager.ts index bf9850cf..b9764d79 100644 --- a/server/services/rTorrent/clientRequestManager.ts +++ b/server/services/rTorrent/clientRequestManager.ts @@ -19,9 +19,6 @@ class ClientRequestManager { constructor(connectionSettings: RTorrentConnectionSettings) { this.connectionSettings = connectionSettings; - this.sendDeferredMethodCall = this.sendDeferredMethodCall.bind(this); - this.sendMethodCall = this.sendMethodCall.bind(this); - this.methodCall = this.methodCall.bind(this); } handleRequestEnd() { @@ -42,7 +39,7 @@ class ClientRequestManager { } } - sendDeferredMethodCall() { + sendDeferredMethodCall = () => { const nextRequest = this.pendingRequests.shift(); if (nextRequest == null) { return; @@ -50,9 +47,9 @@ class ClientRequestManager { this.isRequestPending = true; this.sendMethodCall(nextRequest.methodName, nextRequest.parameters).then(nextRequest.resolve, nextRequest.reject); - } + }; - sendMethodCall(methodName: string, parameters: MethodCallParameters) { + sendMethodCall = (methodName: string, parameters: MethodCallParameters) => { const connectionMethod = this.connectionSettings.type === 'socket' ? { @@ -73,9 +70,9 @@ class ClientRequestManager { throw error; }, ); - } + }; - methodCall(methodName: string, parameters: MethodCallParameters) { + methodCall = (methodName: string, parameters: MethodCallParameters) => { // We only allow one request at a time. if (this.isRequestPending) { return new Promise( @@ -91,7 +88,7 @@ class ClientRequestManager { } this.isRequestPending = true; return this.sendMethodCall(methodName, parameters); - } + }; } export default ClientRequestManager; diff --git a/server/services/taxonomyService.ts b/server/services/taxonomyService.ts index d7b571d1..005a8bf7 100644 --- a/server/services/taxonomyService.ts +++ b/server/services/taxonomyService.ts @@ -23,10 +23,6 @@ class TaxonomyService extends BaseService { constructor(...args: ConstructorParameters) { super(...args); - this.handleProcessTorrent = this.handleProcessTorrent.bind(this); - this.handleProcessTorrentListStart = this.handleProcessTorrentListStart.bind(this); - this.handleProcessTorrentListEnd = this.handleProcessTorrentListEnd.bind(this); - this.onServicesUpdated = () => { if (this.services?.clientGatewayService == null) { return; @@ -59,7 +55,7 @@ class TaxonomyService extends BaseService { }; } - handleProcessTorrentListStart() { + handleProcessTorrentListStart = () => { this.lastTaxonomy = { statusCounts: {...this.taxonomy.statusCounts}, tagCounts: {...this.taxonomy.tagCounts}, @@ -73,9 +69,9 @@ class TaxonomyService extends BaseService { this.taxonomy.statusCounts[''] = 0; this.taxonomy.tagCounts = {'': 0, untagged: 0}; this.taxonomy.trackerCounts = {'': 0}; - } + }; - handleProcessTorrentListEnd({torrents}: {torrents: TorrentList}) { + handleProcessTorrentListEnd = ({torrents}: {torrents: TorrentList}) => { const {length} = Object.keys(torrents); this.taxonomy.statusCounts[''] = length; @@ -90,13 +86,13 @@ class TaxonomyService extends BaseService { id: Date.now(), }); } - } + }; - handleProcessTorrent(torrentProperties: TorrentProperties) { + handleProcessTorrent = (torrentProperties: TorrentProperties) => { this.incrementStatusCounts(torrentProperties.status); this.incrementTagCounts(torrentProperties.tags); this.incrementTrackerCounts(torrentProperties.trackerURIs); - } + }; incrementStatusCounts(statuses: Array) { statuses.forEach((status) => { diff --git a/server/services/torrentService.ts b/server/services/torrentService.ts index e60597e5..569b4bfe 100644 --- a/server/services/torrentService.ts +++ b/server/services/torrentService.ts @@ -22,11 +22,6 @@ class TorrentService extends BaseService { constructor(...args: ConstructorParameters) { super(...args); - this.fetchTorrentList = this.fetchTorrentList.bind(this); - this.handleTorrentProcessed = this.handleTorrentProcessed.bind(this); - this.handleFetchTorrentListSuccess = this.handleFetchTorrentListSuccess.bind(this); - this.handleFetchTorrentListError = this.handleFetchTorrentListError.bind(this); - this.onServicesUpdated = () => { if (this.services?.clientGatewayService == null) { return; @@ -67,7 +62,7 @@ class TorrentService extends BaseService { } } - fetchTorrentList() { + fetchTorrentList = () => { if (this.pollTimeout != null) { clearTimeout(this.pollTimeout); } @@ -78,7 +73,7 @@ class TorrentService extends BaseService { .then(this.handleFetchTorrentListSuccess) .catch(this.handleFetchTorrentListError) || Promise.reject() ); - } + }; getTorrent(hash: TorrentProperties['hash']) { return this.torrentListSummary.torrents[hash]; @@ -92,14 +87,14 @@ class TorrentService extends BaseService { return this.torrentListSummary; } - handleFetchTorrentListError() { + handleFetchTorrentListError = () => { this.deferFetchTorrentList(); this.emit('FETCH_TORRENT_LIST_ERROR'); return null; - } + }; - handleFetchTorrentListSuccess(nextTorrentListSummary: this['torrentListSummary']) { + handleFetchTorrentListSuccess = (nextTorrentListSummary: this['torrentListSummary']) => { const diff = jsonpatch.compare(this.torrentListSummary.torrents, nextTorrentListSummary.torrents); if (diff.length > 0) { this.emit('TORRENT_LIST_DIFF_CHANGE', {diff, id: nextTorrentListSummary.id}); @@ -111,9 +106,9 @@ class TorrentService extends BaseService { this.emit('FETCH_TORRENT_LIST_SUCCESS'); return this.torrentListSummary; - } + }; - handleTorrentProcessed(nextTorrentProperties: TorrentProperties) { + handleTorrentProcessed = (nextTorrentProperties: TorrentProperties) => { const prevTorrentProperties = this.torrentListSummary.torrents[nextTorrentProperties.hash]; if (hasTorrentFinished(prevTorrentProperties, nextTorrentProperties)) { @@ -124,7 +119,7 @@ class TorrentService extends BaseService { }, ]); } - } + }; } export default TorrentService;