feat: add rest support
This commit is contained in:
@@ -1,16 +1,17 @@
|
||||
import type { RelayAdapter, RelayRequestInput, RelayResponse } from "../libraries/adapter.ts";
|
||||
import type { RelayAdapter, RelayRESTInput } from "../libraries/adapter.ts";
|
||||
import { RelayError, UnprocessableContentError } from "../libraries/errors.ts";
|
||||
import { RelayProcedureInput, RelayProcedureResponse } from "../mod.ts";
|
||||
|
||||
export class HttpAdapter implements RelayAdapter {
|
||||
#id: number = 0;
|
||||
|
||||
constructor(readonly url: string) {}
|
||||
|
||||
async send({ method, params }: RelayRequestInput): Promise<RelayResponse> {
|
||||
async send({ method, params }: RelayProcedureInput): Promise<RelayProcedureResponse> {
|
||||
const id = this.#id++;
|
||||
const res = await fetch(this.url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
headers: { "x-relay-type": "rpc", "content-type": "application/json" },
|
||||
body: JSON.stringify({ relay: "1.0", method, params, id }),
|
||||
});
|
||||
const contentType = res.headers.get("content-type");
|
||||
@@ -31,4 +32,20 @@ export class HttpAdapter implements RelayAdapter {
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
async fetch({ method, url, query, body }: RelayRESTInput) {
|
||||
const res = await fetch(`${url}${query}`, {
|
||||
method,
|
||||
headers: { "x-relay-type": "rest", "content-type": "application/json" },
|
||||
body,
|
||||
});
|
||||
const data = await res.text();
|
||||
if (res.status >= 400) {
|
||||
throw new Error(data);
|
||||
}
|
||||
if (res.headers.get("content-type")?.includes("json")) {
|
||||
return JSON.parse(data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user