Skip to content

Commit 4ae3614

Browse files
committed
feat: return new consola instance with consola.create
1 parent aa2216f commit 4ae3614

File tree

1 file changed

+42
-34
lines changed

1 file changed

+42
-34
lines changed

src/consola.js

Lines changed: 42 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,64 @@
1-
import types from './types'
1+
import defaultTypes from './types'
22

33
export default class Consola {
44
constructor (options = {}) {
5+
// Public fields
56
this.reporters = options.reporters || []
6-
this.types = Object.assign({}, types, options.types)
77
this.level = options.level != null ? options.level : 3
88

9-
Object.assign(this, this.withDefaults())
10-
}
9+
// Prevate fields
10+
// Used for constructur and create
11+
this.types = options.types || defaultTypes
12+
this.defaults = options.defaults || {}
13+
14+
// Method aliases
15+
this.withDefaults = this.defaults
16+
this.withScope = this.scope
1117

12-
withDefaults (defaults) {
13-
const logger = {}
18+
// Create logger functions for current instance
1419
for (const type in this.types) {
15-
logger[type] = this._createLogFn(Object.assign(
20+
this[type] = this._createLogFn(Object.assign(
1621
{ type },
1722
this.types[type],
18-
defaults
23+
this.defaults
1924
))
2025
}
21-
return logger
2226
}
2327

24-
withScope (scope) {
25-
return this.withDefaults({ scope })
28+
create (options) {
29+
return new Consola(Object.assign({}, this, options))
30+
}
31+
32+
defaults (defaults) {
33+
return this.create({ defaults })
34+
}
35+
36+
scope (scope) {
37+
return this.defaults({ scope })
38+
}
39+
40+
add (reporter) {
41+
this.reporters.push(reporter)
42+
return this
43+
}
44+
45+
clear () {
46+
this.reporters.splice(0)
47+
return this
48+
}
49+
50+
remove (reporter) {
51+
const i = this.reporters.indexOf(reporter)
52+
if (i >= 0) {
53+
return this.reporters.splice(i, 1)
54+
}
55+
return this
2656
}
2757

2858
_createLogFn (defaults) {
2959
function log (arg1, arg2, ...args) {
3060
// Construct a new log object
31-
const logObj = Object.assign(
32-
{ date: new Date() },
33-
defaults,
34-
{ scope: this.scope }
35-
)
61+
const logObj = Object.assign({ date: new Date() }, defaults)
3662

3763
// Consume function arguments
3864
if (typeof arg1 === 'string') {
@@ -75,22 +101,4 @@ export default class Consola {
75101
}
76102
return this
77103
}
78-
79-
add (reporter) {
80-
this.reporters.push(reporter)
81-
return this
82-
}
83-
84-
clear () {
85-
this.reporters.splice(0)
86-
return this
87-
}
88-
89-
remove (reporter) {
90-
const i = this.reporters.indexOf(reporter)
91-
if (i >= 0) {
92-
return this.reporters.splice(i, 1)
93-
}
94-
return this
95-
}
96104
}

0 commit comments

Comments
 (0)