UNPKG

@miuiu/postgrest

Version:
98 lines 3.3 kB
import PostgrestQueryBuilder from "./PostgrestQueryBuilder"; import PostgrestFilterBuilder from "./PostgrestFilterBuilder"; import { DEFAULT_HEADERS } from "./constants"; /** * PostgREST client. * * @typeParam Database - Types for the schema from the [type * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) * * @typeParam SchemaName - Postgres schema to switch to. Must be a string * literal, the same one passed to the constructor. If the schema is not * `"public"`, this must be supplied manually. */ export default class PostgrestClient { // TODO: Add back shouldThrowOnError once we figure out the typings /** * Creates a PostgREST client. * * @param url - URL of the PostgREST endpoint * @param options - Named parameters * @param options.headers - Custom headers */ constructor(url, { headers = {}, } = {}) { this.url = url; this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS), headers); } /** * Perform a query on a table or a view. * * @param relation - The table or view name to query */ from(relation) { let [schema, table] = relation.split("."); if (!table) { table = schema; schema = "public"; } const url = new URL(`${this.url}/${table}`); return new PostgrestQueryBuilder(url, { headers: Object.assign({}, this.headers), schema, }); } /** * Perform a function call. * * @param fn - The function name to call * @param args - The arguments to pass to the function call * @param options - Named parameters * @param options.head - When set to `true`, `data` will not be returned. * Useful if you only need the count. * @param options.count - Count algorithm to use to count rows returned by the * function. Only applicable for [set-returning * functions](https://www.postgresql.org/docs/current/functions-srf.html). * * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the * hood. * * `"planned"`: Approximated but fast count algorithm. Uses the Postgres * statistics under the hood. * * `"estimated"`: Uses exact count for low numbers and planned count for high * numbers. */ rpc(fn, args = {}, { head = false, count, } = {}) { let method; let [schema, fnname] = fn.split("."); if (!fnname) { fnname = schema; schema = "public"; } const url = new URL(`${this.url}/rpc/${fnname}`); let body; if (head) { method = "HEAD"; Object.entries(args).forEach(([name, value]) => { url.searchParams.append(name, `${value}`); }); } else { method = "POST"; body = args; } const headers = Object.assign({}, this.headers); if (count) { headers["Prefer"] = `count=${count}`; } return new PostgrestFilterBuilder({ method, url, headers, schema, body, allowEmpty: false, }); } } //# sourceMappingURL=PostgrestClient.js.map