-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(middleware): api desgin draft #2293
Open
Gcaufy
wants to merge
2
commits into
main
Choose a base branch
from
feat-middleware
base: main
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# Examples | ||
|
||
1. How to define a middleware | ||
``` | ||
// 抽象通过能力为中间件,由中间件控制事件响应 | ||
const filterMiddleWare = (options) { | ||
return async (message, next) => { | ||
|
||
const room = message.room() | ||
|
||
if (!room) return | ||
if (message.type() !== option.type) return | ||
if (!matchers.roomMatcher(option.room)) return | ||
|
||
await next(); | ||
} | ||
} | ||
``` | ||
|
||
2. Add middleware to specified event | ||
``` | ||
// Only room a print `banana` | ||
bot.on('message', | ||
filterMiddlerWare({ type: type.Message.Text, room: 'room a'}), | ||
(message) => console.log('banana') | ||
); | ||
|
||
// All rooms print `apple` | ||
bot.on('message', | ||
(message) => console.log('apple') | ||
); | ||
``` | ||
|
||
3. Add global middleware | ||
``` | ||
WechatyImpl.middleware({ | ||
message: filterMiddleWare({ type.Message.Text, room: [ 'room-d', 'room-e' ]}) | ||
}) | ||
|
||
// Only room-d, room-e print apple. | ||
bot.on('message', | ||
(message) => console.log('apple') | ||
); | ||
|
||
// only room-d, room-e print orange(50% probability) | ||
bot.on('message', async (message, next) => { | ||
if (Math.random() < 0.5) { | ||
await next(); | ||
} | ||
}, (message) => console.log('orange')) | ||
``` | ||
|
||
4. Work with plugins | ||
``` | ||
WechatyImpl.middleware({ | ||
message: filterMiddleWare({ type.Message.Text, room: [ 'room-d', 'room-e' ]}) | ||
}) | ||
|
||
// Only room-d, room-e has kickoff feature | ||
WechatyImpl.use(KickOffPlugin(options)); | ||
|
||
|
||
// TODO: use support rest params, so we need to think about how design it. | ||
// WechatyImpl.use({ message: someMiddleWare() }, KickOffPlugin(options)); | ||
``` | ||
|
||
5. Work in plugins | ||
``` | ||
const onMessage = (message) => { | ||
// plugin logic | ||
} | ||
export MyPlugin = (bot: WechatyInterface) => { | ||
bot.on('message', [ | ||
MiddleWareA(), | ||
MiddleWareB(), | ||
MiddleWareC(), | ||
], onMessage) | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
const noop = (x: any) => x | ||
// TODO: finish the middleware compose logic | ||
export const compose = function (middlewares: any[]) { | ||
noop(middlewares) | ||
return (...args: any) => { | ||
noop(args) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
/** | ||
* Wechaty MiddleWare Interfaces | ||
*/ | ||
|
||
import type { | ||
WechatyEventListenerDong, | ||
WechatyEventListenerError, | ||
WechatyEventListenerFriendship, | ||
WechatyEventListenerHeartbeat, | ||
WechatyEventListenerLogin, | ||
WechatyEventListenerLogout, | ||
WechatyEventListenerMessage, | ||
WechatyEventListenerPuppet, | ||
WechatyEventListenerReady, | ||
WechatyEventListenerRoomInvite, | ||
WechatyEventListenerRoomJoin, | ||
WechatyEventListenerRoomLeave, | ||
WechatyEventListenerRoomTopic, | ||
WechatyEventListeners, | ||
WechatyEventListenerScan, | ||
WechatyEventListenerStartStop, | ||
} from '../events/wechaty-events.js' | ||
|
||
type AddFunctionParameters< | ||
TFunction extends (...args: any) => any, | ||
TParameters extends [...args: any] | ||
> = ( | ||
...args: [...Parameters<TFunction>, ...TParameters] | ||
) => ReturnType<TFunction>; | ||
|
||
type WechatyMiddleWareDong = AddFunctionParameters<WechatyEventListenerDong, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareError = AddFunctionParameters<WechatyEventListenerError, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareFriendship = AddFunctionParameters<WechatyEventListenerFriendship, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareHeartbeat = AddFunctionParameters<WechatyEventListenerHeartbeat, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareLogin = AddFunctionParameters<WechatyEventListenerLogin, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareLogout = AddFunctionParameters<WechatyEventListenerLogout, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareMessage = AddFunctionParameters<WechatyEventListenerMessage, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWarePuppet = AddFunctionParameters<WechatyEventListenerPuppet, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareReady = AddFunctionParameters<WechatyEventListenerReady, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareRoomInvite = AddFunctionParameters<WechatyEventListenerRoomInvite, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareRoomJoin = AddFunctionParameters<WechatyEventListenerRoomJoin, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareRoomLeave = AddFunctionParameters<WechatyEventListenerRoomLeave, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareRoomTopic = AddFunctionParameters<WechatyEventListenerRoomTopic, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareScan = AddFunctionParameters<WechatyEventListenerScan, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
type WechatyMiddleWareStartStop = AddFunctionParameters<WechatyEventListenerStartStop, [ next: () => void | Promise<void> ]> & { eventType?: keyof WechatyEventListeners}; | ||
|
||
interface WechatyMiddleWares { | ||
'room-invite' : WechatyMiddleWareRoomInvite | ||
'room-join' : WechatyMiddleWareRoomJoin | ||
'room-leave' : WechatyMiddleWareRoomLeave | ||
'room-topic' : WechatyMiddleWareRoomTopic | ||
dong : WechatyMiddleWareDong | ||
error : WechatyMiddleWareError | ||
friendship : WechatyMiddleWareFriendship | ||
heartbeat : WechatyMiddleWareHeartbeat | ||
login : WechatyMiddleWareLogin | ||
logout : WechatyMiddleWareLogout | ||
message : WechatyMiddleWareMessage | ||
puppet : WechatyMiddleWarePuppet | ||
ready : WechatyMiddleWareReady | ||
scan : WechatyMiddleWareScan | ||
start : WechatyMiddleWareStartStop | ||
stop : WechatyMiddleWareStartStop | ||
} | ||
|
||
export interface TypedMiddleWareEventEmitter<Events, MiddleWares> { | ||
on<E extends (keyof Events & keyof MiddleWares)> (event: E, middleware: MiddleWares[E] | MiddleWares[E][], listener: Events[E]): this | ||
} | ||
|
||
export type { | ||
WechatyMiddleWares, | ||
WechatyMiddleWareDong, | ||
WechatyMiddleWareError, | ||
WechatyMiddleWareFriendship, | ||
WechatyMiddleWareHeartbeat, | ||
WechatyMiddleWareLogin, | ||
WechatyMiddleWareLogout, | ||
WechatyMiddleWareMessage, | ||
WechatyMiddleWarePuppet, | ||
WechatyMiddleWareReady, | ||
WechatyMiddleWareRoomInvite, | ||
WechatyMiddleWareRoomJoin, | ||
WechatyMiddleWareRoomLeave, | ||
WechatyMiddleWareRoomTopic, | ||
WechatyMiddleWareScan, | ||
WechatyMiddleWareStartStop, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import { log } from 'wechaty-puppet' | ||
import type { WechatyConstructor } from '../interface/wechaty-interface.js' | ||
import type { WechatySkelton } from './wechaty-skelton.js' | ||
|
||
import type { | ||
WechatyMiddleWareDong, | ||
WechatyMiddleWareError, | ||
WechatyMiddleWareFriendship, | ||
WechatyMiddleWareHeartbeat, | ||
WechatyMiddleWareLogin, | ||
WechatyMiddleWareLogout, | ||
WechatyMiddleWareMessage, | ||
WechatyMiddleWarePuppet, | ||
WechatyMiddleWareReady, | ||
WechatyMiddleWareRoomInvite, | ||
WechatyMiddleWareRoomJoin, | ||
WechatyMiddleWareRoomLeave, | ||
WechatyMiddleWareRoomTopic, | ||
WechatyMiddleWares, | ||
WechatyMiddleWareScan, | ||
WechatyMiddleWareStartStop, | ||
} from '../middlewares/wechaty-middlewares.js' | ||
|
||
type TOrArrayT<T> = T | T[] | ||
|
||
interface WechatyGlobalMiddleWares { | ||
'room-invite'? : TOrArrayT<WechatyMiddleWareRoomInvite> | ||
'room-join'? : TOrArrayT<WechatyMiddleWareRoomJoin> | ||
'room-leave'? : TOrArrayT<WechatyMiddleWareRoomLeave> | ||
'room-topic'? : TOrArrayT<WechatyMiddleWareRoomTopic> | ||
dong? : TOrArrayT<WechatyMiddleWareDong> | ||
error? : TOrArrayT<WechatyMiddleWareError> | ||
friendship? : TOrArrayT<WechatyMiddleWareFriendship> | ||
heartbeat? : TOrArrayT<WechatyMiddleWareHeartbeat> | ||
login? : TOrArrayT<WechatyMiddleWareLogin> | ||
logout? : TOrArrayT<WechatyMiddleWareLogout> | ||
message? : TOrArrayT<WechatyMiddleWareMessage> | ||
puppet? : TOrArrayT<WechatyMiddleWarePuppet> | ||
ready? : TOrArrayT<WechatyMiddleWareReady> | ||
scan? : TOrArrayT<WechatyMiddleWareScan> | ||
start? : TOrArrayT<WechatyMiddleWareStartStop> | ||
stop? : TOrArrayT<WechatyMiddleWareStartStop> | ||
} | ||
|
||
const middleWareMixin = <MixinBase extends typeof WechatySkelton> (mixinBase: MixinBase) => { | ||
log.verbose('WechatyMiddleWareMixin', 'middlewareMixin(%s)', mixinBase.name) | ||
|
||
abstract class MiddleWareMixin extends mixinBase { | ||
|
||
static _globalMiddleWares: WechatyGlobalMiddleWares = {} | ||
|
||
/** | ||
* @param {WechatyGlobalMiddleWare[]} middlewares - The global middlewares you want to use | ||
* | ||
* @return {WechatyInterface} - this for chaining, | ||
* | ||
* @desc | ||
* For wechaty ecosystem, allow user to define a 3rd party middleware for the all wechaty instances | ||
* | ||
* @example | ||
* | ||
* // Random catch all chat message. | ||
* | ||
* function RandomMessageMiddleWare(options: { rate: number}) { | ||
* return function (this: Wechaty, message: Message, next: async () => void | Promise<void>) { | ||
* if (Math.random() > options.rate) { | ||
* await next(); | ||
* } | ||
* } | ||
* } | ||
* | ||
* wechaty.middleware({ | ||
* message: RandomMessageMiddleWare({ rate: 0.5 }), | ||
* }) | ||
* | ||
* bot.on('message', async (message: Message) => { | ||
* await message.say('Bingo'); | ||
* }) | ||
*/ | ||
|
||
// TODO: I prefer `use` for middlewares, and `install` for plugins. But it's an incompatible API change. so that we can use middleware instead. | ||
static middleware ( | ||
middleware: WechatyGlobalMiddleWares | WechatyMiddleWares[keyof WechatyMiddleWares], | ||
): WechatyConstructor { | ||
if (typeof middleware === 'function') { | ||
middleware = middleware as WechatyMiddleWares[keyof WechatyMiddleWares] | ||
if (!middleware.eventType) { | ||
throw new Error('middleware eventType is not defined') | ||
} | ||
this._globalMiddleWares[middleware.eventType] = middleware | ||
} else { | ||
Object.keys(middleware).forEach(item => { | ||
this._globalMiddleWares[item] = middleware[item] | ||
}) | ||
} | ||
// Huan(202110): TODO: remove any | ||
return this as any | ||
} | ||
|
||
} | ||
|
||
return MiddleWareMixin | ||
} | ||
|
||
type MiddleWareMixin = ReturnType<typeof middleWareMixin> | ||
|
||
export type { | ||
WechatyGlobalMiddleWares, | ||
MiddleWareMixin, | ||
} | ||
export { | ||
middleWareMixin, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems that we can hard code the
next: () => void | Promise<void>
at here to replaceTParameters
?