DEV Community

nic
nic

Posted on

http requests received turned into an Iterator

There are a few situations where this sort of thing is useful and I have an important one at work right now.

I thought this was hard at first and I looked at a few modules for doing it... but then I slept on it and ... ta da!

import fetch from "node-fetch";
import {Response} from "node-fetch";
import * as express from "express";
import {EventEmitter} from "events";

async function* gt() {
    const app = express();
    const eventThing = new EventEmitter();
    app.post("/", function (request, response) {
        response.sendStatus(204);
        eventThing.emit("helloEvent", {
            token: ["hello", "world"]
        });
    });
    app.listen(8000);

    const queueEvents = new EventEmitter();
    const queue:any[] = [];
    eventThing.on("helloEvent", e => {
        queue.push(e);
        queueEvents.emit("queueReady", queue);
    });

    const response:Response = await fetch("http://localhost:8000/", {
        method: "POST"
    });
    setInterval(async _ => {
        const response:Response = await fetch("http://localhost:8000/", {
            method: "POST"
        })
    }, 6000);

    while (true) {
        while (queue.length > 0) {
            yield queue.pop();
        }
        await new Promise((resolve, reject) => {
            queueEvents.once("queueReady", resolve);
        });
    }
}

async function test() {
    const stream = gt();
    let next = await stream.next();
    while (!next.done) {
        console.log(next.value);
        next = await stream.next();
    }
}

test().then();

I guess you could make it an IterableIterator too.

I am not sure this is perfect. Would I lose events between the end of the queue in the while loop and the next queue.once? I'm not sure. Anyone wanna tell me?

Top comments (0)