Skip to content

Commit

Permalink
Prettify and lint (no-deploy-lib)
Browse files Browse the repository at this point in the history
  • Loading branch information
amilosmanli authored and benwinding committed Jan 30, 2023
1 parent 5595b3c commit f814216
Show file tree
Hide file tree
Showing 49 changed files with 624 additions and 535 deletions.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@
"gulp": "^4.0.2",
"jest": "^23.6.0",
"microbundle": "^0.15.0",
"prettier": "^2.8.3",
"ra-core": "3.10.0",
"ts-jest": "^25",
"tslint": "^5.16.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "4.5.5"
},
"homepage": "https://github.com/benwinding/react-admin-firebase",
Expand All @@ -43,7 +45,9 @@
"start-emulator": "yarn firebase emulators:start --only firestore",
"test": "yarn firebase emulators:exec \"yarn jest --forceExit --detectOpenHandles\"",
"test-watch": "yarn firebase emulators:exec \"yarn jest --watchAll --detectOpenHandles\"",
"lint": "tslint -c tslint.json 'src/**/*.ts'"
"tslint": "tslint -c tslint.json 'src/**/*.ts' 'tests/**/*.ts'",
"prettify": "prettier --write src tests",
"lint": "yarn prettify && yarn tslint"
},
"files": [
"dist",
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import { RAFirebaseOptions } from './providers/options';
export {
DataProvider as FirebaseDataProvider,
AuthProvider as FirebaseAuthProvider,
RAFirebaseOptions as RAFirebaseOptions
RAFirebaseOptions as RAFirebaseOptions,
};
20 changes: 11 additions & 9 deletions src/misc/dispatcher.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { log } from './logger';

export type DispatchEvent =
'FILE_UPLOAD_WILL_START' |
'FILE_UPLOAD_PROGRESS' |
'FILE_UPLOAD_PAUSED' |
'FILE_UPLOAD_RUNNING' |
'FILE_UPLOAD_CANCELED' |
'FILE_UPLOAD_COMPLETE' |
'FILE_SAVED';
| 'FILE_UPLOAD_WILL_START'
| 'FILE_UPLOAD_PROGRESS'
| 'FILE_UPLOAD_PAUSED'
| 'FILE_UPLOAD_RUNNING'
| 'FILE_UPLOAD_CANCELED'
| 'FILE_UPLOAD_COMPLETE'
| 'FILE_SAVED';

export function dispatch(
eventName: DispatchEvent,
Expand All @@ -16,10 +16,12 @@ export function dispatch(
): void {
const eventMonitor = document.getElementById('eventMonitor');
if (!eventMonitor) {
log(`eventMonitor not found to dispatch event ${eventName} for ${fileName}`);
log(
`eventMonitor not found to dispatch event ${eventName} for ${fileName}`
);
return;
}
const eventData = { fileName, data };
let event = new CustomEvent(eventName, { detail: eventData });
eventMonitor.dispatchEvent(event);
}
}
14 changes: 11 additions & 3 deletions src/misc/document-parser.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { FireStoreQueryDocumentSnapshot, FireStoreDocumentSnapshot } from './firebase-models';
import {
FireStoreQueryDocumentSnapshot,
FireStoreDocumentSnapshot,
} from './firebase-models';
import { logWarn } from './logger';
import { applyRefDocs, translateDocFromFirestore } from './translate-from-firestore';
import {
applyRefDocs,
translateDocFromFirestore,
} from './translate-from-firestore';
import * as ra from './react-admin-models';

export function parseFireStoreDocument<T extends ra.Record>(doc: FireStoreQueryDocumentSnapshot | FireStoreDocumentSnapshot | undefined): T {
export function parseFireStoreDocument<T extends ra.Record>(
doc: FireStoreQueryDocumentSnapshot | FireStoreDocumentSnapshot | undefined
): T {
if (!doc) {
logWarn('parseFireStoreDocument: no doc', { doc });
return {} as T;
Expand Down
12 changes: 7 additions & 5 deletions src/misc/firebase-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ export type FireStorageReference = firebase.storage.Reference;
export type FireUploadTaskSnapshot = firebase.storage.UploadTaskSnapshot;
export type FireUploadTask = firebase.storage.UploadTask;
export type FireStoragePutFileResult = {
task: FireUploadTask,
taskResult: Promise<FireUploadTaskSnapshot>,
downloadUrl: Promise<string>
task: FireUploadTask;
taskResult: Promise<FireUploadTaskSnapshot>;
downloadUrl: Promise<string>;
};

export type FireAuth = firebase.auth.Auth;
Expand All @@ -21,9 +21,11 @@ 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 FireStoreDocumentSnapshot =
firebase.firestore.DocumentSnapshot<firebase.firestore.DocumentData>;
export type FireStoreCollectionRef = firebase.firestore.CollectionReference;
export type FireStoreQueryDocumentSnapshot = firebase.firestore.QueryDocumentSnapshot;
export type FireStoreQueryDocumentSnapshot =
firebase.firestore.QueryDocumentSnapshot;
export type FireStoreQuery = firebase.firestore.Query;
export type FireStoreQueryOrder = firebase.firestore.OrderByDirection;

Expand Down
5 changes: 3 additions & 2 deletions src/misc/objectFlatten.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type SearchValues = {} | number | string | boolean | null ;
type SearchValues = {} | number | string | boolean | null;
type SearchValue = SearchValues | SearchValue[];

export interface SearchObj {
Expand All @@ -10,7 +10,8 @@ export function getFieldReferences(
value: {} | SearchValue
): SearchObj[] {
const isFalsy = !value;
const isSimple = isFalsy ||
const isSimple =
isFalsy ||
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean';
Expand Down
2 changes: 1 addition & 1 deletion src/misc/pathHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export function getAbsolutePath(
relativePath: string | null
): string {
if (!rootRef) {
return relativePath+'';
return relativePath + '';
}
if (!relativePath) {
throw new Error(
Expand Down
2 changes: 1 addition & 1 deletion src/misc/react-admin-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ export {
UpdateResult,
Identifier,
AuthProvider,
UserIdentity
UserIdentity,
} from 'ra-core';
2 changes: 1 addition & 1 deletion src/misc/status-code-translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function retrieveStatusCode(statusTxt: string): number {
const regexResult = /\[code\=([\w-]*)/g.exec(statusTxt);
const status = Array.isArray(regexResult) && regexResult[1];
if (!status) {
logError('unknown StatusCode ', {statusTxt});
logError('unknown StatusCode ', { statusTxt });
}
switch (status) {
case 'unauthenticated':
Expand Down
10 changes: 3 additions & 7 deletions src/misc/storage-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,11 @@ export function parseStoragePath(
fieldPath: string,
useFileName: boolean
): string {
const fileNameBits = rawFile instanceof File
? rawFile.name.split('.')
: [];
const fileNameBits = rawFile instanceof File ? rawFile.name.split('.') : [];

const fileExtension = !fileNameBits?.length
? ''
: '.' + fileNameBits.pop();
const fileExtension = !fileNameBits?.length ? '' : '.' + fileNameBits.pop();

return useFileName
? joinPaths(docPath, fieldPath, rawFile.name)
: joinPaths(docPath, fieldPath + fileExtension);
}
}
8 changes: 3 additions & 5 deletions src/misc/translate-from-firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,15 @@ export function recusivelyCheckObjectValue(
}

function isInputADocReference(input: any): boolean {
const isDocumentReference = typeof input.id === 'string' &&
const isDocumentReference =
typeof input.id === 'string' &&
typeof input.firestore === 'object' &&
typeof input.parent === 'object' &&
typeof input.path === 'string';
return isDocumentReference;
}

export function applyRefDocs(
doc: any,
refDocs: RefDocFound[]
) {
export function applyRefDocs(doc: any, refDocs: RefDocFound[]) {
refDocs.map((d) => {
set(doc, REF_INDENTIFIER + d.fieldPath, d.refDocPath);
});
Expand Down
23 changes: 10 additions & 13 deletions src/providers/AuthProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { RAFirebaseOptions } from './options';
import { FirebaseWrapper } from './database/firebase/FirebaseWrapper';
import {
AuthProvider as RaAuthProvider,
UserIdentity
UserIdentity,
} from '../misc/react-admin-models';
import { IFirebaseWrapper } from './database';
import { FireUser } from '../misc/firebase-models';
Expand Down Expand Up @@ -176,12 +176,9 @@ class AuthClient {

return token.token;
} catch (e) {
log(
'HandleGetJWTToken: no user is logged in or tokenResult error',
{
e,
}
);
log('HandleGetJWTToken: no user is logged in or tokenResult error', {
e,
});
return null;
}
}
Expand Down Expand Up @@ -216,12 +213,12 @@ export function AuthProvider(

export type ReactAdminFirebaseAuthProvider = RaAuthProvider & {
// Custom Functions
getAuthUser: () => Promise<FireUser>,
getJWTAuthTime: () => Promise<string | null>,
getJWTExpirationTime: () => Promise<string | null>,
getJWTSignInProvider: () => Promise<string | null>,
getJWTClaims: () => Promise<{ [key: string]: any; } | null>,
getJWTToken: () => Promise<string | null>
getAuthUser: () => Promise<FireUser>;
getJWTAuthTime: () => Promise<string | null>;
getJWTExpirationTime: () => Promise<string | null>;
getJWTSignInProvider: () => Promise<string | null>;
getJWTClaims: () => Promise<{ [key: string]: any } | null>;
getJWTToken: () => Promise<string | null>;
};

function VerifyAuthProviderArgs(
Expand Down
6 changes: 2 additions & 4 deletions src/providers/DataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
logger,
retrieveStatusCode,
logError,
MakeFirestoreLogger
MakeFirestoreLogger,
} from '../misc';
import * as ra from '../misc/react-admin-models';
import { RAFirebaseOptions } from './options';
Expand Down Expand Up @@ -75,9 +75,7 @@ export function DataProvider(
resource: string,
params: ra.GetManyReferenceParams
): Promise<ra.GetManyReferenceResult<RecordType>> {
return run(() =>
GetManyReference<RecordType>(resource, params, client)
);
return run(() => GetManyReference<RecordType>(resource, params, client));
},
update<RecordType extends ra.Record = ra.Record>(
resource: string,
Expand Down
16 changes: 13 additions & 3 deletions src/providers/commands/Create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,27 @@ export async function Create<T extends ra.Record>(
`the id:"${overridenId}" already exists, please use a unique string if overriding the 'id' field`
);
}
const docData = await client.parseDataAndUpload(r, overridenId, params.data);
const docData = 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(resourceName, documentObj, overridenId);
const documentObjTransformed = client.transformToDb(
resourceName,
documentObj,
overridenId
);
log('Create', { documentObj });
await r.collection.doc(overridenId).set(documentObjTransformed, { merge: false });
await r.collection
.doc(overridenId)
.set(documentObjTransformed, { merge: false });
return {
data: {
...documentObjTransformed,
Expand Down
14 changes: 8 additions & 6 deletions src/providers/commands/UpdateMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,18 @@ export async function UpdateMany(
log('UpdateMany', { resourceName, resource: r, params });
const ids = params.ids;
const returnData = await Promise.all(
ids.map(async id => {
const idStr = id+'';
ids.map(async (id) => {
const idStr = id + '';
const data = await client.parseDataAndUpload(r, idStr, params.data);
const docObj = { ...data };
client.checkRemoveIdField(docObj, idStr);
await client.addUpdatedByFields(docObj);
const docObjTransformed = client.transformToDb(resourceName, docObj, idStr);
await r.collection
.doc(idStr)
.update(docObjTransformed);
const docObjTransformed = client.transformToDb(
resourceName,
docObj,
idStr
);
await r.collection.doc(idStr).update(docObjTransformed);
return {
...data,
id: idStr,
Expand Down
34 changes: 24 additions & 10 deletions src/providers/database/FireClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { set, get } from 'lodash';
import { TASK_CANCELED, TASK_PAUSED, TASK_RUNNING } from '../../misc/firebase-models';
import {
TASK_CANCELED,
TASK_PAUSED,
TASK_RUNNING,
} from '../../misc/firebase-models';
import {
AddCreatedByFields,
AddUpdatedByFields,
Expand All @@ -9,7 +13,7 @@ import {
logError,
dispatch,
translateDocToFirestore,
parseStoragePath
parseStoragePath,
} from '../../misc';
import { RAFirebaseOptions } from '../options';
import { IFirebaseWrapper } from './firebase/IFirebaseWrapper';
Expand All @@ -32,7 +36,11 @@ export class FireClient {
}
}

public transformToDb(resourceName: string, documentData: any, docId: string): any {
public transformToDb(
resourceName: string,
documentData: any,
docId: string
): any {
if (typeof this.options.transformToDb === 'function') {
return this.options.transformToDb(resourceName, documentData, docId);
}
Expand All @@ -49,7 +57,12 @@ export class FireClient {
const uploads = result.uploads;
await Promise.all(
uploads.map(async (u) => {
const storagePath = parseStoragePath(u.rawFile, docPath, u.fieldDotsPath, !!this.options.useFileNamesInStorage);
const storagePath = parseStoragePath(
u.rawFile,
docPath,
u.fieldDotsPath,
!!this.options.useFileNamesInStorage
);
const link = await this.saveFile(storagePath, u.rawFile);
set(data, u.fieldDotsPath + '.src', link);
})
Expand All @@ -71,12 +84,16 @@ export class FireClient {
): Promise<string | undefined> {
log('saveFile() saving file...', { storagePath, rawFile });
try {
const { task, taskResult, downloadUrl } = this.fireWrapper.putFile(storagePath, rawFile);
const { task, taskResult, downloadUrl } = this.fireWrapper.putFile(
storagePath,
rawFile
);
const { name } = rawFile;
// monitor upload status & progress
dispatch('FILE_UPLOAD_WILL_START', name);
task.on('state_changed', (snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
log('Upload is ' + progress + '% done');
dispatch('FILE_UPLOAD_PROGRESS', name, progress);
switch (snapshot.state) {
Expand All @@ -98,10 +115,7 @@ export class FireClient {
// already handled by then
}
});
const [getDownloadURL] = await Promise.all([
downloadUrl,
taskResult,
]);
const [getDownloadURL] = await Promise.all([downloadUrl, taskResult]);
dispatch('FILE_UPLOAD_COMPLETE', name);
dispatch('FILE_SAVED', name);
log('saveFile() saved file', {
Expand Down
Loading

0 comments on commit f814216

Please sign in to comment.