Support receiving messages in Sandy plugins

Summary: This diffs adds the capability to listen to messages in Sandy plugins. Although API wise it looks more like the old `this.subscribe`, semantically it behaves like the `persistedStateReducer`; messages are queued if the plugin is enabled but not active.

Reviewed By: nikoant

Differential Revision: D22282711

fbshipit-source-id: 885faa702fe779ac8d593c1d224b2be13e688d47
This commit is contained in:
Michel Weststrate
2020-07-01 08:58:40 -07:00
committed by Facebook GitHub Bot
parent 6c79408b0f
commit bb0c8e0df0
8 changed files with 841 additions and 59 deletions

View File

@@ -13,6 +13,11 @@ import {EventEmitter} from 'events';
type EventsContract = Record<string, any>;
type MethodsContract = Record<string, (params: any) => Promise<any>>;
type Message = {
method: string;
params?: any;
};
/**
* API available to a plugin factory
*/
@@ -47,6 +52,17 @@ export interface FlipperClient<
method: Method,
params: Parameters<Methods[Method]>[0],
): ReturnType<Methods[Method]>;
/**
* Subscribe to a specific event arriving from the device.
*
* Messages can only arrive if the plugin is enabled and connected.
* For background plugins messages will be batched and arrive the next time the plugin is connected.
*/
onMessage<Event extends keyof Events>(
event: Event,
callback: (params: Events[Event]) => void,
): void;
}
/**
@@ -73,6 +89,10 @@ export type FlipperPluginFactory<
export type FlipperPluginComponent = React.FC<{}>;
export class SandyPluginInstance {
static is(thing: any): thing is SandyPluginInstance {
return thing instanceof SandyPluginInstance;
}
/** base client provided by Flipper */
realClient: RealFlipperClient;
/** client that is bound to this instance */
@@ -111,6 +131,9 @@ export class SandyPluginInstance {
params as any,
);
},
onMessage: (event, callback) => {
this.events.on('event-' + event, callback);
},
};
this.instanceApi = definition.module.plugin(this.client);
}
@@ -156,6 +179,12 @@ export class SandyPluginInstance {
this.destroyed = true;
}
receiveMessages(messages: Message[]) {
messages.forEach((message) => {
this.events.emit('event-' + message.method, message.params);
});
}
toJSON() {
this.assertNotDestroyed();
// TODO: T68683449