convex
Version:
Client for the Convex Cloud
96 lines (95 loc) • 2.79 kB
JavaScript
;
import { convexToJson } from "../values/index.js";
export class QueriesObserver {
constructor(createWatch) {
this.createWatch = createWatch;
this.queries = {};
this.listeners = /* @__PURE__ */ new Set();
}
setQueries(newQueries) {
for (const identifier of Object.keys(newQueries)) {
const { name, args } = newQueries[identifier];
if (this.queries[identifier] === void 0) {
this.addQuery(identifier, name, args);
} else {
const existingInfo = this.queries[identifier];
if (name !== existingInfo.name || JSON.stringify(convexToJson(args)) !== JSON.stringify(convexToJson(existingInfo.args))) {
this.removeQuery(identifier);
this.addQuery(identifier, name, args);
}
}
}
for (const identifier of Object.keys(this.queries)) {
if (newQueries[identifier] === void 0) {
this.removeQuery(identifier);
}
}
}
subscribe(listener) {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
getCurrentQueries() {
const result = {};
for (const identifier of Object.keys(this.queries)) {
let value;
try {
value = this.queries[identifier].watch.localQueryResult();
} catch (e) {
if (e instanceof Error) {
value = e;
} else {
throw e;
}
}
result[identifier] = value;
}
return result;
}
setCreateWatch(createWatch) {
this.createWatch = createWatch;
for (const identifier of Object.keys(this.queries)) {
const { name, args, watch } = this.queries[identifier];
const journal = watch.journal();
this.removeQuery(identifier);
this.addQuery(identifier, name, args, journal);
}
}
destroy() {
for (const identifier of Object.keys(this.queries)) {
this.removeQuery(identifier);
}
this.listeners = /* @__PURE__ */ new Set();
}
addQuery(identifier, name, args, journal) {
if (this.queries[identifier] !== void 0) {
throw new Error(
`Tried to add a new query with identifier ${identifier} when it already exists.`
);
}
const watch = this.createWatch(name, args, journal);
const unsubscribe = watch.onUpdate(() => this.notifyListeners());
this.queries[identifier] = {
name,
args,
watch,
unsubscribe
};
}
removeQuery(identifier) {
const info = this.queries[identifier];
if (info === void 0) {
throw new Error(`No query found with identifier ${identifier}.`);
}
info.unsubscribe();
delete this.queries[identifier];
}
notifyListeners() {
for (const listener of this.listeners) {
listener();
}
}
}
//# sourceMappingURL=queries_observer.js.map