Skip to content

added method to clear all firestore data #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ lib
.npmrc
.vscode
*.tgz
.tmp
.tmp
*.log
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
"pretest": "node_modules/.bin/tsc",
"test": "mocha .tmp/spec/index.spec.js",
"posttest": "npm run lint && rm -rf .tmp",
"preintegrationTest": "node_modules/.bin/tsc",
"integrationTest": "firebase emulators:exec --project=not-a-project --only firestore 'mocha .tmp/spec/integration/**/*.spec.js'",
"postintegrationTest": "rm -rf .tmp",
"format": "prettier --check '**/*.{json,ts,yml,yaml}'",
"format:fix": "prettier --write '**/*.{json,ts,yml,yaml}'"
},
Expand Down Expand Up @@ -44,6 +47,7 @@
"chai": "^4.2.0",
"firebase-admin": "~8.9.0",
"firebase-functions": "^3.3.0",
"firebase-tools": "^8.9.2",
"mocha": "^6.2.2",
"prettier": "^1.19.1",
"sinon": "^7.5.0",
Expand Down
44 changes: 44 additions & 0 deletions spec/integration/providers/firestore.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { expect } from 'chai';
import { firestore, initializeApp } from 'firebase-admin';
import fft = require('../../../src/index');

describe('providers/firestore', () => {
before(() => {
initializeApp();
});

it('clears database with clearFirestoreData', async () => {
const test = fft({ projectId: 'not-a-project' });
const db = firestore();

await Promise.all([
db
.collection('test')
.doc('doc1')
.set({}),
db
.collection('test')
.doc('doc1')
.collection('test')
.doc('doc2')
.set({}),
]);

await test.firestore.clearFirestoreData({ projectId: 'not-a-project' });

const docs = await Promise.all([
db
.collection('test')
.doc('doc1')
.get(),
db
.collection('test')
.doc('doc1')
.collection('test')
.doc('doc2')
.get(),
]);
expect(docs[0].exists).to.be.false;
expect(docs[1].exists).to.be.false;
});
});
57 changes: 57 additions & 0 deletions src/providers/firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import { has, get, isEmpty, isPlainObject, mapValues } from 'lodash';

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

import * as http from 'http';

/** Optional parameters for creating a DocumentSnapshot. */
export interface DocumentSnapshotOptions {
/** ISO timestamp string for the snapshot was read, default is current time. */
Expand Down Expand Up @@ -214,3 +216,58 @@ export function objectToValueProto(data: object) {

return mapValues(data, encodeHelper);
}

const FIRESTORE_ADDRESS_ENVS = [
'FIRESTORE_EMULATOR_HOST',
'FIREBASE_FIRESTORE_EMULATOR_ADDRESS',
];

const FIRESTORE_ADDRESS = FIRESTORE_ADDRESS_ENVS.reduce(
(addr, name) => process.env[name] || addr,
'localhost:8080'
);
const FIRESTORE_PORT = FIRESTORE_ADDRESS.split(':')[1];

/** Clears all data in firestore. Works only in offline mode.
*/
export function clearFirestoreData(options: { projectId: string } | string) {
return new Promise((resolve, reject) => {
let projectId;

if (typeof options === 'string') {
projectId = options;
} else if (typeof options === 'object' && has(options, 'projectId')) {
projectId = options.projectId;
} else {
throw new Error('projectId not specified');
}

const config = {
method: 'DELETE',
hostname: 'localhost',
port: FIRESTORE_PORT,
path: `/emulator/v1/projects/${projectId}/databases/(default)/documents`,
};

const req = http.request(config, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`statusCode: ${res.statusCode}`));
}
res.on('data', () => {});
res.on('end', resolve);
});

req.on('error', (error) => {
reject(error);
});

const postData = JSON.stringify({
database: `projects/${projectId}/databases/(default)`,
});

req.setHeader('Content-Length', postData.length);

req.write(postData);
req.end();
});
}