forked from firebase/firebase-admin-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.ts
More file actions
230 lines (202 loc) · 6.47 KB
/
database.ts
File metadata and controls
230 lines (202 loc) · 6.47 KB
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
224
225
226
227
228
229
230
import {URL} from 'url';
import * as path from 'path';
import {FirebaseApp} from '../firebase-app';
import {FirebaseDatabaseError, AppErrorCodes} from '../utils/error';
import {FirebaseServiceInterface, FirebaseServiceInternalsInterface} from '../firebase-service';
import {Database} from '@firebase/database';
import * as validator from '../utils/validator';
import { AuthorizedHttpClient, HttpRequestConfig, HttpError } from '../utils/api-request';
/**
* Internals of a Database instance.
*/
class DatabaseInternals implements FirebaseServiceInternalsInterface {
public databases: {
[dbUrl: string]: Database,
} = {};
/**
* Deletes the service and its associated resources.
*
* @return {Promise<()>} An empty Promise that will be fulfilled when the service is deleted.
*/
public delete(): Promise<void> {
for (const dbUrl of Object.keys(this.databases)) {
const db: Database = this.databases[dbUrl];
db.INTERNAL.delete();
}
return Promise.resolve(undefined);
}
}
declare module '@firebase/database' {
interface Database {
getRules(): Promise<string>;
getRulesJSON(): Promise<object>;
setRules(source: string | Buffer | object): Promise<void>;
}
}
export class DatabaseService implements FirebaseServiceInterface {
public readonly INTERNAL: DatabaseInternals = new DatabaseInternals();
private readonly appInternal: FirebaseApp;
constructor(app: FirebaseApp) {
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new FirebaseDatabaseError({
code: 'invalid-argument',
message: 'First argument passed to admin.database() must be a valid Firebase app instance.',
});
}
this.appInternal = app;
}
/**
* Returns the app associated with this DatabaseService instance.
*
* @return {FirebaseApp} The app associated with this DatabaseService instance.
*/
get app(): FirebaseApp {
return this.appInternal;
}
public getDatabase(url?: string): Database {
const dbUrl: string = this.ensureUrl(url);
if (!validator.isNonEmptyString(dbUrl)) {
throw new FirebaseDatabaseError({
code: 'invalid-argument',
message: 'Database URL must be a valid, non-empty URL string.',
});
}
let db: Database = this.INTERNAL.databases[dbUrl];
if (typeof db === 'undefined') {
const rtdb = require('@firebase/database');
const { version } = require('../../package.json');
db = rtdb.initStandalone(this.appInternal, dbUrl, version).instance;
const rulesClient = new DatabaseRulesClient(this.app, dbUrl);
db.getRules = () => {
return rulesClient.getRules();
};
db.getRulesJSON = () => {
return rulesClient.getRulesJSON();
};
db.setRules = (source) => {
return rulesClient.setRules(source);
};
this.INTERNAL.databases[dbUrl] = db;
}
return db;
}
private ensureUrl(url?: string): string {
if (typeof url !== 'undefined') {
return url;
} else if (typeof this.appInternal.options.databaseURL !== 'undefined') {
return this.appInternal.options.databaseURL;
}
throw new FirebaseDatabaseError({
code: 'invalid-argument',
message: 'Can\'t determine Firebase Database URL.',
});
}
}
const RULES_URL_PATH = '.settings/rules.json';
/**
* A helper client for managing RTDB security rules.
*/
class DatabaseRulesClient {
private readonly dbUrl: string;
private readonly httpClient: AuthorizedHttpClient;
constructor(app: FirebaseApp, dbUrl: string) {
const parsedUrl = new URL(dbUrl);
parsedUrl.pathname = path.join(parsedUrl.pathname, RULES_URL_PATH);
this.dbUrl = parsedUrl.toString();
this.httpClient = new AuthorizedHttpClient(app);
}
/**
* Gets the currently applied security rules as a string. The return value consists of
* the rules source including comments.
*
* @return {Promise<string>} A promise fulfilled with the rules as a raw string.
*/
public getRules(): Promise<string> {
const req: HttpRequestConfig = {
method: 'GET',
url: this.dbUrl,
};
return this.httpClient.send(req)
.then((resp) => {
return resp.text;
})
.catch((err) => {
throw this.handleError(err);
});
}
/**
* Gets the currently applied security rules as a parsed JSON object. Any comments in
* the original source are stripped away.
*
* @return {Promise<object>} A promise fulfilled with the parsed rules source.
*/
public getRulesJSON(): Promise<object> {
const req: HttpRequestConfig = {
method: 'GET',
url: this.dbUrl,
data: {format: 'strict'},
};
return this.httpClient.send(req)
.then((resp) => {
return resp.data;
})
.catch((err) => {
throw this.handleError(err);
});
}
/**
* Sets the specified rules on the Firebase Database instance. If the rules source is
* specified as a string or a Buffer, it may include comments.
*
* @param {string|Buffer|object} source Source of the rules to apply. Must not be `null`
* or empty.
* @return {Promise<void>} Resolves when the rules are set on the Database.
*/
public setRules(source: string | Buffer | object): Promise<void> {
if (!validator.isNonEmptyString(source) &&
!validator.isBuffer(source) &&
!validator.isNonNullObject(source)) {
const error = new FirebaseDatabaseError({
code: 'invalid-argument',
message: 'Source must be a non-empty string, Buffer or an object.',
});
return Promise.reject(error);
}
const req: HttpRequestConfig = {
method: 'PUT',
url: this.dbUrl,
data: source,
headers: {
'content-type': 'application/json; charset=utf-8',
},
};
return this.httpClient.send(req)
.then(() => {
return;
})
.catch((err) => {
throw this.handleError(err);
});
}
private handleError(err: Error): Error {
if (err instanceof HttpError) {
return new FirebaseDatabaseError({
code: AppErrorCodes.INTERNAL_ERROR,
message: this.getErrorMessage(err),
});
}
return err;
}
private getErrorMessage(err: HttpError): string {
const intro = 'Error while accessing security rules';
try {
const body: {error?: string} = err.response.data;
if (body && body.error) {
return `${intro}: ${body.error.trim()}`;
}
} catch {
// Ignore parsing errors
}
return `${intro}: ${err.response.text}`;
}
}