-
Notifications
You must be signed in to change notification settings - Fork 10
/
middeware.ts
103 lines (83 loc) · 2.21 KB
/
middeware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { Arguments } from "yargs"
import chalk from "chalk"
export function LoggerMiddleware(argv: Arguments) {
const isCLI = argv.commandline as boolean
let logger: BaseLogger
if (isCLI) {
logger = new CommandlineLogger(console.log)
} else {
if (!argv.respond) {
throw new Error(`BotLogger Error: should pass \`respond()\` property into argv context`)
} else {
// @ts-ignore
logger = new BotLogger(argv.respond)
}
}
argv.logger = logger
}
type logFn = (str: string) => void
export class BaseLogger {
readonly _logFn: logFn
constructor(fn: logFn) {
if (!fn) {
throw new Error(`BaseLogger: required logFn when initialize`)
}
this._logFn = fn
}
formatTitle(title: string) {
return title
}
formatProperty(key: string, value: any) {
return `- ${key}: ${value}`
}
formatInfo(msg: any) {
return msg
}
formatError(msg: any) {
return `\nERROR! "${msg}"\n`
}
info() {
// NOTE: add this functionality if needed
}
error() {
// NOTE: add this functionality if needed
}
warning() {
// NOTE: add this functionality if needed
}
log = (str: string) => {
this._logFn(str)
}
}
export class BotLogger extends BaseLogger {
// NOTE: add any customization for BotLogger here
private bufferedStr: string = ''
log = (str: string = '') => {
// NOTE: use empty string as the termination character to send message
if (str !== '') {
this.bufferedStr += `${str}\n`
} else {
this._logFn(
`\`\`\`${this.bufferedStr}\`\`\``
)
this.bufferedStr = ''
}
}
logLine = (str: string = '') => {
this._logFn(str)
}
}
class CommandlineLogger extends BaseLogger {
formatTitle(title: string) {
return chalk.green(title)
}
formatProperty(key: string, value: any) {
return chalk.yellow(`- ${key}: `) + `${value}`
}
formatInfo(msg: any) {
return chalk.yellow(msg)
}
formatError(msg: any) {
return chalk.red(`\nERROR! "${msg}"\n`)
}
}