Skip to content

Commit

Permalink
Refactoring to firebase v9
Browse files Browse the repository at this point in the history
  • Loading branch information
amilosmanli committed Mar 11, 2023
1 parent f9fe702 commit beba28b
Show file tree
Hide file tree
Showing 43 changed files with 3,691 additions and 4,273 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ src/**/*.js
.rts*
TEST.config.ts
FIREBASE_CONFIG.js

database-debug.log
firestore-debug.log
3 changes: 3 additions & 0 deletions firebase.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"storage": {
"rules": "storage.rules"
},
"emulators": {
"firestore": {
"port": 8080
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"@types/react": "^18.0.9",
"@types/react-router-dom": "^5.3.3",
"@types/rx": "^4.1.1",
"firebase": "^9.8.1",
"firebase": "^9.15.0",
"firebase-tools": "11.x",
"gulp": "^4.0.2",
"jest": "^23.6.0",
Expand Down
2 changes: 1 addition & 1 deletion src/misc/document-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ export function parseFireStoreDocument<T extends ra.Record>(
const result = translateDocFromFirestore(data);
const dataWithRefs = applyRefDocs(result.parsedDoc, result.refdocs);
// React Admin requires an id field on every document,
// So we can just using the firestore document id
// So we can just use the firestore document id
return { id: doc.id, ...dataWithRefs } as T;
}
65 changes: 41 additions & 24 deletions src/misc/firebase-models.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,51 @@
import firebase from 'firebase/compat/app';
import 'firebase/compat/storage';
import { FirebaseApp } from 'firebase/app';
import { Auth, User, UserCredential } from 'firebase/auth';
import {
CollectionReference,
DocumentData,
DocumentReference,
DocumentSnapshot,
FieldValue,
Firestore,
OrderByDirection,
Query,
QueryDocumentSnapshot,
WriteBatch,
} from 'firebase/firestore';
import {
FirebaseStorage,
StorageReference,
TaskState,
UploadTask,
UploadTaskSnapshot,
} from 'firebase/storage';

export type FireUser = firebase.User;
export type FireApp = firebase.app.App;
export type FireUser = User;
export type FireApp = FirebaseApp;

export type FireStorage = firebase.storage.Storage;
export type FireStorageReference = firebase.storage.Reference;
export type FireUploadTaskSnapshot = firebase.storage.UploadTaskSnapshot;
export type FireUploadTask = firebase.storage.UploadTask;
export type FireStorage = FirebaseStorage;
export type FireStorageReference = StorageReference;
export type FireUploadTaskSnapshot = UploadTaskSnapshot;
export type FireUploadTask = UploadTask;
export type FireStoragePutFileResult = {
task: FireUploadTask;
taskResult: Promise<FireUploadTaskSnapshot>;
downloadUrl: Promise<string>;
};

export type FireAuth = firebase.auth.Auth;
export type FireAuthUserCredentials = firebase.auth.UserCredential;
export type FireAuth = Auth;
export type FireAuthUserCredentials = UserCredential;

export type FireStore = firebase.firestore.Firestore;
export type FireStoreBatch = firebase.firestore.WriteBatch;
export type FireStoreTimeStamp = firebase.firestore.FieldValue;
export type FireStoreDocumentRef = firebase.firestore.DocumentReference;
export type FireStoreDocumentSnapshot =
firebase.firestore.DocumentSnapshot<firebase.firestore.DocumentData>;
export type FireStoreCollectionRef = firebase.firestore.CollectionReference;
export type FireStoreQueryDocumentSnapshot =
firebase.firestore.QueryDocumentSnapshot;
export type FireStoreQuery = firebase.firestore.Query;
export type FireStoreQueryOrder = firebase.firestore.OrderByDirection;
export type FireStore = Firestore;
export type FireStoreBatch = WriteBatch;
export type FireStoreTimeStamp = FieldValue;
export type FireStoreDocumentRef = DocumentReference;
export type FireStoreDocumentSnapshot = DocumentSnapshot<DocumentData>;
export type FireStoreCollectionRef = CollectionReference;
export type FireStoreQueryDocumentSnapshot = QueryDocumentSnapshot;
export type FireStoreQuery = Query;
export type FireStoreQueryOrder = OrderByDirection;

export const TASK_PAUSED = firebase.storage.TaskState.PAUSED;
export const TASK_RUNNING = firebase.storage.TaskState.RUNNING;
export const TASK_CANCELED = firebase.storage.TaskState.CANCELED;
export const TASK_PAUSED = 'paused' as TaskState;
export const TASK_RUNNING = 'running' as TaskState;
export const TASK_CANCELED = 'cancelled' as TaskState;
4 changes: 2 additions & 2 deletions src/misc/messageTypes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FireStoreCollectionRef } from './firebase-models';
import { FireStoreCollectionRef, FireStoreQuery } from './firebase-models';
import { ParsedRefDoc } from './internal.models';
// Firebase types
import { GetListParams } from './react-admin-models';
Expand All @@ -9,7 +9,7 @@ export namespace messageTypes {

export type CollectionQueryType = (
arg0: FireStoreCollectionRef
) => FireStoreCollectionRef;
) => FireStoreQuery;

export interface IParamsGetOne {
id: string;
Expand Down
1 change: 1 addition & 0 deletions src/misc/status-code-translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { logError } from './logger';

// tslint:disable-next-line:max-line-length
// - https://github.com/firebase/firebase-js-sdk/blob/9f109f85ad0d99f6c13e68dcb549a0b852e35a2a/packages/functions/src/api/error.ts
export function retrieveStatusTxt(status: number): 'ok' | 'unauthenticated' {
// Make sure any successful status is OK.
Expand Down
17 changes: 10 additions & 7 deletions src/misc/translate-from-firestore.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getDownloadURL, ref } from 'firebase/storage';
import { has, set } from 'lodash';
import { IFirebaseWrapper } from 'providers/database';
import { FireStoreDocumentRef } from './firebase-models';
Expand Down Expand Up @@ -56,9 +57,12 @@ export function recusivelyCheckObjectValue(
}
const isDocumentReference = isInputADocReference(input);
if (isDocumentReference) {
const ref = input as FireStoreDocumentRef;
result.refdocs.push({ fieldPath: fieldPath, refDocPath: ref.path });
return ref.id;
const documentReference = input as FireStoreDocumentRef;
result.refdocs.push({
fieldPath: fieldPath,
refDocPath: documentReference.path,
});
return documentReference.id;
}
const isObject = typeof input === 'object';
if (isObject) {
Expand Down Expand Up @@ -98,10 +102,9 @@ export const recursivelyMapStorageUrls = async (
const isFileField = has(fieldValue, 'src');
if (isFileField) {
try {
const src = await fireWrapper
.storage()
.ref(fieldValue.src)
.getDownloadURL();
const src = await getDownloadURL(
ref(fireWrapper.fireStorage(), fieldValue.src)
);
return {
...fieldValue,
src,
Expand Down
30 changes: 16 additions & 14 deletions src/providers/commands/Create.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { doc, getDoc, setDoc } from 'firebase/firestore';
import { log } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
Expand All @@ -14,36 +15,37 @@ export async function Create<T extends ra.Record>(
log('Create', { hasOverridenDocId });
if (hasOverridenDocId) {
const overridenId = params.data.id;
const exists = (await r.collection.doc(overridenId).get()).exists;
const exists = (await getDoc(doc(r.collection, overridenId))).exists();
if (exists) {
throw new Error(
`the id:"${overridenId}" already exists, please use a unique string if overriding the 'id' field`
);
}
const docData = await client.parseDataAndUpload(

const createData = await client.parseDataAndUpload(
r,
overridenId,
params.data
);
if (!overridenId) {
throw new Error('id must be a valid string');
}
const documentObj = { ...docData };
client.checkRemoveIdField(documentObj, overridenId);
await client.addCreatedByFields(documentObj);
await client.addUpdatedByFields(documentObj);
const documentObjTransformed = client.transformToDb(
const createDocObj = { ...createData };
client.checkRemoveIdField(createDocObj, overridenId);
await client.addCreatedByFields(createDocObj);
await client.addUpdatedByFields(createDocObj);
const createDocObjTransformed = client.transformToDb(
resourceName,
documentObj,
createDocObj,
overridenId
);
log('Create', { documentObj });
await r.collection
.doc(overridenId)
.set(documentObjTransformed, { merge: false });
log('Create', { docObj: createDocObj });
await setDoc(doc(r.collection, overridenId), createDocObjTransformed, {
merge: false,
});
return {
data: {
...documentObjTransformed,
...createDocObjTransformed,
id: overridenId,
},
};
Expand All @@ -55,7 +57,7 @@ export async function Create<T extends ra.Record>(
await client.addCreatedByFields(docObj);
await client.addUpdatedByFields(docObj);
const docObjTransformed = client.transformToDb(resourceName, docObj, newId);
await r.collection.doc(newId).set(docObjTransformed, { merge: false });
await setDoc(doc(r.collection, newId), docObjTransformed, { merge: false });
return {
data: {
...docObjTransformed,
Expand Down
14 changes: 7 additions & 7 deletions src/providers/commands/Delete.Soft.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc, updateDoc } from 'firebase/firestore';
import { log, logError } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
import { FireClient } from '../database';

export async function DeleteSoft<T extends ra.Record>(
resourceName: string,
Expand All @@ -13,12 +14,11 @@ export async function DeleteSoft<T extends ra.Record>(
log('DeleteSoft', { resourceName, resource: r, params });
const docObj = { deleted: true };
await client.addUpdatedByFields(docObj);
r.collection
.doc(id)
.update(docObj)
.catch((error) => {
logError('DeleteSoft error', { error });
});

updateDoc(doc(r.collection, id), docObj).catch((error) => {
logError('DeleteSoft error', { error });
});

return {
data: params.previousData as T,
};
Expand Down
4 changes: 3 additions & 1 deletion src/providers/commands/Delete.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { deleteDoc, doc } from 'firebase/firestore';
import { log } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
Expand All @@ -16,7 +17,8 @@ export async function Delete<T extends ra.Record>(
log('apiDelete', { resourceName, resource: r, params });
try {
const id = params.id + '';
await r.collection.doc(id).delete();

await deleteDoc(doc(r.collection, id));
} catch (error) {
throw new Error(error as any);
}
Expand Down
12 changes: 5 additions & 7 deletions src/providers/commands/DeleteMany.Soft.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc, updateDoc } from 'firebase/firestore';
import { log, logError } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
import { FireClient } from '../database';

export async function DeleteManySoft(
resourceName: string,
Expand All @@ -16,12 +17,9 @@ export async function DeleteManySoft(
const idStr = id + '';
const docObj = { deleted: true };
await client.addUpdatedByFields(docObj);
r.collection
.doc(idStr)
.update(docObj)
.catch((error) => {
logError('apiSoftDeleteMany error', { error });
});
updateDoc(doc(r.collection, idStr), docObj).catch((error) => {
logError('apiSoftDeleteMany error', { error });
});
return idStr;
})
);
Expand Down
6 changes: 4 additions & 2 deletions src/providers/commands/DeleteMany.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc } from 'firebase/firestore';
import { log } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
import { FireClient } from '../database';
import { DeleteManySoft } from './DeleteMany.Soft';

export async function DeleteMany(
Expand All @@ -18,10 +19,11 @@ export async function DeleteMany(
const batch = fireWrapper.dbCreateBatch();
for (const id of params.ids) {
const idStr = id + '';
const docToDelete = r.collection.doc(idStr);
const docToDelete = doc(r.collection, idStr);
batch.delete(docToDelete);
returnData.push(id);
}

try {
await batch.commit();
} catch (error) {
Expand Down
5 changes: 3 additions & 2 deletions src/providers/commands/Update.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc, updateDoc } from 'firebase/firestore';
import { log } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
import { FireClient } from '../database';

export async function Update<T extends ra.Record>(
resourceName: string,
Expand All @@ -18,7 +19,7 @@ export async function Update<T extends ra.Record>(
client.checkRemoveIdField(docObj, id);
await client.addUpdatedByFields(docObj);
const docObjTransformed = client.transformToDb(resourceName, docObj, id);
await r.collection.doc(id).update(docObjTransformed);
await updateDoc(doc(r.collection, id), docObjTransformed);
return {
data: {
...data,
Expand Down
5 changes: 3 additions & 2 deletions src/providers/commands/UpdateMany.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc, updateDoc } from 'firebase/firestore';
import { log } from '../../misc';
import * as ra from '../../misc/react-admin-models';
import { FireClient } from '../database/FireClient';
import { FireClient } from '../database';

export async function UpdateMany(
resourceName: string,
Expand All @@ -25,7 +26,7 @@ export async function UpdateMany(
docObj,
idStr
);
await r.collection.doc(idStr).update(docObjTransformed);
await updateDoc(doc(r.collection, idStr), docObjTransformed);
return {
...data,
id: idStr,
Expand Down
4 changes: 2 additions & 2 deletions src/providers/database/FireClient.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { doc } from 'firebase/firestore';
import { get, set } from 'lodash';
import {
AddCreatedByFields,
AddUpdatedByFields,
dispatch,
IFirestoreLogger,
joinPaths,
log,
logError,
parseStoragePath,
Expand Down Expand Up @@ -51,7 +51,7 @@ export class FireClient {
if (!data) {
return data;
}
const docPath = r.collection.doc(id).path;
const docPath = doc(r.collection, id).path;

const result = translateDocToFirestore(data);
const uploads = result.uploads;
Expand Down
Loading

0 comments on commit beba28b

Please sign in to comment.