UNPKG

2.29 kBPlain TextView Raw
1// Copyright 2021 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import * as Common from '../../core/common/common.js';
6import type * as SDK from '../../core/sdk/sdk.js';
7import type * as Protocol from '../../generated/protocol.js';
8
9import {Events as NetworkLogEvents, NetworkLog} from './NetworkLog.js';
10
11/**
12 * A class that facilitates resolving a requestId to a network request. If the requestId does not resolve, a listener
13 * is installed on the network request to wait for the request to appear. This is useful if an attempt to resolve the
14 * requestId is made before the network request got reported.
15 *
16 * This functionality is intentionally provided in this class (instead of as part of NetworkLog) to enable clients
17 * to control the duration of the wait and the lifetime of the associated promises by using the `clear` method on
18 * this class.
19 */
20export class RequestResolver extends
21 Common.ResolverBase.ResolverBase<Protocol.Network.RequestId, SDK.NetworkRequest.NetworkRequest> {
22 private networkListener: Common.EventTarget.EventDescriptor|null = null;
23 private networkLog: NetworkLog;
24
25 constructor(networkLog: NetworkLog = NetworkLog.instance()) {
26 super();
27 this.networkLog = networkLog;
28 }
29
30 protected getForId(id: Protocol.Network.RequestId): SDK.NetworkRequest.NetworkRequest|null {
31 const requests = this.networkLog.requestsForId(id);
32 if (requests.length > 0) {
33 return requests[0];
34 }
35 return null;
36 }
37
38 private onRequestAdded(event: Common.EventTarget.EventTargetEvent<SDK.NetworkRequest.NetworkRequest>): void {
39 const request = event.data;
40 const backendRequestId = request.backendRequestId();
41 if (backendRequestId) {
42 this.onResolve(backendRequestId, request);
43 }
44 }
45
46 protected override startListening(): void {
47 if (this.networkListener) {
48 return;
49 }
50 this.networkListener = this.networkLog.addEventListener(NetworkLogEvents.RequestAdded, this.onRequestAdded, this);
51 }
52
53 protected override stopListening(): void {
54 if (!this.networkListener) {
55 return;
56 }
57 Common.EventTarget.removeEventListeners([this.networkListener]);
58 this.networkListener = null;
59 }
60}