Last active
April 19, 2020 13:45
-
-
Save tchak/2a23843c35617a265e75c136afc99b77 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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