Skip to content

Commit

Permalink
feat: spam preventation
Browse files Browse the repository at this point in the history
  • Loading branch information
pooya parsa committed Jun 18, 2019
1 parent 7d900f6 commit 7da806b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
- Browser support
- Pause/Resume support
- Mocking support
- Spam preventation by throttling logs

## Installation

Expand Down
13 changes: 13 additions & 0 deletions examples/spam.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/env node -r esm

import { consola } from './utils'

function spam (msg, level = 'warn', count = 10) {
for (let i = 0; i < 10; i++) {
consola[level](msg)
}
}

spam('FOOOOOOO FOOOOOOOOO')
consola.log('bar')
spam('FOOOOOOO FOOOOOOOOO')
21 changes: 21 additions & 0 deletions src/consola.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class Consola {
this._stdout = options.stdout
this._stderr = options.stdout
this._mockFn = options.mockFn
this._throttle = options.throttle || 2000

// Create logger functions for current instance
for (const type in this._types) {
Expand All @@ -28,6 +29,10 @@ class Consola {
if (this._mockFn) {
this.mockTypes()
}

// Keep serialized version of last message
this._lastMessage = null
this._lastMessageTime = null
}

get level () {
Expand Down Expand Up @@ -251,6 +256,22 @@ class Consola {
logObj.tag = logObj.tag.toLowerCase()
}

// Throttle
const diffTime = this._lastMessageTime ? logObj.date - this._lastMessageTime : 0
this._lastMessageTime = logObj.date
if (diffTime < this._throttle) {
try {
const serializedMessage = JSON.stringify([logObj.type, logObj.tag, logObj.args])
const isSameMessage = this._lastMessage === serializedMessage
this._lastMessage = serializedMessage
if (isSameMessage) {
return // SPAM!
}
} catch (_) {
// Circular References
}
}

// Log
if (this._async) {
return this._logAsync(logObj)
Expand Down

0 comments on commit 7da806b

Please sign in to comment.