Created
May 13, 2018 20:16
-
-
Save lukaszx0/7995b7559ae58eef3e418c7275ebf7ba to your computer and use it in GitHub Desktop.
proto-over-http
This file contains hidden or 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
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