-
Notifications
You must be signed in to change notification settings - Fork 387
/
Copy pathmessaging-api-request-internal.ts
139 lines (128 loc) · 4.76 KB
/
messaging-api-request-internal.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*!
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { App } from '../app';
import { FirebaseApp } from '../app/firebase-app';
import {
HttpMethod, AuthorizedHttpClient, HttpRequestConfig, HttpError, HttpResponse,
} from '../utils/api-request';
import { createFirebaseError, getErrorCode } from './messaging-errors-internal';
import { SubRequest, BatchRequestClient } from './batch-request-internal';
import { getSdkVersion } from '../utils/index';
import { SendResponse, BatchResponse } from './messaging-api';
// FCM backend constants
const FIREBASE_MESSAGING_TIMEOUT = parseInt(process.env.FIREBASE_MESSAGING_TIMEOUT || '10000', 10);
const FIREBASE_MESSAGING_BATCH_URL = 'https://fcm.googleapis.com/batch';
const FIREBASE_MESSAGING_HTTP_METHOD: HttpMethod = 'POST';
const FIREBASE_MESSAGING_HEADERS = {
'X-Firebase-Client': `fire-admin-node/${getSdkVersion()}`,
};
const LEGACY_FIREBASE_MESSAGING_HEADERS = {
'X-Firebase-Client': `fire-admin-node/${getSdkVersion()}`,
'access_token_auth': 'true',
};
/**
* Class that provides a mechanism to send requests to the Firebase Cloud Messaging backend.
*/
export class FirebaseMessagingRequestHandler {
private readonly httpClient: AuthorizedHttpClient;
private readonly batchClient: BatchRequestClient;
/**
* @param app - The app used to fetch access tokens to sign API requests.
* @constructor
*/
constructor(app: App) {
this.httpClient = new AuthorizedHttpClient(app as FirebaseApp);
this.batchClient = new BatchRequestClient(
this.httpClient, FIREBASE_MESSAGING_BATCH_URL, FIREBASE_MESSAGING_HEADERS);
}
/**
* Invokes the request handler with the provided request data.
*
* @param host - The host to which to send the request.
* @param path - The path to which to send the request.
* @param requestData - The request data.
* @returns A promise that resolves with the response.
*/
public invokeRequestHandler(host: string, path: string, requestData: object): Promise<object> {
const request: HttpRequestConfig = {
method: FIREBASE_MESSAGING_HTTP_METHOD,
url: `https://${host}${path}`,
data: requestData,
headers: LEGACY_FIREBASE_MESSAGING_HEADERS,
timeout: FIREBASE_MESSAGING_TIMEOUT,
};
return this.httpClient.send(request).then((response) => {
// Send non-JSON responses to the catch() below where they will be treated as errors.
if (!response.isJson()) {
throw new HttpError(response);
}
// Check for backend errors in the response.
const errorCode = getErrorCode(response.data);
if (errorCode) {
throw new HttpError(response);
}
// Return entire response.
return response.data;
})
.catch((err) => {
if (err instanceof HttpError) {
throw createFirebaseError(err);
}
// Re-throw the error if it already has the proper format.
throw err;
});
}
/**
* Sends the given array of sub requests as a single batch to FCM, and parses the result into
* a BatchResponse object.
*
* @param requests - An array of sub requests to send.
* @returns A promise that resolves when the send operation is complete.
*/
public sendBatchRequest(requests: SubRequest[]): Promise<BatchResponse> {
return this.batchClient.send(requests)
.then((responses: HttpResponse[]) => {
return responses.map((part: HttpResponse) => {
return this.buildSendResponse(part);
});
}).then((responses: SendResponse[]) => {
const successCount: number = responses.filter((resp) => resp.success).length;
return {
responses,
successCount,
failureCount: responses.length - successCount,
};
}).catch((err) => {
if (err instanceof HttpError) {
throw createFirebaseError(err);
}
// Re-throw the error if it already has the proper format.
throw err;
});
}
private buildSendResponse(response: HttpResponse): SendResponse {
const result: SendResponse = {
success: response.status === 200,
};
if (result.success) {
result.messageId = response.data.name;
} else {
result.error = createFirebaseError(new HttpError(response));
}
return result;
}
}