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

DONT MERGE: Using firestore as local db #27

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
1 change: 0 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"editor.formatOnSave": true,
"editor.codeLens": false,
"editor.tabSize": 2,
"files.insertFinalNewline": true,
"javascript.preferences.importModuleSpecifier": "relative",
"typescript.preferences.importModuleSpecifier": "relative",
Expand Down
24 changes: 23 additions & 1 deletion AppInit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,46 @@ import React from 'react';
import { useDispatch } from 'react-redux';
import { Style } from './styles/style';
import { setTheme } from './store/actions/actions';
import auth from '@react-native-firebase/auth';

interface AppInitProps {
children: React.ReactElement;
}

const AuthenticateUser = async () => {
try {
const response = await auth().signInAnonymously();
return response;
} catch (error) {
if (error.code === 'auth/operation-not-allowed') {
console.log('Enable anonymous in your firebase console.');
}

console.error(error);
}
};

const AppInit: React.FC<AppInitProps> = props => {
const [isInitialized, setIsInitialized] = React.useState(false);
const [currentUser, setCurrentUser] = React.useState<string | null>('');
const dispatch = useDispatch();

React.useEffect(() => {
const fetchConfigFromStorage = async () => {
await Style.computeCurrentTheme();
dispatch(setTheme(Style.getCurrentTheme()));

const user = await AuthenticateUser();
if (user) {
setCurrentUser(user.user.displayName);
console.log(user.user.uid);
}

setIsInitialized(true);
};

fetchConfigFromStorage();
}, [dispatch, setIsInitialized]);
}, [currentUser, dispatch, setIsInitialized]);

if (isInitialized) {
return props.children;
Expand Down
1 change: 1 addition & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
apply plugin: "com.android.application"
apply plugin: "com.google.gms.google-services"

import com.android.build.OutputFile

Expand Down
40 changes: 40 additions & 0 deletions android/app/google-services.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"project_info": {
"project_number": "301938801516",
"firebase_url": "https://rn-fitbook.firebaseio.com",
"project_id": "rn-fitbook",
"storage_bucket": "rn-fitbook.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:301938801516:android:e6786ea7423cd9d93fd149",
"android_client_info": {
"package_name": "com.fitbook"
}
},
"oauth_client": [
{
"client_id": "301938801516-klgq32le15hukm6q20mb94lu8k3j6vjt.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyD7_AwC14DOmUicmaqyYPmoJhLZXJ-f4f0"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "301938801516-klgq32le15hukm6q20mb94lu8k3j6vjt.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}
1 change: 1 addition & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ buildscript {
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.3")
classpath("com.google.gms:google-services:4.3.3")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Expand Down
15 changes: 14 additions & 1 deletion commonlib/database/IDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@ export default interface IDatabase {
params?: Record<string, any>,
query?: Record<string, any>
) => Promise<any[] | ServiceResponse>;
GetListAsync: () => Promise<any[] | ServiceResponse>;
GetListAsync: (params?: IQueryParams[]) => Promise<any[] | ServiceResponse>;
PostAsync: (data: Record<string, any>) => Promise<any>;
}

export enum Operators {
EQUALS,
GREATERTHANOREQUALTO,
LESSTHANOREQUALTO,
NOTEQUALTO,
}

export interface IQueryParams {
key: string;
operator: Operators;
value: string | number;
}
12 changes: 8 additions & 4 deletions commonlib/services/resistance.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright FitBook

import IDatabase from '../database/IDatabase';
import IDatabase, { IQueryParams, Operators } from '../database/IDatabase';
import { CreateResistanceModel, ResistanceModel } from '../models/ResistanceModel';
import ServiceResponse, { isServiceResponse } from '../models/ServiceResponse';

Expand All @@ -22,10 +22,14 @@ export default class ResistanceService {
return r;
}

public async getResistanceListByUserId(type: string, userId: string): Promise<ResistanceModel[] | ServiceResponse> {
const params = { type: type.toLocaleUpperCase() };
public async getResistanceListByUserId(type: string): Promise<ResistanceModel[] | ServiceResponse> {
const param: IQueryParams = {
key: 'type',
value: type.toLocaleUpperCase(),
operator: Operators.EQUALS,
};

const r: ResistanceModel[] | ServiceResponse = await this.db.GetListByUserId(userId, params);
const r: ResistanceModel[] | ServiceResponse = await this.db.GetListAsync([param]);

if (isServiceResponse(r)) {
return r;
Expand Down
3 changes: 1 addition & 2 deletions components/CreateResistance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,8 @@ const ResistanceInput: React.FC<ResistanceInputProps> = props => {

const addLog = () => {
let timestamp = getTimestamp();
let id = '5dfecbdd39d8760019968d04';
const newResistance: CreateResistanceModel = {
userId: id,
userId: '',
type: props.name,
createdDate: new Date(timestamp),
weight,
Expand Down
24 changes: 3 additions & 21 deletions domainlogic/controllers/resistance.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,16 @@
// Copyright FitBook

import { CreateResistanceModel, ResistanceModel, ResistanceTypes } from '../../commonlib/models/ResistanceModel';
import AsyncStorage from '@react-native-community/async-storage';
import Storage from '../../constants/storage';
import ResistanceService from '../../commonlib/services/resistance';
import ServiceResponse from '../../commonlib/models/ServiceResponse';
import LocalStorageDB from '../database/localStorageDB';
import MongoDb from '../database/mongoDb';
import FirebaseDB from '../database/FirebaseDB';

export default class ResistanceController {
private resistanceSvc: ResistanceService;
private static readonly TABLE_NAME: string = 'resistance';
private static readonly ENDPOINT = '/api/resistance';
private static readonly TABLE_NAME: string = 'Resistances';

constructor() {
this.resistanceSvc = new ResistanceService(new LocalStorageDB(ResistanceController.TABLE_NAME));
this.initialize();
}

public async initialize() {
let allowRemoteStorage = true;
AsyncStorage.getItem(Storage.ALLOW_REMOTE_STORAGE).then(value => {
if (value) {
allowRemoteStorage = !!value;
}

this.resistanceSvc = allowRemoteStorage
? new ResistanceService(new MongoDb(ResistanceController.ENDPOINT))
: new ResistanceService(new LocalStorageDB(ResistanceController.TABLE_NAME));
});
this.resistanceSvc = new ResistanceService(new FirebaseDB(ResistanceController.TABLE_NAME));
}

public async createResistance(data: CreateResistanceModel): Promise<ResistanceModel | ServiceResponse> {
Expand Down
100 changes: 100 additions & 0 deletions domainlogic/database/FirebaseDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright FitBook
import firestore from '@react-native-firebase/firestore';
import auth from '@react-native-firebase/auth';
import IDatabase, { IQueryParams, Operators } from '../../commonlib/database/IDatabase';
import ServiceResponse from '../../commonlib/models/ServiceResponse';

export default class FirebaseDB implements IDatabase {
private tableName: string;
private currentUserId: string | undefined;
private isOffline: boolean;

constructor(tableName: string) {
this.tableName = tableName;
this.currentUserId = auth().currentUser?.uid;
this.isOffline = false;
}
public async PostAsync(data: Record<string, any>) {
if (!this.isOffline) this.setOffline();

try {
data.userId = this.currentUserId;
const result = await firestore().collection(this.tableName).add(data);
const value = await result.get();
return value;
} catch (error) {
return new ServiceResponse();
}
}

public async GetAsync(id: string): Promise<Record<string, any>> {
if (!this.isOffline) this.setOffline();

try {
const querySnapshot = await firestore().collection(this.tableName).where('id', '==', id).get();
return querySnapshot.docs;
} catch (error) {
console.error('Something went wrong', error);
return new ServiceResponse();
}
}

public async GetListAsync(params?: IQueryParams[]): Promise<any[] | ServiceResponse> {
if (!this.isOffline) this.setOffline();

try {
let query = firestore().collection(this.tableName).where('userId', '==', this.currentUserId);

if (params) {
params.forEach(param => {
query.where(param.key, this.GetOperator(param.operator), param.value);
});
}
const snapshot = await query.get();

let data: any[] = [];
snapshot.forEach(doc => {
data.push(doc.data());
});

return data;
} catch (error) {
console.error('Something went wrong', error);
return new ServiceResponse();
}
}

public async GetListByUserId(_userId: string, _params?: Record<string, any>): Promise<any[] | ServiceResponse> {
try {
const snapshot = await firestore().collection(this.tableName).get();
return snapshot.docs;
} catch (error) {
console.error('Something went wrong', error);
return new ServiceResponse();
}
}

private GetOperator(operator: Operators): any {
switch (operator) {
case Operators.EQUALS:
return '==';
case Operators.GREATERTHANOREQUALTO:
return '>=';
case Operators.LESSTHANOREQUALTO:
return '<=';
case Operators.NOTEQUALTO:
return '!=';
default:
return '==';
}
}

private async setOffline() {
try {
await firestore().enableNetwork();
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be disableNetwork() if u want to test offline feature

this.isOffline = true;
} catch (error) {
console.error('Unable to set device offline.', error);
}
}
}
5 changes: 5 additions & 0 deletions firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"react-native": {
"database_persistence_enabled": true
}
}
36 changes: 36 additions & 0 deletions ios/GoogleService-Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CLIENT_ID</key>
<string>301938801516-m0h0in8b7jdngt9j0ucupvsfa5h48vqb.apps.googleusercontent.com</string>
<key>REVERSED_CLIENT_ID</key>
<string>com.googleusercontent.apps.301938801516-m0h0in8b7jdngt9j0ucupvsfa5h48vqb</string>
<key>API_KEY</key>
<string>AIzaSyAuhEOM76Zd5fz50w037TQXulReJu9p22Y</string>
<key>GCM_SENDER_ID</key>
<string>301938801516</string>
<key>PLIST_VERSION</key>
<string>1</string>
<key>BUNDLE_ID</key>
<string>org.fitbook.fitbook</string>
<key>PROJECT_ID</key>
<string>rn-fitbook</string>
<key>STORAGE_BUCKET</key>
<string>rn-fitbook.appspot.com</string>
<key>IS_ADS_ENABLED</key>
<false></false>
<key>IS_ANALYTICS_ENABLED</key>
<false></false>
<key>IS_APPINVITE_ENABLED</key>
<true></true>
<key>IS_GCM_ENABLED</key>
<true></true>
<key>IS_SIGNIN_ENABLED</key>
<true></true>
<key>GOOGLE_APP_ID</key>
<string>1:301938801516:ios:55c56b3359ba92563fd149</string>
<key>DATABASE_URL</key>
<string>https://rn-fitbook.firebaseio.com</string>
</dict>
</plist>
Loading