Skip to content

Instantly share code, notes, and snippets.

@tchak
Last active April 19, 2020 13:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tchak/2a23843c35617a265e75c136afc99b77 to your computer and use it in GitHub Desktop.
Save tchak/2a23843c35617a265e75c136afc99b77 to your computer and use it in GitHub Desktop.
import { Source, SourceSettings, buildTransform } from '@orbit/data';
import {
createConsumer,
Cable,
ChannelNameWithParams
} from '@rails/actioncable';
import { JSONAPISerializer, ResourceOperationsDocument } from '@orbit/jsonapi';
export interface ActionCableSourceSettings extends SourceSettings {
cable?: Cable;
}
export class ActionCableSource extends Source {
consumer: Cable;
serializer: JSONAPISerializer;
constructor(settings: ActionCableSourceSettings) {
super(settings);
this.serializer = new JSONAPISerializer({
schema: this.schema
});
this.consumer = settings.cable as Cable;
}
async deactivate() {
await super.deactivate();
this.consumer.disconnect();
}
subscribe(query: Query) {
const channel = { channel: 'QueryChannel', expressions: query.expressions, options: query.options };
return this.consumer.subscriptions.create(channel, {
received: async (data: ResourceOperationsDocument) => {
const operations = this.serializer.deserializeOperationsDocument(data);
const transform = buildTransform(operations);
await this.transformed([transform]);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment