Skip to content
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

Feature: Add get, modify and subscribe methods to Firestore #6

Merged
merged 1 commit into from
Aug 9, 2024
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
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"no-obj-calls": 2,
"no-octal": 2,
"no-prototype-builtins": 2,
"no-redeclare": 2,
"no-redeclare": "off",
"no-regex-spaces": 2,
"no-self-assign": 2,
"no-setter-return": 2,
Expand Down
129 changes: 124 additions & 5 deletions src/lib/firebase/firestore/firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,41 @@
* limitations under the License.
*/

import { FirebaseApp } from "@firebase/app";
import { getFirestore, Firestore as Database } from "@firebase/firestore";
import { App } from "firebase-admin/app";
import { getFirestore as adminGetFirestore, Firestore as AdminDatabase } from "firebase-admin/firestore";
import {
getFirestore as adminGetFirestore,
SetOptions,
type Firestore as AdminDatabase,
} from "firebase-admin/firestore";
import { FirebaseApp } from "@firebase/app";
import {
getFirestore,
Firestore as Database,
disableNetwork,
enableNetwork,
getDocs,
DocumentReference,
getDoc,
onSnapshot,
setDoc,
updateDoc,
deleteDoc,
} from "@firebase/firestore";

import { FirestoreError } from "./error";
import { DataSnapshot, ErrorCallback, QueryConfig, QueryMethod, SubscribeCallback, Unsubscribe } from "./types";
import { documentFrom, queryFrom, Snapshot } from "./utils";
import { Client } from "../client";

/**
* Class representing a Firestore database.
* @remarks Firestore has not a real connection state, so use the RTDB connection state instead.
* See {@link https://firebase.google.com/docs/firestore/rtdb-vs-firestore?hl=en#presence | Firestore vs RTDB} presence comparison.
* See also the simulated {@link https://firebase.google.com/docs/firestore/solutions/presence | Firestore presence} example.
*/
export class Firestore {
private _database!: AdminDatabase | Database;
private _isOffline: boolean = false;

constructor(public readonly client: Client) {
if (!(client instanceof Client)) throw new TypeError("Firestore must be instantiated with Client as parameter");
Expand All @@ -35,6 +61,10 @@ export class Firestore {
return this._database;
}

public get offline(): boolean {
return this._isOffline;
}

private getDatabase() {
if (!this.client.app || !this.client.clientInitialised)
throw new FirestoreError("Firestore is called before the Client is initialized");
Expand All @@ -46,10 +76,99 @@ export class Firestore {

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
protected isAdminApp(app: App | FirebaseApp): app is App {
private isAdmin(db: AdminDatabase | Database): db is AdminDatabase {
if (this.client.admin === undefined) throw new FirestoreError("Property 'admin' missing in App class");
return this.client.admin;
}

// TODO: add methods for querying
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
private isAdminApp(app: App | FirebaseApp): app is App {
if (this.client.admin === undefined) throw new FirestoreError("Property 'admin' missing in App class");
return this.client.admin;
}

public goOffline(): Promise<void> {
this._isOffline = true;
// TODO: this._database.terminate() kill the instance
return this._database instanceof Database ? disableNetwork(this._database) : Promise.resolve();
}

public goOnline(): Promise<void> {
this._isOffline = false;
// TODO: How to re-use the database after `terminate()`
if (this._database instanceof Database) {
return enableNetwork(this._database);
}

return Promise.resolve();
}

public async get(config: QueryConfig): Promise<DataSnapshot> {
if (this.isAdmin(this._database)) {
const snapshot = await queryFrom(this._database, config).get();

return Snapshot.from(snapshot);
}

const query = queryFrom(this._database, config);

if (query instanceof DocumentReference) {
return Snapshot.from(await getDoc(query));
}

return Snapshot.from(await getDocs(query));
}

// For autocomple - TODO listDocuments
public async listCollections(): Promise<Array<string>> {
if (this.isAdmin(this._database)) {
const collections = await this._database.listCollections();
return collections.map((collection) => collection.id);
}

// TODO: Firebase JS don't have listCollections function
return Promise.resolve([]);
}

public async modify(method: QueryMethod, config: QueryConfig, value?: object, options: SetOptions = {}) {
switch (method) {
case "set":
if (!value || typeof value !== "object") throw new TypeError("Value to write must be an object");
if (this.isAdmin(this._database)) {
return documentFrom(this._database, config).set(value, options);
}
return setDoc(documentFrom(this._database, config), value, options);
case "update":
if (!value || typeof value !== "object") throw new TypeError("Value to write must be an object");
if (this.isAdmin(this._database)) {
return documentFrom(this._database, config).update(value);
}
return updateDoc(documentFrom(this._database, config), value);
case "delete":
if (this.isAdmin(this._database)) {
return documentFrom(this._database, config).delete();
}
return deleteDoc(documentFrom(this._database, config));
default:
throw new Error(`Write method should be one of "set", "update" or "delete"`);
}
}

public subscribe(config: QueryConfig, callback: SubscribeCallback, errorCallback?: ErrorCallback): Unsubscribe {
if (this.isAdmin(this._database)) {
return queryFrom(this._database, config).onSnapshot(
(snapshot) => callback(Snapshot.from(snapshot)),
errorCallback
);
}

const query = queryFrom(this._database, config);

if (query instanceof DocumentReference) {
return onSnapshot(query, (snapshot) => callback(Snapshot.from(snapshot)), errorCallback);
}

return onSnapshot(query, (snapshot) => callback(Snapshot.from(snapshot)), errorCallback);
}
}
4 changes: 3 additions & 1 deletion src/lib/firebase/firestore/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@
* limitations under the License.
*/

export * from "./firestore";
export * from "./error";
export * from "./firestore";
export * from "./types";
export * from "./utils";
72 changes: 72 additions & 0 deletions src/lib/firebase/firestore/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @license
* Copyright 2023 Gauthier Dandele
*
* 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 { DocumentChangeType, DocumentData, OrderByDirection, WhereFilterOp } from "firebase-admin/firestore";

export type DocumentId = string;

export interface DocumentChange {
id: DocumentId;
doc: DocumentData;
newIndex: number;
oldIndex: number;
type: DocumentChangeType;
}

export interface CollectionData {
changes: Array<DocumentChange>;
docs: Record<DocumentId, DocumentData>;
size: number;
}

export type DataSnapshot = CollectionData | DocumentData | null;

export type SubscribeCallback = (snapshot: DataSnapshot) => void;
export type ErrorCallback = (error: Error) => void;
export type Unsubscribe = () => void;

export interface Constraint {
endAt?: unknown;
endBefore?: unknown;
limitToFirst?: number;
limitToLast?: number;
orderBy?: { fieldPath: string; direction?: OrderByDirection };
offset?: number;
select?: string | Array<string>;
startAfter?: unknown;
startAt?: unknown;
where?: { fieldPath: string; filter: WhereFilterOp; value: unknown };
}

export interface QueryConfig {
collection?: string;
collectionGroup?: string;
constraints?: Constraint;
document?: string;
}

export type QueryMethod = "delete" | "set" | "update";

interface SetMergeOption {
merge?: boolean;
}

interface SetMergeFieldsOption {
mergeFields?: Array<string>;
}

export type SetOptions = SetMergeOption | SetMergeFieldsOption;
Loading