Skip to content

Instantly share code, notes, and snippets.

@dminkovsky
Last active July 8, 2018 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dminkovsky/6c6022c9c40b579235c206cc92a2900c to your computer and use it in GitHub Desktop.
Save dminkovsky/6c6022c9c40b579235c206cc92a2900c to your computer and use it in GitHub Desktop.
export default class MessageUpdater {
constructor(id, environment) {
this._id = id;
this._environment = environment;
}
update({to, body}) {
const dirty = this._dirty();
const message = {
...(dirty && dirty.response.messageUpdate.message),
id: this._id,
};
if (to !== undefined) {
message.to = to;
}
if (body !== undefined) {
message.body = body;
}
const response = {
messageUpdate: {
message,
},
};
const input = {
id: this._id,
};
if (message.to !== undefined) {
input.to = message.to;
}
if (message.body !== undefined) {
input.body = body;
}
const operation = this._operation(
mutation,
{input},
);
const update = {
operation,
response,
};
if (dirty) {
this._environment.replaceUpdate(dirty, update);
} else {
this._environment.applyUpdate(update);
}
}
persist() {
const dirty = this._dirty();
if (!dirty) {
return Observable.from(null);
}
return this._environment.executeMutation({
operation: dirty.operation,
})
.do({
next: () => this._environment.revertUpdate(dirty),
})
.map(({response}) => {
return response.data.messageUpdate.message;
});
}
_dirty() {
return this._findOptimisticUpdate(
({response}) => response.messageUpdate &&
response.messageUpdate.message.id === this._id
);
}
_findOptimisticUpdate(predicate) {
return this._environment._publishQueue
._appliedOptimisticUpdates
.toJSON()
.find(predicate);
}
_operation(query, variables) {
const {
createOperationSelector,
getRequest,
} = this._environment.unstable_internal;
const request = getRequest(query);
return createOperationSelector(
request,
variables
);
}
}
const mutation = graphql`
mutation MessageUpdaterMutation(
$input: MessageUpdateInput!
) {
messageUpdate(input: $input) {
message {
to
body
}
}
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment