microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/common/extensionMessaging.ts
66lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import * as Q from "q"; |
| 5 | import * as http from "http"; |
| 6 | |
| 7 | /** |
| 8 | * Message server parameters. |
| 9 | */ |
| 10 | export let ServerDefaultParams = { |
| 11 | PORT: 8099, |
| 12 | HOST: "127.0.0.1" |
| 13 | }; |
| 14 | |
| 15 | /** |
| 16 | * Defines the messages sent to the extension. |
| 17 | * Add new messages to this enum. |
| 18 | */ |
| 19 | export enum ExtensionMessage { |
| 20 | START_PACKAGER, |
| 21 | STOP_PACKAGER, |
| 22 | PREWARM_BUNDLE_CACHE |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Sends messages to the extension. |
| 27 | */ |
| 28 | export class ExtensionMessageSender { |
| 29 | |
| 30 | public sendMessage(message: ExtensionMessage, args?: any[], port?: number): Q.Promise<any> { |
| 31 | let deferred = Q.defer<any>(); |
| 32 | |
| 33 | let options = { |
| 34 | host: ServerDefaultParams.HOST, |
| 35 | port: port || ServerDefaultParams.PORT, |
| 36 | path: "/" + ExtensionMessage[message], |
| 37 | method: "POST", |
| 38 | headers: { "Content-Type": "application/json" } |
| 39 | }; |
| 40 | |
| 41 | let responseCallback = (response: http.IncomingMessage) => { |
| 42 | let body = ""; |
| 43 | |
| 44 | response.on("data", function(data: any) { |
| 45 | body += data; |
| 46 | }); |
| 47 | |
| 48 | response.on("end", function() { |
| 49 | try { |
| 50 | let responseBody: any = body ? JSON.parse(body) : null; |
| 51 | deferred.resolve(responseBody); |
| 52 | } catch (e) { |
| 53 | deferred.reject(e); |
| 54 | } |
| 55 | }); |
| 56 | }; |
| 57 | |
| 58 | let postRequest = http.request(options, responseCallback); |
| 59 | if (args) { |
| 60 | postRequest.write(JSON.stringify(args)); |
| 61 | } |
| 62 | postRequest.end(); |
| 63 | |
| 64 | return deferred.promise; |
| 65 | } |
| 66 | } |