Skip to content

Instantly share code, notes, and snippets.

@lukaszx0
Created May 13, 2018 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaszx0/7995b7559ae58eef3e418c7275ebf7ba to your computer and use it in GitHub Desktop.
Save lukaszx0/7995b7559ae58eef3e418c7275ebf7ba to your computer and use it in GitHub Desktop.
proto-over-http
function doFetch<ReqT extends { serializeBinary(): Uint8Array }, RespT>
(method: string, req: ReqT, respClass: { new(): RespT, deserializeBinary(bytes: Uint8Array): RespT }): Promise<RespT> {
const params: RequestInit = {
headers: {
"Accept": PROTO_CONTENT_TYPE,
"Content-Type": PROTO_CONTENT_TYPE,
},
method: "POST",
body: toArrayBuffer(req.serializeBinary()),
};
return fetch(`${API_ENDPOINT}/${method}`, params).then((res) => {
if (!res.ok) {
throw Error(res.statusText);
}
return res.arrayBuffer().then((buffer) => respClass.deserializeBinary(new Uint8Array(buffer)));
});
}
function toArrayBuffer(encodedRequest: Uint8Array): ArrayBuffer {
return encodedRequest.buffer.slice(encodedRequest.byteOffset, encodedRequest.byteOffset + encodedRequest.byteLength);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment