microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/common/extensionMessaging.ts
68lines · 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 ServerParams = { |
| 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 ExtensionIncomingMessage { |
| 20 | START_PACKAGER, |
| 21 | STOP_PACKAGER |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Generic interface for messages with arguments. |
| 26 | */ |
| 27 | export interface MessageWithArgs<T> { |
| 28 | message: T; |
| 29 | args?: any[]; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Sends messages to the extension. |
| 34 | */ |
| 35 | export class ExtensionMessageSender { |
| 36 | |
| 37 | public sendMessage(message: MessageWithArgs<ExtensionIncomingMessage>): Q.Promise<any> { |
| 38 | let deferred = Q.defer<any>(); |
| 39 | |
| 40 | let options = { |
| 41 | host: ServerParams.HOST, |
| 42 | port: ServerParams.PORT, |
| 43 | path: "/", |
| 44 | method: "POST", |
| 45 | headers: { "Content-Type": "application/json" } |
| 46 | }; |
| 47 | |
| 48 | let responseCallback = (response: http.IncomingMessage) => { |
| 49 | let body = ""; |
| 50 | |
| 51 | response.on("data", function(data: any) { |
| 52 | body += data; |
| 53 | }); |
| 54 | |
| 55 | response.on("end", function() { |
| 56 | let responseBody: any = JSON.parse(body); |
| 57 | console.log("Response: " + body); |
| 58 | deferred.resolve(responseBody); |
| 59 | }); |
| 60 | }; |
| 61 | |
| 62 | let postRequest = http.request(options, responseCallback); |
| 63 | postRequest.write(JSON.stringify(message)); |
| 64 | postRequest.end(); |
| 65 | |
| 66 | return deferred.promise; |
| 67 | } |
| 68 | } |