Created
April 4, 2018 15:22
-
-
Save lukaszx0/157e81a4b0ca803c5117161dc19c350e to your computer and use it in GitHub Desktop.
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
import * as protos from "./protos"; | |
import pb = protos.exemplar; | |
const HOST = "https://localhost:1234"; | |
const PROTO_CONTENT_TYPE = "application/x-protobuf"; | |
interface ResponseMessageBuilder<PropT, RespT> { | |
new(properties?: PropT): RespT; | |
encode(message: PropT, writer?: protobuf.Writer): protobuf.Writer; | |
decode(reader: (protobuf.Reader | Uint8Array), length?: number): RespT; | |
} | |
enum HttpMethod { | |
GET, | |
POST, | |
PUT, | |
DELETE, | |
} | |
function doFetch<RespPropsT, RespT, RespBuilderT extends ResponseMessageBuilder<RespPropsT, RespT>, ReqT> | |
(url: string, builder: RespBuilderT, method: HttpMethod = HttpMethod.GET, req?: ReqT): | |
Promise<RespT> { | |
const params: RequestInit = { | |
headers: { | |
"Accept": PROTO_CONTENT_TYPE, | |
"Content-Type": PROTO_CONTENT_TYPE, | |
}, | |
}; | |
if (method != HttpMethod.GET) { | |
const encodedRequest = req.constructor().encode(req).finish(); | |
params.method = "POST"; | |
params.body = toArrayBuffer(encodedRequest); | |
} | |
return fetch(`${HOST}${url}`, params).then((res) => { | |
if (!res.ok) { | |
throw Error(res.statusText); | |
} | |
return res.arrayBuffer().then((buffer) => builder.decode(new Uint8Array(buffer))); | |
}); | |
} | |
function toArrayBuffer(encodedRequest: Uint8Array): ArrayBuffer { | |
return encodedRequest.buffer.slice(encodedRequest.byteOffset, encodedRequest.byteOffset + encodedRequest.byteLength); | |
} | |
// Endpoint wrapper | |
export function getTodos(): Promise<pb.GetTodosResponse> { | |
return doFetch(`/api/todos`, pb.GetTodosResponse); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment