Skip to content

Commit

Permalink
refa: migrate ctx symbol to service.ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jun 17, 2024
1 parent ebaeded commit b005e94
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
15 changes: 7 additions & 8 deletions packages/timer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class TimerService extends Service {
}

setTimeout(callback: () => void, delay: number) {
const dispose = this[Context.origin].effect(() => {
const dispose = this.ctx.effect(() => {
const timer = setTimeout(() => {
dispose()
callback()
Expand All @@ -32,14 +32,14 @@ export class TimerService extends Service {
}

setInterval(callback: () => void, delay: number) {
return this[Context.origin].effect(() => {
return this.ctx.effect(() => {
const timer = setInterval(callback, delay)
return () => clearInterval(timer)
})
}

sleep(delay: number) {
const caller = this[Context.origin]
const caller = this.ctx
return new Promise<void>((resolve, reject) => {
const dispose1 = this.setTimeout(() => {
dispose1()
Expand All @@ -55,22 +55,21 @@ export class TimerService extends Service {
}

private createWrapper(callback: (args: any[], check: () => boolean) => any, isDisposed = false) {
const caller = this[Context.origin]
caller.scope.assertActive()
this.ctx.scope.assertActive()

let timer: number | NodeJS.Timeout | undefined
const dispose = () => {
isDisposed = true
remove(caller.scope.disposables, dispose)
remove(this.ctx.scope.disposables, dispose)
clearTimeout(timer)
}

const wrapper: any = (...args: any[]) => {
clearTimeout(timer)
timer = callback(args, () => !isDisposed && caller.scope.isActive)
timer = callback(args, () => !isDisposed && this.ctx.scope.isActive)
}
wrapper.dispose = dispose
caller.scope.disposables.push(dispose)
this.ctx.scope.disposables.push(dispose)
return wrapper
}

Expand Down
8 changes: 3 additions & 5 deletions packages/timer/tests/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { mock } from 'node:test'
import { FakeTimerInstallOpts, install, InstalledClock } from '@sinonjs/fake-timers'
import { Context } from 'cordis'
import { Context } from '@cordisjs/core'
import assert from 'node:assert'
import Timer from '../src'

declare module 'cordis' {
declare module '@cordisjs/core' {
interface Context {
clock: InstalledClock
}
Expand All @@ -15,9 +15,7 @@ function withContext(callback: (ctx: Context) => Promise<void>, config?: FakeTim
const ctx = new Context()
ctx.clock = install(config)
ctx.plugin(Timer)
ctx.plugin(() => {
callback(ctx).then(resolve, reject).finally(() => ctx.clock.uninstall())
})
callback(ctx).then(resolve, reject).finally(() => ctx.clock.uninstall())
})
}

Expand Down

0 comments on commit b005e94

Please sign in to comment.