Skip to content

Commit 7da806b

Browse files
author
pooya parsa
committedJun 18, 2019
feat: spam preventation
1 parent 7d900f6 commit 7da806b

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed
 

Diff for: ‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
- Browser support
2121
- Pause/Resume support
2222
- Mocking support
23+
- Spam preventation by throttling logs
2324

2425
## Installation
2526

Diff for: ‎examples/spam.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/usr/bin/env node -r esm
2+
3+
import { consola } from './utils'
4+
5+
function spam (msg, level = 'warn', count = 10) {
6+
for (let i = 0; i < 10; i++) {
7+
consola[level](msg)
8+
}
9+
}
10+
11+
spam('FOOOOOOO FOOOOOOOOO')
12+
consola.log('bar')
13+
spam('FOOOOOOO FOOOOOOOOO')

Diff for: ‎src/consola.js

+21
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class Consola {
1414
this._stdout = options.stdout
1515
this._stderr = options.stdout
1616
this._mockFn = options.mockFn
17+
this._throttle = options.throttle || 2000
1718

1819
// Create logger functions for current instance
1920
for (const type in this._types) {
@@ -28,6 +29,10 @@ class Consola {
2829
if (this._mockFn) {
2930
this.mockTypes()
3031
}
32+
33+
// Keep serialized version of last message
34+
this._lastMessage = null
35+
this._lastMessageTime = null
3136
}
3237

3338
get level () {
@@ -251,6 +256,22 @@ class Consola {
251256
logObj.tag = logObj.tag.toLowerCase()
252257
}
253258

259+
// Throttle
260+
const diffTime = this._lastMessageTime ? logObj.date - this._lastMessageTime : 0
261+
this._lastMessageTime = logObj.date
262+
if (diffTime < this._throttle) {
263+
try {
264+
const serializedMessage = JSON.stringify([logObj.type, logObj.tag, logObj.args])
265+
const isSameMessage = this._lastMessage === serializedMessage
266+
this._lastMessage = serializedMessage
267+
if (isSameMessage) {
268+
return // SPAM!
269+
}
270+
} catch (_) {
271+
// Circular References
272+
}
273+
}
274+
254275
// Log
255276
if (this._async) {
256277
return this._logAsync(logObj)

0 commit comments

Comments
 (0)
Please sign in to comment.