convex
Version:
Client for the Convex Cloud
97 lines (89 loc) • 2.9 kB
text/typescript
import { jsonToConvex, Value } from "../../values/index.js";
import { Long } from "../long.js";
import { logToConsole } from "../logging.js";
import { QueryId, StateVersion, Transition } from "./protocol.js";
/**
* The result of running a query function on the server.
*
* If the function hit an exception it will have an `errorMessage`. Otherwise
* it will produce a `Value`.
*
* @public
*/
export type QueryResult =
| {
success: true;
value: Value;
}
| { success: false; errorMessage: string };
/**
* A represention of the query results we've received on the current WebSocket
* connection.
*/
export class RemoteQuerySet {
private version: StateVersion;
private readonly remoteQuerySet: Map<QueryId, QueryResult>;
private readonly queryPath: (queryId: QueryId) => string | null;
constructor(queryPath: (queryId: QueryId) => string | null) {
this.version = { querySet: 0, ts: Long.fromNumber(0), identity: 0 };
this.remoteQuerySet = new Map();
this.queryPath = queryPath;
}
transition(transition: Transition): void {
const start = transition.startVersion;
if (
this.version.querySet !== start.querySet ||
this.version.ts.notEquals(start.ts) ||
this.version.identity !== start.identity
) {
throw new Error(`Invalid start version: ${start.ts}:${start.querySet}`);
}
for (const modification of transition.modifications) {
switch (modification.type) {
case "QueryUpdated": {
const queryPath = this.queryPath(modification.queryId);
if (queryPath) {
for (const line of modification.logLines) {
logToConsole("info", "query", queryPath, line);
}
}
const value = jsonToConvex(modification.value ?? null);
this.remoteQuerySet.set(modification.queryId, {
success: true,
value,
});
break;
}
case "QueryFailed": {
const queryPath = this.queryPath(modification.queryId);
if (queryPath) {
for (const line of modification.logLines) {
logToConsole("info", "query", queryPath, line);
}
}
this.remoteQuerySet.set(modification.queryId, {
success: false,
errorMessage: modification.errorMessage,
});
break;
}
case "QueryRemoved": {
this.remoteQuerySet.delete(modification.queryId);
break;
}
default: {
// Enforce that the switch-case is exhaustive.
const _: never = modification;
throw new Error(`Invalid modification ${modification}`);
}
}
}
this.version = transition.endVersion;
}
remoteQueryResults(): Map<QueryId, QueryResult> {
return this.remoteQuerySet;
}
timestamp(): Long {
return this.version.ts;
}
}