Add FlipperServerClient to headless tic-tac-toe

Summary: FlipperServerClient is a high-level abstraction to talk to Flipper Server

Reviewed By: passy

Differential Revision: D36545544

fbshipit-source-id: 12845a96dfc39d4268d2f7134d90d5addae48b83
This commit is contained in:
Andrey Goncharov
2022-05-23 08:06:18 -07:00
committed by Facebook GitHub Bot
parent 77ada56e02
commit 9bd66e6188
5 changed files with 122 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
module.exports.ticTacToePluginId = 'ReactNativeTicTacToe';
module.exports.player = 'O';

View File

@@ -0,0 +1,77 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const WebSocket = require('ws');
const EventEmitter = require('events');
class FlipperServerClient {
messageId = 0;
wsClient = new WebSocket('ws://localhost:52342?server_companion=true');
execReqs = new Map();
eventBus = new EventEmitter();
async init() {
await new Promise((resolve) => this.wsClient.on('open', resolve));
this.wsClient.on('message', (data) => {
const {event, payload} = JSON.parse(data);
switch (event) {
case 'exec-response':
case 'exec-response-error': {
const req = this.execReqs.get(payload.id);
if (!req) {
console.warn('Unknown exec request');
return;
}
this.execReqs.delete(payload.id);
if (event === 'exec-response') {
req.resolve(payload.data);
} else {
req.reject(payload.data);
}
return;
}
case 'companion-event': {
this.eventBus.emit(payload.event, payload.data);
}
}
});
}
exec(command, args) {
return new Promise((resolve, reject) => {
const id = this.messageId++;
this.wsClient.send(
JSON.stringify({
event: 'exec',
payload: {
id,
command,
args,
},
}),
);
this.execReqs.set(id, {resolve, reject});
});
}
on(eventName, cb) {
this.eventBus.on(eventName, cb);
}
}
module.exports = {
FlipperServerClient,
};

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const main = async () => {
// TODO: Implement me
};
main().catch(console.error);

View File

@@ -0,0 +1,12 @@
{
"name": "flipper-headless-tic-tac-toe",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"ws": "^8.6.0"
}
}

View File

@@ -0,0 +1,8 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
ws@^8.6.0:
version "8.6.0"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.6.0.tgz#e5e9f1d9e7ff88083d0c0dd8281ea662a42c9c23"
integrity sha512-AzmM3aH3gk0aX7/rZLYvjdvZooofDu3fFOzGqcSnQ1tOcTWwhM/o+q++E8mAyVVIyUdajrkzWUGftaVSDLn1bw==