UNPKG

3.03 kBJavaScriptView Raw
1"use strict";
2/*!
3 * Copyright 2019 Google Inc. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18exports.ResourceStream = void 0;
19const stream_1 = require("stream");
20class ResourceStream extends stream_1.Transform {
21 constructor(args, requestFn) {
22 const options = Object.assign({ objectMode: true }, args.streamOptions);
23 super(options);
24 this._ended = false;
25 this._maxApiCalls = args.maxApiCalls === -1 ? Infinity : args.maxApiCalls;
26 this._nextQuery = args.query;
27 this._reading = false;
28 this._requestFn = requestFn;
29 this._requestsMade = 0;
30 this._resultsToSend = args.maxResults === -1 ? Infinity : args.maxResults;
31 }
32 /* eslint-disable @typescript-eslint/no-explicit-any */
33 end(...args) {
34 this._ended = true;
35 return super.end(...args);
36 }
37 _read() {
38 if (this._reading) {
39 return;
40 }
41 this._reading = true;
42 // Wrap in a try/catch to catch input linting errors, e.g.
43 // an invalid BigQuery query. These errors are thrown in an
44 // async fashion, which makes them un-catchable by the user.
45 try {
46 this._requestFn(this._nextQuery, (err, results, nextQuery) => {
47 if (err) {
48 this.destroy(err);
49 return;
50 }
51 this._nextQuery = nextQuery;
52 if (this._resultsToSend !== Infinity) {
53 results = results.splice(0, this._resultsToSend);
54 this._resultsToSend -= results.length;
55 }
56 let more = true;
57 for (const result of results) {
58 if (this._ended) {
59 break;
60 }
61 more = this.push(result);
62 }
63 const isFinished = !this._nextQuery || this._resultsToSend < 1;
64 const madeMaxCalls = ++this._requestsMade >= this._maxApiCalls;
65 if (isFinished || madeMaxCalls) {
66 this.end();
67 }
68 if (more && !this._ended) {
69 setImmediate(() => this._read());
70 }
71 this._reading = false;
72 });
73 }
74 catch (e) {
75 this.destroy(e);
76 }
77 }
78}
79exports.ResourceStream = ResourceStream;
80//# sourceMappingURL=resource-stream.js.map
\No newline at end of file