-
Notifications
You must be signed in to change notification settings - Fork 877
/
service.ts
223 lines (202 loc) · 6.38 KB
/
service.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
* @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 { FirebaseApp } from '@firebase/app-types';
import firebase from '@firebase/app';
import {
FirebaseFunctions,
FunctionsErrorCode,
HttpsCallable,
HttpsCallableResult,
HttpsCallableOptions
} from '@firebase/functions-types';
import { _errorForResponse, HttpsErrorImpl } from './error';
import { ContextProvider } from '../context';
import { Serializer } from '../serializer';
/**
* The response to an http request.
*/
interface HttpResponse {
status: number;
json: any;
}
/**
* Returns a Promise that will be rejected after the given duration.
* The error will be of type HttpsErrorImpl.
*
* @param millis Number of milliseconds to wait before rejecting.
*/
function failAfter(millis: number): Promise<HttpResponse> {
return new Promise((_, reject) => {
setTimeout(() => {
reject(new HttpsErrorImpl('deadline-exceeded', 'deadline-exceeded'));
}, millis);
});
}
/**
* The main class for the Firebase Functions SDK.
*/
export class Service implements FirebaseFunctions {
private readonly contextProvider: ContextProvider;
private readonly serializer = new Serializer();
private emulatorOrigin: string | null = null;
/**
* Creates a new Functions service for the given app and (optional) region.
* @param app_ The FirebaseApp to use.
* @param region_ The region to call functions in.
*/
constructor(
private app_: FirebaseApp,
private region_: string = 'us-central1'
) {
this.contextProvider = new ContextProvider(app_);
}
get app(): FirebaseApp {
return this.app_;
}
/**
* Returns the URL for a callable with the given name.
* @param name The name of the callable.
*/
_url(name: string): string {
const projectId = this.app_.options.projectId;
const region = this.region_;
if (this.emulatorOrigin !== null) {
const origin = this.emulatorOrigin;
return `${origin}/${projectId}/${region}/${name}`;
}
return `https://${region}-${projectId}.cloudfunctions.net/${name}`;
}
/**
* Changes this instance to point to a Cloud Functions emulator running
* locally. See https://firebase.google.com/docs/functions/local-emulator
*
* @param origin The origin of the local emulator, such as
* "http://localhost:5005".
*/
useFunctionsEmulator(origin: string) {
this.emulatorOrigin = origin;
}
/**
* Returns a reference to the callable https trigger with the given name.
* @param name The name of the trigger.
*/
httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable {
let callable = <HttpsCallable>(data?: any) => {
return this.call(name, data, options || {});
};
return callable;
}
/**
* Does an HTTP POST and returns the completed response.
* @param url The url to post to.
* @param body The JSON body of the post.
* @param headers The HTTP headers to include in the request.
* @return A Promise that will succeed when the request finishes.
*/
private async postJSON(
url: string,
body: {},
headers: Headers
): Promise<HttpResponse> {
headers.append('Content-Type', 'application/json');
let response: Response;
try {
response = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
headers
});
} catch (e) {
// This could be an unhandled error on the backend, or it could be a
// network error. There's no way to know, since an unhandled error on the
// backend will fail to set the proper CORS header, and thus will be
// treated as a network error by fetch.
return {
status: 0,
json: null
};
}
let json: any = null;
try {
json = await response.json();
} catch (e) {
// If we fail to parse JSON, it will fail the same as an empty body.
}
return {
status: response.status,
json: json
};
}
/**
* Calls a callable function asynchronously and returns the result.
* @param name The name of the callable trigger.
* @param data The data to pass as params to the function.s
*/
private async call(
name: string,
data: any,
options: HttpsCallableOptions
): Promise<HttpsCallableResult> {
const url = this._url(name);
// Encode any special types, such as dates, in the input data.
data = this.serializer.encode(data);
const body = { data };
// Add a header for the authToken.
const headers = new Headers();
const context = await this.contextProvider.getContext();
if (context.authToken) {
headers.append('Authorization', 'Bearer ' + context.authToken);
}
if (context.instanceIdToken) {
headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);
}
// Default timeout to 70s, but let the options override it.
const timeout = options.timeout || 70000;
const response = await Promise.race([
this.postJSON(url, body, headers),
failAfter(timeout)
]);
// Check for an error status, regardless of http status.
const error = _errorForResponse(
response.status,
response.json,
this.serializer
);
if (error) {
throw error;
}
if (!response.json) {
throw new HttpsErrorImpl(
'internal',
'Response is not valid JSON object.'
);
}
let responseData = response.json.data;
// TODO(klimt): For right now, allow "result" instead of "data", for
// backwards compatibility.
if (typeof responseData === 'undefined') {
responseData = response.json.result;
}
if (typeof responseData === 'undefined') {
// Consider the response malformed.
throw new HttpsErrorImpl('internal', 'Response is missing data field.');
}
// Decode any special types, such as dates, in the returned data.
const decodedData = this.serializer.decode(responseData);
return { data: decodedData };
}
}