Skip to content

Commit

Permalink
Allow vars in HTTP query method (#148)
Browse files Browse the repository at this point in the history
  • Loading branch information
kearfy authored Jul 20, 2023
1 parent c3567a1 commit fa9cb26
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 49 deletions.
71 changes: 41 additions & 30 deletions src/library/SurrealHTTP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ export class SurrealHTTP<TFetcher = typeof fetch> {
private _database?: string;
private fetch: TFetcher;

constructor(url: string, {
fetcher,
}: {
fetcher?: TFetcher;
} = {}) {
this.fetch = fetcher ?? fetch as TFetcher;
constructor(
url: string,
{
fetcher,
}: {
fetcher?: TFetcher;
} = {},
) {
this.fetch = fetcher ?? (fetch as TFetcher);
this.url = processUrl(url, {
ws: "http",
wss: "https",
Expand Down Expand Up @@ -49,32 +52,40 @@ export class SurrealHTTP<TFetcher = typeof fetch> {
return this._database;
}

async request<T = unknown>(path: string, options?: {
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
plainBody?: boolean;
body?: Record<string, unknown> | string;
}): Promise<T> {
async request<T = unknown>(
path: string,
options?: {
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
plainBody?: boolean;
body?: Record<string, unknown> | string;
searchParams?: URLSearchParams;
},
): Promise<T> {
path = path.startsWith("/") ? path.slice(1) : path;
if (!this.ready()) throw new NoConnectionDetails();
return (await (this.fetch as typeof fetch)(
`${this.url}/${path}`,
{
method: options?.method ?? "POST",
headers: {
"Content-Type": options?.plainBody
? "text/plain"
: "application/json",
"Accept": "application/json",
"NS": this._namespace!,
"DB": this._database!,
...(this.authorization
? { "Authorization": this.authorization }
: {}),
return (
await (this.fetch as typeof fetch)(
`${this.url}/${path}${
options?.searchParams ? `?${options?.searchParams}` : ""
}`,
{
method: options?.method ?? "POST",
headers: {
"Content-Type": options?.plainBody
? "text/plain"
: "application/json",
Accept: "application/json",
NS: this._namespace!,
DB: this._database!,
...(this.authorization
? { Authorization: this.authorization }
: {}),
},
body: typeof options?.body == "string"
? options?.body
: JSON.stringify(options?.body),
},
body: typeof options?.body == "string"
? options?.body
: JSON.stringify(options?.body),
},
)).json() as T;
)
).json() as T;
}
}
20 changes: 13 additions & 7 deletions src/strategies/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,18 +166,24 @@ export class HTTPStrategy<TFetcher = typeof fetch> implements Connection {
* @param query - Specifies the SurrealQL statements.
* @param vars - Assigns variables which can be used in the query.
*/
async query<T extends RawQueryResult[]>(query: string) {
if (arguments[1]) {
throw new Error(
"The query function in the HTTP strategy does not support data as the second argument.",
);
}

async query<T extends RawQueryResult[]>(
query: string,
vars?: Record<string, unknown>,
) {
await this.ready;
const res = await this.request<InvalidSQL | MapQueryResult<T>>("/sql", {
body: query,
plainBody: true,
method: "POST",
searchParams: vars &&
new URLSearchParams(
Object.fromEntries(
Object.entries(vars).map(([k, v]) => [
k,
typeof v == "object" ? JSON.stringify(v) : `${v}`,
]),
),
),
});

if ("information" in res) throw new Error(res.information);
Expand Down
18 changes: 6 additions & 12 deletions test/e2e/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,12 @@ export default async (db) => {
});

await test("Perform a custom advanced query", async (expect) => {
let groups =
db.strategy == "ws"
? await db.query(
"SELECT marketing, count() FROM type::table($tb) GROUP BY marketing",
{
tb: "person",
}
)
: // The HTTP protocol cannot accept variables, so needs to test different
await db.query(
"SELECT marketing, count() FROM person GROUP BY marketing"
);
let groups = await db.query(
"SELECT marketing, count() FROM type::table($tb) GROUP BY marketing",
{
tb: "person",
}
);

expect(groups[0].status).toBe("OK");
expect(groups[0].result).toEqualStringified([
Expand Down

0 comments on commit fa9cb26

Please sign in to comment.