Created
March 24, 2019 04:01
-
-
Save adrianosela/d88303c50b231832f972d3a1afb0e271 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { GiftedChat } from "react-native-gifted-chat"; | |
import { getAccessTokenFromStorage } from '../utils/Auth' | |
import firebaseSvc from "../utils/FirebaseSvc"; | |
export default class Chat extends React.Component { | |
state = { | |
messages: [] | |
}; | |
async componentWillMount() { | |
// hit api /chat_token to trade stored wrdup | |
// access token for firebase custom token | |
let firebaseToken; | |
const accessToken = await getAccessTokenFromStorage(); | |
try { | |
const checkResp = await axiosClient.get('/chat_token', { | |
headers: { | |
Authorization: `Bearer ${accessToken}`, | |
}, | |
}); | |
firebaseToken = checkResp.data.firebaseToken; | |
} catch ({ response, message }) { | |
if (response.status === 401) { | |
console.log('Error getting firebase ID token', response.status, message); | |
return; | |
} | |
} | |
// use token for login into firebase | |
const success_callback = (stuff) => console.log("[FIREBASE AUTH] SUCCESS"); | |
const failed_callback = (stuff) => console.log('[FIREBASE AUTH] FAILURE: ', stuff); | |
firebaseSvc.login(firebaseToken,success_callback, failed_callback); | |
} | |
render() { | |
return ( | |
<GiftedChat | |
messages={this.state.messages} | |
onSend={message => { | |
firebaseSvc.sendMessage(message); | |
}} | |
user={{ | |
_id: firebaseSvc.getUid(), | |
name: firebaseSvc.getUid() // FIXME: this.props.username | |
}} | |
/> | |
); | |
} | |
// MOUNTED: load messages on each new message | |
componentDidMount() { | |
firebaseSvc.loadMessages(message => { | |
this.setState(previousState => { | |
return { | |
messages: GiftedChat.append(previousState.messages, message) | |
}; | |
}); | |
}); | |
} | |
// UNMOUNT: Call the firebase service closer | |
componentWillUnmount() { | |
firebaseSvc.closeChat(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import firebase from "firebase"; | |
class FirebaseSvc { | |
uid = ""; | |
messagesRef = null; | |
// initialize Firebase Backend | |
constructor() { | |
if (!firebase.apps.length) { //avoid re-initializing | |
firebase.initializeApp({ | |
apiKey: "AIzaSyB-WtxcyGmf0wiF4Zgr7G37UiE6yzl4Rzs", | |
authDomain: "wrdupapp-d4be5.firebaseapp.com", | |
databaseURL: "https://wrdupapp-d4be5.firebaseio.com", | |
projectId: "wrdupapp-d4be5", | |
storageBucket: "wrdupapp-d4be5.appspot.com", | |
messagingSenderId: "6614415512" | |
}); | |
this.state = { | |
user: {} | |
} | |
} | |
} | |
login = async(token, success_callback, failed_callback) => { | |
await firebase.auth().signInWithCustomToken(token).then(success_callback, failed_callback); | |
this.state = {user: firebase.auth().currentUser}; | |
this.setUid(user.uid); | |
console.log("Firebase User:", this.state.user) | |
} | |
setUid(value) { | |
this.uid = value; | |
} | |
getUid() { | |
return this.uid; | |
} | |
// retrieve the messages from the Backend | |
loadMessages(callback) { | |
this.messagesRef = firebase.database().ref("messages"); | |
this.messagesRef.off(); //Detaches a callback previously attached with on() | |
const onReceive = data => { | |
const message = data.val(); | |
callback({ | |
_id: data.key, | |
text: message.text, | |
//createdAt: new Date(message.createdAt), | |
createdAt: message.createdAt, | |
user: { | |
_id: message.user._id, | |
name: message.user.name | |
} | |
}); | |
}; | |
var d = this.getLimit(); | |
console.log(d); | |
//Generates a new Query object limited to the last specific number of children. | |
//this.messagesRef.limitToLast(10).on("child_added", onReceive); | |
this.messagesRef | |
.orderByChild("createdAt") | |
//.startAt(d) | |
//.endAt("2017-11-27T06:51:47.851Z") | |
.on("child_added", onReceive); | |
} | |
// send a given message | |
sendMessage(message) { | |
//console.log(new Date(firebase.database.ServerValue.TIMESTAMP)); | |
var today = new Date(); | |
/* today.setDate(today.getDate() - 30); | |
var timestamp = new Date(today).toISOString(); */ | |
var timestamp = today.toISOString(); | |
for (let i = 0; i < message.length; i++) { | |
this.messagesRef.push({ | |
text: message[i].text, | |
user: message[i].user, | |
createdAt: timestamp | |
}); | |
} | |
} | |
// close the connection | |
closeChat() { | |
if (this.messagesRef) { | |
this.messagesRef.off(); | |
} | |
} | |
getLimit() { | |
var today = new Date(); | |
//var milliseconds = Date.parse(today); | |
//var changed = milliseconds - 86400000; //10 minutes (- 900000) - 86400000 1 day | |
today.setDate(today.getDate() - 31); // last 30 Days | |
//console.log(today); | |
var changedISODate = new Date(today).toISOString(); | |
//var changedISODate = today.toISOString(); | |
console.log(changedISODate); | |
return changedISODate; | |
} | |
} | |
// Export instance, not class | |
const firebaseSvc = new FirebaseSvc(); | |
export default firebaseSvc; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment