Last active
February 1, 2016 00:13
-
-
Save krisselden/0abd82beae696a0efec6 to your computer and use it in GitHub Desktop.
Event Promise
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
import { EventEmitter } from "events"; | |
export default function eventPromise<T>(emitter: EventEmitter, resolveEvent: string, rejectEvent: string): Promise<T> { | |
return new Promise<T>((resolve, reject) => { | |
let resolveHandler = (evt) => { | |
resolve(evt); | |
emitter.removeListener(resolveEvent, resolveHandler); | |
emitter.removeListener(rejectEvent, rejectHandler); | |
} | |
let rejectHandler = (evt) => { | |
reject(evt); | |
emitter.removeListener(resolveEvent, resolveHandler); | |
emitter.removeListener(rejectEvent, rejectHandler); | |
} | |
emitter.on(resolveEvent, resolveHandler); | |
emitter.on(rejectEvent, rejectHandler); | |
}); | |
} |
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
import * as http from "http"; | |
import * as WebSocket from "ws"; | |
import eventPromise from "./event-promise"; | |
export async function openWebSocket(url: string): Promise<WebSocket> { | |
let ws = new WebSocket(url); | |
return eventPromise(ws, "open", "error").then(() => ws); | |
} | |
export async function getResponse(options: any): Promise<http.IncomingMessage> { | |
let request = http.get(options); | |
return eventPromise<http.IncomingMessage>(request, "response", "error"); | |
} | |
export async function readResponseBody(response: http.IncomingMessage): Promise<string> { | |
let body = ""; | |
response.setEncoding("utf8"); | |
response.on("data", (chunk) => { | |
body += chunk; | |
}); | |
return eventPromise(response, "end", "error").then(() => body); | |
} | |
class ResponseError extends Error { | |
status: number; | |
constructor(message: string, status: number) { | |
super(message); | |
this.status = status; | |
} | |
} | |
export async function get(options: any): Promise<string> { | |
let response = await getResponse(options); | |
let status = response.statusCode; | |
let body = await readResponseBody(response); | |
if (status !== 200) { | |
throw new ResponseError(body, status); | |
} | |
return body; | |
} | |
export async function getJSON<T>(options: any): Promise<T> { | |
let body = await get(options); | |
return JSON.parse(body); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An utility function for creating a promise of an event with example code that it cleans up.