apollo-form
Version:
Form state manager
60 lines (59 loc) • 1.99 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("../../utils");
const isEqual_1 = __importDefault(require("lodash/isEqual"));
const BaseManager_1 = __importDefault(require("../BaseManager"));
class ApolloManager extends BaseManager_1.default {
constructor(name, client) {
super();
this.name = name;
this.query = this.getQuery();
this.apolloClient = client;
}
set(state) {
this.apolloClient.writeQuery({ query: this.query, data: { [this.name]: state } });
}
get() {
let data = null;
try {
data = this.apolloClient.readQuery({
query: this.query,
});
}
catch (e) { }
return (data || {})[this.name];
}
watch(selector, handler, defaultState) {
const rawState = this.get();
// @ts-ignore
const state = rawState ? rawState : defaultState;
let previous = selector && state ? selector(state) : state;
const unWatch = this.apolloClient.cache.watch({
query: this.query,
callback: ({ result }) => {
const fullState = result[this.name];
if (!fullState) {
return;
}
const v = (selector ? selector(fullState) : fullState);
if (!isEqual_1.default(previous, v)) {
const prev = previous;
previous = v;
handler(v, prev);
}
},
optimistic: false,
});
return unWatch;
}
remove() {
this.apolloClient.cache.evict({ id: 'ROOT_QUERY', fieldName: this.name });
}
getQuery() {
return utils_1.makeApolloFormQuery(this.name);
}
}
exports.default = ApolloManager;