Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert tests #1

Open
ssured opened this issue Mar 16, 2018 · 0 comments
Open

convert tests #1

ssured opened this issue Mar 16, 2018 · 0 comments

Comments

@ssured
Copy link
Owner

ssured commented Mar 16, 2018

const Gun = require("gun/gun");
const { pipe, take, forEach, interval } = require("callbag-basics");

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const val = (gun, wait = 99) =>
  new Promise(resolve => gun.val(resolve, { wait }));

describe("callbag support for gun", () => {
  const fromContext = function(gun, options = {}) {
    let isRunning = false,
      event;

    const cleanup = () => {
      if (!isRunning && event) {
        event.off();
        event = void 0;
      }
    };

    return function(start, sink) {
      if (start !== 0) return;
      isRunning = true;
      sink(0, function(t) {
        if (t === 2) {
          isRunning = false;
          cleanup();
        }
      });
      gun.on(function(data, key, context, _event) {
        event = _event;
        if (!isRunning) {
          cleanup();
        } else {
          sink(1, data);
        }
      }, options);
    };
  };

  it("it exposes a gun endpoint as callbag", async () => {
    const gun = Gun({});

    const context = gun.get("random").get("key");
    context.put("hello");

    const values = [];
    pipe(
      fromContext(context),
      take(2),
      forEach(value => {
        values.push(value);
      })
    );

    context.put("world");
    await delay(100);
    expect(values).toEqual(["hello", "world"]);

    context.put("!");
    await delay(100);
    expect(values).toEqual(["hello", "world"]);
  });

  const toContext = function(gun) {
    return function(source) {
      let talkback;
      source(0, function(t, d) {
        if (t === 0) talkback = d;
        if (t === 1) gun.put(d);
        if (t === 1 || t === 0) talkback(1);
      });
    };
  };

  it("it writes a callbag to a context", async () => {
    const gun = Gun({});

    const context = gun.get("random").get("key");
    context.put("initial");

    pipe(interval(100), take(2), toContext(context));

    expect(await val(context, 0)).toEqual("initial");
    expect(await val(context, 100)).toEqual(0);
    expect(await val(context, 100)).toEqual(1);
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant