UNPKG

2.67 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 { StatusObject, WriteObject } from './call-interface';
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>): 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 push(filters: Filter[]) {
76 this.filters.unshift(...filters);
77 }
78
79 getFilters(): Filter[] {
80 return this.filters;
81 }
82}
83
84export class FilterStackFactory implements FilterFactory<FilterStack> {
85 constructor(private readonly factories: Array<FilterFactory<Filter>>) {}
86
87 push(filterFactories: FilterFactory<Filter>[]) {
88 this.factories.unshift(...filterFactories);
89 }
90
91 clone(): FilterStackFactory {
92 return new FilterStackFactory([...this.factories]);
93 }
94
95 createFilter(): FilterStack {
96 return new FilterStack(
97 this.factories.map(factory => factory.createFilter())
98 );
99 }
100}