Last active
May 3, 2020 18:28
-
-
Save taka1156/e3aeb6643468ebc351b3e293eee64a82 to your computer and use it in GitHub Desktop.
FireBaseチャットサイト
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/app'; | |
| import 'firebase/firestore'; | |
| import store from '@/store/index.js'; | |
| let DB = firebase.firestore(); | |
| // ローカルの時刻は、ズレがあるのでサーバ時刻を使用 | |
| const TIME_STAMP = firebase.firestore.FieldValue.serverTimestamp(); | |
| // インクリメント(同時書き換えを気にしなくていい) | |
| const INCREMENT = firebase.firestore.FieldValue.increment(1); | |
| export default { | |
| postRoom(room) { | |
| // 部屋ドキュメントの参照 | |
| const roomDocRef = DB.collection('room').doc(); | |
| // 部屋情報書き込み | |
| roomDocRef.set({ | |
| roomName: room.roomName, | |
| detail: room.detail, | |
| pass: room.pass, | |
| uid: room.uid, | |
| userName: room.userName, | |
| date: TIME_STAMP | |
| }); | |
| // デフォルトのメッセージ書き込み(roomドキュメントにサブコレクションchatを生やす) | |
| roomDocRef.collection('chat').add({ | |
| name: '管理者', | |
| img: '', | |
| message: room.roomName + 'にようこそ', | |
| date: TIME_STAMP | |
| }); | |
| }, | |
| // チャットメッセージ | |
| postChat(roomDoc, chat) { | |
| // 部屋ドキュメントの参照 | |
| const roomDocRef = DB.collection('room').doc(roomDoc); | |
| // メッセージ書き込み | |
| roomDocRef.collection('chat').add({ | |
| name: chat.userName, | |
| img: chat.img, | |
| message: chat.message, | |
| date: TIME_STAMP | |
| }); | |
| }, | |
| getRooms(lastDate) { | |
| // 部屋コレクションの参照 | |
| const roomRef = DB.collection('room'); | |
| // ソートして現在取得している最後のアイテムの日付(初回ならありえない値(サイト稼働前の日付)) | |
| const sortRoom = roomRef.orderBy('date', 'desc').startAfter(lastDate); | |
| // 5件ずつ取得 | |
| let rooms = sortRoom.limit(4); | |
| rooms.get().then(querySnapshot => { | |
| querySnapshot.forEach(roomDoc => { | |
| console.log(roomDoc) | |
| store.commit('room/setRooms', roomDoc.data()); | |
| }); | |
| }); | |
| }, | |
| getChats() {} | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment