Skip to content

Commit a6bd3fe

Browse files
author
Shubham Bhardwaj
committed
added method to clear all firestore data
1 parent de23c0f commit a6bd3fe

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/providers/firestore.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import { has, get, isEmpty, isPlainObject, mapValues } from 'lodash';
2727

2828
import { testApp } from '../app';
2929

30+
import * as http from 'http';
31+
3032
/** Optional parameters for creating a DocumentSnapshot. */
3133
export interface DocumentSnapshotOptions {
3234
/** ISO timestamp string for the snapshot was read, default is current time. */
@@ -214,3 +216,52 @@ export function objectToValueProto(data: object) {
214216

215217
return mapValues(data, encodeHelper);
216218
}
219+
220+
const FIRESTORE_ADDRESS_ENVS = [
221+
'FIRESTORE_EMULATOR_HOST',
222+
'FIREBASE_FIRESTORE_EMULATOR_ADDRESS',
223+
];
224+
225+
const FIRESTORE_ADDRESS = FIRESTORE_ADDRESS_ENVS.reduce(
226+
(addr, name) => process.env[name] || addr,
227+
'localhost:8080'
228+
);
229+
const FIRESTORE_PORT = FIRESTORE_ADDRESS.split(':')[1];
230+
231+
export type ClearFirestoreDataOptions = {
232+
projectId: string;
233+
};
234+
235+
/** Clears all data in firestore. Works only in offline mode.
236+
*/
237+
export function clearFirestoreData(options: ClearFirestoreDataOptions) {
238+
return new Promise((resolve, reject) => {
239+
const config = {
240+
method: 'DELETE',
241+
hostname: 'localhost',
242+
port: FIRESTORE_PORT,
243+
path: `/emulator/v1/projects/${options.projectId}/databases/(default)/documents`,
244+
};
245+
246+
const req = http.request(config, (res) => {
247+
if (res.statusCode !== 200) {
248+
reject(new Error(`statusCode: ${res.statusCode}`));
249+
}
250+
res.on('data', () => {});
251+
res.on('end', resolve);
252+
});
253+
254+
req.on('error', (error) => {
255+
reject(error);
256+
});
257+
258+
const postData = JSON.stringify({
259+
database: `projects/${options.projectId}/databases/(default)`,
260+
});
261+
262+
req.setHeader('Content-Length', postData.length);
263+
264+
req.write(postData);
265+
req.end();
266+
});
267+
}

0 commit comments

Comments
 (0)