@n1ru4l/socket-io-graphql-client
Version:
[](https://www.npmjs.com/package/@n1ru4l/socket-io-graphql-client) [](https://www.npmjs.co
78 lines (77 loc) • 2.66 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSocketIOGraphQLClient = void 0;
const push_pull_async_iterable_iterator_1 = require("@n1ru4l/push-pull-async-iterable-iterator");
const createSocketIOGraphQLClient = (socket) => {
let currentOperationId = 0;
const operations = new Map();
const onExecutionResult = ({ id, isFinal, ...result }) => {
var _a, _b;
const record = operations.get(id);
if (!record) {
return;
}
record.publishValue(result);
if (isFinal) {
(_b = (_a = record.iterator).return) === null || _b === void 0 ? void 0 : _b.call(_a);
operations.delete(id);
}
};
let isOffline = false;
const onDisconnect = () => {
isOffline = true;
};
const onConnect = () => {
if (isOffline) {
isOffline = false;
Array.from(operations.values()).forEach((record) => {
record.execute();
});
}
};
socket.on("@graphql/result", onExecutionResult);
socket.on("connect", onConnect);
socket.on("disconnect", onDisconnect);
const destroy = () => {
socket.off("@graphql/result", onExecutionResult);
socket.off("connect", onConnect);
socket.off("disconnect", onDisconnect);
};
const execute = ({ operation, variables, operationName, extensions, }) => {
const operationId = currentOperationId;
currentOperationId = currentOperationId + 1;
const { asyncIterableIterator: source, pushValue: publishValue } = (0, push_pull_async_iterable_iterator_1.makePushPullAsyncIterableIterator)();
const stream = (0, push_pull_async_iterable_iterator_1.withHandlers)(source, () => {
if (operations.delete(operationId) === false) {
return;
}
socket.emit("@graphql/unsubscribe", {
id: operationId,
});
source.return();
});
const record = {
execute: () => {
socket.emit("@graphql/execute", {
id: operationId,
operationName,
operation,
variables,
extensions,
});
},
iterator: stream,
publishValue,
};
operations.set(operationId, record);
if (!isOffline) {
record.execute();
}
return stream;
};
return {
execute,
destroy,
};
};
exports.createSocketIOGraphQLClient = createSocketIOGraphQLClient;
;