How to use the iterall.forAwaitEach function in iterall

To help you get started, we’ve selected a few iterall examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github badbatch / graphql-box / test / specs / server / subscription / index.ts View on Github external
before(async () => {
          mockRestRequest("product", "402-5806");
          fetchMock.spy();

          try {
            const asyncIterator = await client.request(
              ecom.requests.singleSubscription,
              { awaitDataCached: true },
            );

            if (isAsyncIterable(asyncIterator)) {
              forAwaitEach(asyncIterator, (value) => {
                result = value as RequestResultData;
                const deferredValue = deferred[0] as DeferPromise.Deferred;
                deferredValue.resolve();
              });
            }
          } catch (error) {
            console.log(error); // tslint:disable-line
          }
        });
github graphql-factory / graphql-factory / src / utilities / httpPOST.js View on Github external
const req = proto.request(opts, res => {
        let data = '';
        const contentType = res.headers['content-type'];
        const types =
          typeof contentType === 'string'
            ? contentType.split(';').map(h => h.trim().toLowerCase())
            : [];

        const iterator = AsyncIterator.fromStream(res, {
          closeEvent: 'end',
        });

        // iterate through the data stream
        return forAwaitEach(iterator, value => {
          data += value;
        })
          .then(() => {
            clearTimeout(timeout);
            if (types.indexOf('application/json') !== -1) {
              try {
                resolve(JSON.parse(data));
              } catch (parseErr) {
                clearTimeout(timeout);
                return reject(parseErr);
              }
            }
          })
          .catch(err => {
            clearTimeout(timeout);
            return reject(err);
github tjmehta / primus-graphql / lib / server / data-handler.js View on Github external
return this._queryExecutor.subscribe(payload).then(function (iterator) {
    activeIterators.add(spark.id, payload.id, iterator)
    return forAwaitEach(iterator, (val) => callbacks.onNext(val.data)).then(function () {
      // iterator completed
      activeIterators.remove(spark.id, payload.id)
      callbacks.onCompleted()
    })
  }).catch(function (err) {
    // iterator errored
github Urigo / SOFA / src / subscriptions.ts View on Github external
variableValues,
      contextValue: C,
    });

    if (isAsyncIterable(execution)) {
      // successful

      // add execution to clients
      this.clients.set(id, {
        name,
        url,
        iterator: execution as any,
      });

      // success
      forAwaitEach(execution, async result => {
        await this.sendData({
          id,
          result,
        });
      }).then(
        () => {
          // completes
          this.stop(id);
        },
        e => {
          logger.info(`Subscription #${id} closed`);
          logger.error(e);
          this.stop(id);
        }
      );
    } else {
github badbatch / graphql-box / packages / subscribe / src / main / index.ts View on Github external
const subscribeArgs: SubscribeArgs = {
      contextValue: { ...contextValue, boxID },
      document: ast || parse(request),
      fieldResolver: fieldResolver || this._fieldResolver,
      operationName,
      rootValue: rootValue || this._rootValue,
      schema: this._schema,
      subscribeFieldResolver: subscribeFieldResolver || this._subscribeFieldResolver,
    };

    try {
      const subscribeResult = await this._subscribe(subscribeArgs);

      if (isAsyncIterable(subscribeResult)) {
        forAwaitEach(subscribeResult, async ({ data, errors }: ExecutionResult) => {
          const resolvedResult = await subscriberResolver({ data, errors });
          this._eventEmitter.emit(hash, resolvedResult);
        });
      }

      const eventAsyncIterator = new EventAsyncIterator(this._eventEmitter, hash);
      return eventAsyncIterator.getIterator();
    } catch (error) {
      return Promise.reject(error);
    }
  }
}
github fanout / apollo-serverless-demo / src / subscriptions-transport-core / server.ts View on Github external
.then(({ executionIterable, params }) => {
                  forAwaitEach(
                    executionIterable as any,
                    (value: ExecutionResult) => {
                      let result = value;

                      if (params.formatResponse) {
                        try {
                          result = params.formatResponse(value, params);
                        } catch (err) {
                          console.error("Error in formatError function:", err);
                        }
                      }

                      this.sendMessage(
                        connectionContext,
                        opId,
                        MessageTypes.GQL_DATA,
github badbatch / graphql-box / packages / worker-client / src / register-worker / index.ts View on Github external
async function handleSubscription(
  request: string,
  method: MethodNames,
  options: RequestOptions,
  context: MessageContext,
  client: Client,
): Promise {
  const subscribeResult = await client.subscribe(request, options, context);

  if (isAsyncIterable(subscribeResult)) {
    forAwaitEach(subscribeResult, ({ _cacheMetadata, ...otherProps }: MaybeRequestResult) => {
      const result: MaybeRequestResultWithDehydratedCacheMetadata = { ...otherProps };
      if (_cacheMetadata) result._cacheMetadata = dehydrateCacheMetadata(_cacheMetadata);
      postMessage({ context, method, result, type: GRAPHQL_BOX });
    });
  }
}
github badbatch / graphql-box / src / server-handl / index.ts View on Github external
private async _messageHandler(ws: WebSocket, message: string, opts: ServerRequestOptions = {}): Promise {
    try {
      const { subscriptionID, subscription } = JSON.parse(message);
      const subscribeResult = await this._client.request(subscription, opts);

      if (isAsyncIterable(subscribeResult)) {
        forAwaitEach(subscribeResult, (result: RequestResultData) => {
          if (ws.readyState === ws.OPEN) {
            const dehydratedResult = {
              ...result,
              cacheMetadata: ClientHandl.dehydrateCacheMetadata(result.cacheMetadata),
            };

            ws.send(JSON.stringify({ result: dehydratedResult, subscriptionID }));
          }
        });
      } else if (ws.readyState === ws.OPEN) {
        const result = subscribeResult as RequestResultData;

        const dehydratedResult = {
          ...result,
          cacheMetadata: ClientHandl.dehydrateCacheMetadata(result.cacheMetadata),
        };
github badbatch / graphql-box / packages / server / src / main / index.ts View on Github external
private async _messageHandler(message: Data, { ws, ...rest }: ServerSocketRequestOptions): Promise {
    try {
      const { context, subscriptionID, subscription } = JSON.parse(message as string);
      const subscribeResult = await this._client.request(subscription, rest, context);

      if (isAsyncIterable(subscribeResult)) {
        forAwaitEach(subscribeResult, ({ _cacheMetadata, ...otherProps }: MaybeRequestResult) => {
          if (ws.readyState === ws.OPEN) {
            const result: MaybeRequestResultWithDehydratedCacheMetadata = { ...otherProps };
            if (_cacheMetadata) result._cacheMetadata = dehydrateCacheMetadata(_cacheMetadata);
            ws.send(JSON.stringify({ result, subscriptionID }));
          }
        });
      }
    } catch (error) {
      ws.send(error);
    }
  }