UNPKG

2.69 kBPlain TextView Raw
1/*
2 * Copyright 2019 gRPC authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18import { Call, StatusObject, WriteObject } from './call-stream';
19import { Filter, FilterFactory } from './filter';
20import { Metadata } from './metadata';
21
22export class FilterStack implements Filter {
23 constructor(private readonly filters: Filter[]) {}
24
25 sendMetadata(metadata: Promise<Metadata>) {
26 let result: Promise<Metadata> = metadata;
27
28 for (let i = 0; i < this.filters.length; i++) {
29 result = this.filters[i].sendMetadata(result);
30 }
31
32 return result;
33 }
34
35 receiveMetadata(metadata: Metadata) {
36 let result: Metadata = metadata;
37
38 for (let i = this.filters.length - 1; i >= 0; i--) {
39 result = this.filters[i].receiveMetadata(result);
40 }
41
42 return result;
43 }
44
45 sendMessage(message: Promise<WriteObject>): Promise<WriteObject> {
46 let result: Promise<WriteObject> = message;
47
48 for (let i = 0; i < this.filters.length; i++) {
49 result = this.filters[i].sendMessage(result);
50 }
51
52 return result;
53 }
54
55 receiveMessage(message: Promise<Buffer>): Promise<Buffer> {
56 let result: Promise<Buffer> = message;
57
58 for (let i = this.filters.length - 1; i >= 0; i--) {
59 result = this.filters[i].receiveMessage(result);
60 }
61
62 return result;
63 }
64
65 receiveTrailers(status: StatusObject): StatusObject {
66 let result: StatusObject = status;
67
68 for (let i = this.filters.length - 1; i >= 0; i--) {
69 result = this.filters[i].receiveTrailers(result);
70 }
71
72 return result;
73 }
74
75 refresh(): void {
76 for (const filter of this.filters) {
77 filter.refresh();
78 }
79 }
80
81 push(filters: Filter[]) {
82 this.filters.unshift(...filters);
83 }
84
85 getFilters(): Filter[] {
86 return this.filters;
87 }
88}
89
90export class FilterStackFactory implements FilterFactory<FilterStack> {
91 constructor(private readonly factories: Array<FilterFactory<Filter>>) {}
92
93 push(filterFactories: FilterFactory<Filter>[]) {
94 this.factories.unshift(...filterFactories);
95 }
96
97 createFilter(callStream: Call): FilterStack {
98 return new FilterStack(
99 this.factories.map((factory) => factory.createFilter(callStream))
100 );
101 }
102}