create cycle js driver

89 Views Asked by At

I am relatively new to this framework and am trying to play around creating driver. I understand this code:

import {adapt} from '@cycle/run/lib/adapt';

function makeSockDriver(peerId) {
  let sock = new Sock(peerId);

  function sockDriver(outgoing$) {
    outgoing$.addListener({
      next: outgoing => {
        sock.send(outgoing));
      },
      error: () => {},
      complete: () => {},
    });

    const incoming$ = xs.create({
      start: listener => {
        sock.onReceive(function (msg) {
          listener.next(msg);
        });
      },
      stop: () => {},
    });

    return adapt(incoming$);
  }

  return sockDriver;
}

but what I am not sure yet is how to have listener (incoming$) take parameter like the http driver:

const response$ = HTTP
        .select('posts')
1

There are 1 best solutions below

0
On

The select method from the HTTP does not come from xstream, it's a method that is implemented and returned by the HTTP driver (you can see the implementation of that method here : https://github.com/cyclejs/cyclejs/blob/462e53a67e05d48091c002f004e51ae1f322f7a3/http/src/MainHTTPSource.ts#L20)

So, if you feel you need a select method (if you have to filter your socket source), you can implement it yourself in the driver and return it in your sockDriver function

function makeSockDriver(peerId) {
  let sock = new Sock(peerId);

  function sockDriver(outgoing$) {
    const incoming$ = /* ... */

    function select(category) {
      const res$ = category ?
        incoming$.filter(data => /* filter the data here */) :
        incoming$;

      return res$;
    }
    return { select }; // an object with the `select` method
  }

  return sockDriver;
}

That being said, I don't think you need a select method for a socket driver! The select is, more or less, a convention that allows you to filter the source according to the sink that has generated that source.

For example, one of your component issues a HTTP request with a category doThing then, in that component, you might want to select the responses that have the doThing category.

In your case (a socket driver) there is no request-response pattern. There is no obvious link between the sinks and the sources (you can trigger messages that won't send any response message, and you can receive responses messages that are not linked to any message you've sent).

So if I were you, I'd just use the incoming$ returned by your driver (and eventually filtering it out in your components) like this

function component({ socket }) {
  /* here `socket` is the `incoming$` you return in the `sockDriver`
  const socketData$ = socket.filter(data => /* predicate here */);

  return {
    /* sinks */
  }
}