UNPKG

rxdb-server

Version:
70 lines 2.83 kB
import { postRequest } from "./utils.js"; import { Subject } from 'rxjs'; import { EventSource } from 'eventsource'; import { customFetchWithFixedHeaders } from "../../utils.js"; export var RxRestClient = /*#__PURE__*/function () { function RxRestClient(endpointUrl, headers = {}, eventSource = EventSource) { this.endpointUrl = endpointUrl; this.headers = headers; this.eventSource = eventSource; } var _proto = RxRestClient.prototype; _proto.setHeaders = function setHeaders(headers) { this.headers = headers; }; _proto.handleError = function handleError(response) { if (response.error) { throw new Error('Server returned an error ' + JSON.stringify(response)); } }; _proto.query = async function query(_query) { var response = await postRequest(this.endpointUrl + '/query', _query, this.headers); this.handleError(response); return response; }; _proto.observeQuery = function observeQuery(query) { var result = new Subject(); // Standard base64 uses '+' and '/'; both are URL-reserved and a raw // '+' in the query string is decoded as a space by the server's // URL parser. Without encoding, the server's atob() then rejects // the corrupted string with "Invalid character" and the SSE // connection silently never delivers any document. var queryAsBase64 = encodeURIComponent(btoa(JSON.stringify(query))); var eventSource = new this.eventSource(this.endpointUrl + '/query/observe?query=' + queryAsBase64, { withCredentials: true, /** * Sending headers is not supported by the Browser EventSource API, * only by the npm module we use. In react-native you might have * to set another EventSource implementation. * @link https://www.npmjs.com/package/eventsource */ fetch: customFetchWithFixedHeaders(this.headers) }); eventSource.onmessage = event => { var eventData = JSON.parse(event.data); result.next(eventData); }; return result.asObservable(); }; _proto.get = async function get(ids) { var response = await postRequest(this.endpointUrl + '/get', ids, this.headers); this.handleError(response); return response; }; _proto.set = async function set(docs) { var response = await postRequest(this.endpointUrl + '/set', docs, this.headers); this.handleError(response); return response; }; _proto.delete = async function _delete(ids) { var response = await postRequest(this.endpointUrl + '/delete', ids, this.headers); this.handleError(response); return response; }; return RxRestClient; }(); export function createRestClient(endpointUrl, headers, eventSource = EventSource) { return new RxRestClient(endpointUrl, headers, eventSource); } export * from "./utils.js"; //# sourceMappingURL=index.js.map