Skip to content

Commit

Permalink
feat(dev-utils): support event helper
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jun 14, 2021
1 parent fdd9541 commit 3ce5fc7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
13 changes: 11 additions & 2 deletions packages/koishi-dev-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as K from 'koishi-core'

const map = new WeakMap<{}, K.Disposable[]>()
const map = new WeakMap<Object, ((this: K.Context) => void)[]>()

export interface PluginContext<T = any> extends K.Plugin.Object<T>, K.Context {}

Expand All @@ -26,11 +26,20 @@ export const Plugin = ((name) => (factory) => {

Object.assign(Plugin, K.Plugin)

type MethodDecorator<T> = (target: Object, key: string | symbol, desc: TypedPropertyDescriptor<T>) => void

export type Middleware = K.Middleware

export const Middleware: MethodDecorator = (target, key, desc) => {
export const Middleware: MethodDecorator<K.Middleware> = (target, key, desc) => {
if (!map.has(target)) map.set(target, [])
map.get(target).push(function() {
this.middleware(desc.value)
})
}

export const Event: <E extends keyof K.EventMap>(name: E, prepend?: boolean) => MethodDecorator<K.EventMap[E]> = (name, prepend) => (target, key, desc) => {
if (!map.has(target)) map.set(target, [])
map.get(target).push(function() {
this.on(name, desc.value, prepend)
})
}
21 changes: 18 additions & 3 deletions packages/koishi-dev-utils/tests/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import { Session } from 'koishi-core'
import { NextFunction, Session } from 'koishi-core'
import { App } from 'koishi-test-utils'
import { Plugin, PluginContext, Middleware } from 'koishi-dev-utils'
import { Plugin, PluginContext, Middleware, Event } from 'koishi-dev-utils'
import { expect } from 'chai'
import jest from 'jest-mock'

describe('Plugin Context', () => {
const fn = jest.fn()

@Plugin('test-1')
class MyPlugin extends PluginContext {
@Middleware
hello(session: Session) {
hello(session: Session, next: NextFunction) {
session.send('hello!')
}

@Event('disconnect')
onDisconnect() {
fn()
}
}

const app = new App().plugin(new MyPlugin())
Expand All @@ -17,4 +26,10 @@ describe('Plugin Context', () => {
it('middleware', async () => {
await sess.shouldReply('say hello', 'hello!')
})

it('event', async () => {
expect(fn.mock.calls).to.have.length(0)
app.emit('disconnect')
expect(fn.mock.calls).to.have.length(1)
})
})

0 comments on commit 3ce5fc7

Please sign in to comment.