Skip to content

Commit

Permalink
fix(core): koishijs#630 cancelQueued (Breaking)
Browse files Browse the repository at this point in the history
  • Loading branch information
DrLee-lihr committed May 5, 2022
1 parent ecb28c4 commit 2e6e955
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions packages/core/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,9 @@ export class Session<U extends User.Field = never, G extends Channel.Field = nev
guild?: Channel.Observed<G>
parsed?: Parsed

private _delay?: number
private _queued: Promise<void>
private _hooks: (() => void)[]
private _hooks: NodeJS.Timeout[]
private _promise: Promise<string>
private _queuedMessages: [string, number][]

constructor(bot: Bot, session: Partial<Session.Payload>) {
Object.assign(this, session)
Expand All @@ -107,7 +106,7 @@ export class Session<U extends User.Field = never, G extends Channel.Field = nev
defineProperty(this, 'user', null)
defineProperty(this, 'channel', null)
defineProperty(this, 'id', Random.id())
defineProperty(this, '_queued', Promise.resolve())
defineProperty(this, '_queuedMessages', [])
defineProperty(this, '_hooks', [])
}

Expand Down Expand Up @@ -168,9 +167,22 @@ export class Session<U extends User.Field = never, G extends Channel.Field = nev
})
}

cancelQueued(delay = this.app.options.delay.cancel) {
this._hooks.forEach(Reflect.apply)
this._delay = delay
cancelQueued() {
this._hooks.forEach(clearTimeout)
this._queuedMessages = []
}

private _next() {
const message = this._queuedMessages.shift()
if (typeof message === 'undefined') return
remove(this._queuedMessages, message)
this.send(message[0])
this._hooks.push(
setTimeout(() => {
this._hooks.shift()
this._next()
}, message[1]),
)
}

async sendQueued(content: string, delay?: number) {
Expand All @@ -179,19 +191,8 @@ export class Session<U extends User.Field = never, G extends Channel.Field = nev
const { message, character } = this.app.options.delay
delay = Math.max(message, character * content.length)
}
return this._queued = this._queued.then(() => new Promise<void>((resolve) => {
const hook = () => {
resolve()
clearTimeout(timer)
remove(this._hooks, hook)
}
this._hooks.push(hook)
const timer = setTimeout(async () => {
await this.send(content)
this._delay = delay
hook()
}, this._delay || 0)
}))
this._queuedMessages.push([content, delay])
if (this._hooks.length === 0) this._next()
}

resolveValue<T>(source: T | ((session: Session) => T)): T {
Expand Down

0 comments on commit 2e6e955

Please sign in to comment.