Move all firbase dependencies from actions layer to firebaseService layer (#13)

This commit is contained in:
Qolzam
2017-10-12 17:47:26 +07:00
parent c82826bdd4
commit 0785c38d42
48 changed files with 1305 additions and 796 deletions

View File

@@ -1,5 +1,4 @@
// - Import react components
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import moment from 'moment'
import { push } from 'react-router-redux'
@@ -12,8 +11,7 @@ import { AuthorizeActionType } from 'constants/authorizeActionType'
// - Import services
import { IAuthorizeService } from 'services/authorize'
import { IServiceProvider } from 'factories'
import { ServiceProvide } from 'factories'
import { IServiceProvider, ServiceProvide } from 'factories'
const serviceProvider: IServiceProvider = new ServiceProvide()
const authorizeService: IAuthorizeService = serviceProvider.createAuthorizeService()

View File

@@ -1,9 +1,7 @@
// - Import firebase component
import firebase, { firebaseRef } from 'app/firebase/'
// - Import domain
import { User } from 'domain/users'
import { Circle, UserFollower } from 'domain/circles'
import { SocialError } from 'domain/common'
// - Import utility components
import moment from 'moment'
@@ -11,23 +9,23 @@ import moment from 'moment'
// - Import action types
import { CircleActionType } from 'constants/circleActionType'
// - Import actions
import * as globalActions from 'actions/globalActions'
import * as postActions from 'actions/postActions'
import * as userActions from 'actions/userActions'
import * as notifyActions from 'actions/notifyActions'
import { IServiceProvider,ServiceProvide } from 'factories'
import { ICircleService } from 'services/circles'
const serviceProvider: IServiceProvider = new ServiceProvide()
const circleService: ICircleService = serviceProvider.createCircleService()
/* _____________ CRUD DB _____________ */
/**
* Add a circle
* @param {string} circleName
* @param {string} circleName
*/
export let dbAddCircle = (circleName: string) => {
return (dispatch: any, getState: Function) => {
@@ -38,21 +36,19 @@ export let dbAddCircle = (circleName: string) => {
name: circleName,
users: {}
}
let circleRef = firebaseRef.child(`userCircles/${uid}/circles`).push(circle)
return circleRef.then(() => {
circle.id = circleRef.key
return circleService.addCircle(uid,circle).then((circleKey: string) => {
circle.id = circleKey
circle.ownerId = uid
dispatch(addCircle(circle))
}, (error) => dispatch(globalActions.showErrorMessage(error.message)))
}, (error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
/**
* Add a user in a circle
* @param {string} cid is circle identifier
* @param {string} cid is circle identifier
* @param {User} userFollowing is the user for following
*/
export let dbAddFollowingUser = (cid: string, userFollowing: User) => {
@@ -72,46 +68,42 @@ export let dbAddFollowingUser = (cid: string, userFollowing: User) => {
avatar: user.avatar || '',
approved: false
}
let updates: any = {}
updates[`userCircles/${uid}/circles/${cid}/users/${userFollowing.userId}`] = userCircle
updates[`userCircles/${userFollowing.userId}/circles/-Followers/users/${uid}`] = userFollower
return firebaseRef.update(updates).then((result) => {
dispatch(addFollowingUser(uid, cid, userFollowing.userId as string, { ...userCircle } as User))
dispatch(notifyActions.dbAddNotify(
{
description: `${user.fullName} follow you.`,
url: `/${uid}`,
notifyRecieverUserId: userFollowing.userId as string,
notifierUserId: uid,
isSeen:false
}))
return circleService.addFollowingUser(uid,cid,userCircle,userFollower,userFollowing.userId as string)
.then(() => {
dispatch(addFollowingUser(uid, cid, userFollowing.userId as string, { ...userCircle } as User))
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
})
dispatch(notifyActions.dbAddNotification(
{
description: `${user.fullName} follow you.`,
url: `/${uid}`,
notifyRecieverUserId: userFollowing.userId as string,
notifierUserId: uid,
isSeen: false
}))
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
/**
* Delete a user from a circle
* @param {string} cid is circle identifier
* @param {string} followingId following user identifier
* @param {string} cid is circle identifier
* @param {string} userFollowingId following user identifier
*/
export let dbDeleteFollowingUser = (cid: string, followingId: string) => {
return (dispatch: any, getState:Function) => {
export let dbDeleteFollowingUser = (cid: string, userFollowingId: string) => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
let updates: any = {}
updates[`userCircles/${uid}/circles/${cid}/users/${followingId}`] = null
updates[`userCircles/${followingId}/circles/-Followers/users/${uid}`] = null
return firebaseRef.update(updates).then((result) => {
dispatch(deleteFollowingUser(uid, cid, followingId))
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
})
return circleService.deleteFollowingUser(uid,cid,userFollowingId)
.then(() => {
dispatch(deleteFollowingUser(uid, cid, userFollowingId))
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
@@ -126,23 +118,21 @@ export const dbUpdateCircle = (newCircle: Circle) => {
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
let circle: Circle = getState().circle.userCircles[uid][newCircle.id!]
let updatedCircle : Circle = {
let updatedCircle: Circle = {
name: newCircle.name || circle.name,
users: newCircle.users ? newCircle.users : (circle.users || [])
}
updates[`userCircles/${uid}/circles/${newCircle.id}`] = updatedCircle
return firebaseRef.update(updates).then(() => {
dispatch(updateCircle(uid,{ id: newCircle.id, ...updatedCircle }))
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
})
return circleService.updateCircle(uid,newCircle.id!,circle)
.then(() => {
dispatch(updateCircle(uid,{ id: newCircle.id, ...updatedCircle }))
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
/**
* Delete a circle from database
* @param {string} id is circle identifier
@@ -153,15 +143,12 @@ export const dbDeleteCircle = (id: string) => {
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
updates[`userCircles/${uid}/circles/${id}`] = null
return firebaseRef.update(updates).then((result) => {
dispatch(deleteCircle(uid, id))
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
})
return circleService.deleteCircle(uid,id)
.then(() => {
dispatch(deleteCircle(uid, id))
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
@@ -173,32 +160,28 @@ export const dbGetCircles = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let circlesRef: any = firebaseRef.child(`userCircles/${uid}/circles`)
return circlesRef.once('value').then((snapshot: any) => {
let circles: any = snapshot.val() || {}
let parsedCircles: { [circleId: string]: Circle } = {}
Object.keys(circles).forEach((circleId) => {
if (circleId !== '-Followers' && circles[circleId].users) {
Object.keys(circles[circleId].users).filter((v, i, a) => a.indexOf(v) === i).forEach((userId) => {
dispatch(postActions.dbGetPostsByUserId(userId))
dispatch(userActions.dbGetUserInfoByUserId(userId, ''))
})
}
parsedCircles[circleId] = {
id: circleId,
...circles[circleId]
}
return circleService.getCircles(uid)
.then((circles: { [circleId: string]: Circle }) => {
Object.keys(circles).forEach((circleId) => {
if (circleId !== '-Followers' && circles[circleId].users) {
Object.keys(circles[circleId].users).filter((v, i, a) => a.indexOf(v) === i).forEach((userId) => {
dispatch(postActions.dbGetPostsByUserId(userId))
dispatch(userActions.dbGetUserInfoByUserId(userId, ''))
})
}
})
dispatch(addCircles(uid, circles))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
dispatch(addCircles(uid, parsedCircles))
})
}
}
}
/**
* Get all user circles from data base by user id
* @param uid user identifier
@@ -207,35 +190,23 @@ export const dbGetCirclesByUserId = (uid: string) => {
return (dispatch: any, getState: Function) => {
if (uid) {
let circlesRef = firebaseRef.child(`userCircles/${uid}/circles`)
return circlesRef.once('value').then((snapshot) => {
let circles = snapshot.val() || {}
let parsedCircles: { [circleId: string]: Circle } = {}
Object.keys(circles).forEach((circleId) => {
parsedCircles[circleId] = {
id: circleId,
...circles[circleId]
}
})
dispatch(addCircles(uid, parsedCircles))
})
return circleService.getCircles(uid)
.then((circles: { [circleId: string]: Circle }) => {
dispatch(addCircles(uid, circles))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
}
/* _____________ CRUD State _____________ */
/**
* Add a normal circle
* @param {string} uid is user identifier
* @param {Circle} circle
* @param {Circle} circle
*/
export const addCircle = (circle: Circle) => {
return {
@@ -247,7 +218,7 @@ export const addCircle = (circle: Circle) => {
/**
* Update a circle
* @param {string} uid is user identifier
* @param {Circle} circle
* @param {Circle} circle
*/
export const updateCircle = (uid: string, circle: Circle) => {
return {
@@ -268,11 +239,10 @@ export const deleteCircle = (uid: string, id: string) => {
}
}
/**
* Add a list of circle
* @param {string} uid
* @param {circleId: string]: Circle} circles
* @param {string} uid
* @param {circleId: string]: Circle} circles
*/
export const addCircles = (uid: string, circles: { [circleId: string]: Circle }) => {
return {
@@ -290,7 +260,6 @@ export const clearAllCircles = () => {
}
}
/**
* Open circle settings
* @param uid user idenifier

View File

@@ -1,9 +1,9 @@
// - Import react components
import moment from 'moment'
import { firebaseRef } from 'app/firebase/'
// - Import domain
import { Comment } from 'domain/comments'
import { SocialError } from 'domain/common'
// - Import action types
import { CommentActionType } from 'constants/commentActionType'
@@ -12,6 +12,12 @@ import { CommentActionType } from 'constants/commentActionType'
import * as globalActions from 'actions/globalActions'
import * as notifyActions from 'actions/notifyActions'
import { IServiceProvider, ServiceProvide } from 'factories'
import { ICommentService } from 'services/comments'
const serviceProvider: IServiceProvider = new ServiceProvide()
const commentService: ICommentService = serviceProvider.createCommentService()
/* _____________ CRUD DB _____________ */
/**
@@ -37,28 +43,27 @@ export const dbAddComment = (ownerPostUserId: string,newComment: Comment, callBa
text: newComment.text
}
let commentRef: any = firebaseRef.child(`postComments/${newComment.postId}`).push(comment)
return commentRef.then(() => {
dispatch(addComment(newComment))
callBack()
dispatch(globalActions.hideTopLoading())
return commentService.addComment(newComment.postId,comment)
.then((commentKey: string) => {
dispatch(addComment({id: commentKey! ,...comment}))
callBack()
dispatch(globalActions.hideTopLoading())
if (ownerPostUserId && ownerPostUserId !== uid) {
dispatch(notifyActions.dbAddNotify(
{
description: 'Add comment on your post.',
url: `/${ownerPostUserId}/posts/${newComment.postId}`,
notifyRecieverUserId: ownerPostUserId, notifierUserId: uid,
isSeen: false
}))
}
if (ownerPostUserId && ownerPostUserId !== uid) {
dispatch(notifyActions.dbAddNotification(
{
description: 'Add comment on your post.',
url: `/${ownerPostUserId}/posts/${comment.postId}`,
notifyRecieverUserId: ownerPostUserId, notifierUserId: uid,
isSeen: false
}))
}
}, (error: any) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
}
}
@@ -69,14 +74,14 @@ export const dbGetComments = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let commentsRef: any = firebaseRef.child(`postComments`)
return commentsRef.on('value', (snapshot: any) => {
let comments: {[postId: string]: {[commentId: string]: Comment}} = snapshot!.val() || {}
return commentService.getComments()
.then((comments: {[postId: string]: {[commentId: string]: Comment}}) => {
dispatch(addCommentList(comments))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
}
@@ -96,9 +101,8 @@ export const dbUpdateComment = (id: string, postId: string, text: string) => {
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
let comment: Comment = getState().comment.postComments[postId][id]
updates[`postComments/${postId}/${id}`] = {
let updatedComment: Comment = {
postId: postId,
score: comment.score,
text: text,
@@ -107,15 +111,17 @@ export const dbUpdateComment = (id: string, postId: string, text: string) => {
userAvatar: comment.userAvatar,
userId: uid
}
return firebaseRef.update(updates).then((result) => {
dispatch(updateComment( id, postId, text))
dispatch(globalActions.hideTopLoading())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
return commentService.updateComment(uid,postId,updatedComment)
.then(() => {
dispatch(updateComment( id, postId, text))
dispatch(globalActions.hideTopLoading())
})
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
}
}
@@ -128,24 +134,28 @@ export const dbUpdateComment = (id: string, postId: string, text: string) => {
export const dbDeleteComment = (id: string, postId: string) => {
return (dispatch: any, getState: Function) => {
if (id === undefined || id === null) {
dispatch(globalActions.showErrorMessage('comment id can not be null or undefined'))
}
console.log('====================================')
console.log(id,postId)
console.log('====================================')
dispatch(globalActions.showTopLoading())
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
updates[`postComments/${postId}/${id}`] = null
return commentService.deleteComment(id,postId)
.then(() => {
dispatch(deleteComment(id, postId))
dispatch(globalActions.hideTopLoading())
return firebaseRef.update(updates).then((result) => {
dispatch(deleteComment(id, postId))
dispatch(globalActions.hideTopLoading())
}, (error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
})
}
}

View File

@@ -1,5 +1,5 @@
// - Import image gallery action types
import {GlobalActionType} from 'constants/globalActionType'
import { GlobalActionType } from 'constants/globalActionType'
// - Import actions
import * as postActions from 'actions/postActions'
@@ -8,8 +8,8 @@ import * as userActions from 'actions/userActions'
/**
* Progress change
* @param {string} percent
* @param {boolean} visible
* @param {string} percent
* @param {boolean} visible
*/
export const progressChange = (percent: number, visible: Boolean) => {
return {
@@ -38,16 +38,15 @@ export const defaultDataDisable = () => {
}
}
// - Show notification of request
export const showNotificationRequest = () => {
export const showNotificationRequest = () => {
return{
type: GlobalActionType.SHOW_SEND_REQUEST_MESSAGE_GLOBAL
}
}
// - Show notification of success
export const showNotificationSuccess = () => {
export const showNotificationSuccess = () => {
return{
type: GlobalActionType.SHOW_REQUEST_SUCCESS_MESSAGE_GLOBAL
}
@@ -65,9 +64,9 @@ export const hideMessage = () => {
/**
* Show error message
* @param {string} message
* @param {string} message
*/
export const showErrorMessage = (message: string) => {
export const showErrorMessage = (message: string) => {
return {
type: GlobalActionType.SHOW_ERROR_MESSAGE_GLOBAL,
payload: message
@@ -85,7 +84,6 @@ export const setHeaderTitleOpt = (callerKey: string,payload: any) => {
const userName = getState().user.info && getState().user.info[payload] ? getState().user.info[payload].fullName : ''
dispatch(setHeaderTitle(userName))
break
default:
break
}
@@ -145,9 +143,6 @@ export const hideTopLoading = () => {
}
/**
* Store temp data
*/
@@ -159,11 +154,10 @@ export const temp = (data: string) => {
}
// - Load data for guest
export const loadDataGuest = () => {
// tslint:disable-next-line:no-empty
return (dispatch: any,getState: Function) => {
}
}
}

View File

@@ -1,9 +1,9 @@
// - Import react componetns
import moment from 'moment'
import { firebaseRef, firebaseAuth, storageRef } from 'app/firebase/'
// - Import domain
import { Image } from 'domain/imageGallery'
import { SocialError } from 'domain/common'
// - Import action types
import { ImageGalleryActionType } from 'constants/imageGalleryActionType'
@@ -14,29 +14,29 @@ import * as globalActions from 'actions/globalActions'
// - Import app API
import FileAPI from 'api/FileAPI'
import { IServiceProvider, ServiceProvide } from 'factories'
import { IImageGalleryService } from 'services/imageGallery'
const serviceProvider: IServiceProvider = new ServiceProvide()
const imageGalleryService: IImageGalleryService = serviceProvider.createImageGalleryService()
/* _____________ UI Actions _____________ */
/**
* Download images for image gallery
*/
export const downloadForImageGallery = () => {
export const dbGetImageGallery = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let imagesRef: any = firebaseRef.child(`userFiles/${uid}/files/images`)
return imagesRef.once('value').then((snapshot: any) => {
let images = snapshot.val() || {}
let parsedImages: Image[] = []
Object.keys(images).forEach((imageId) => {
parsedImages.push({
id: imageId,
...images[imageId]
})
return imageGalleryService.getImageGallery(uid)
.then((images: Image[]) => {
dispatch(addImageList(images))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
dispatch(addImageList(parsedImages))
})
}
}
@@ -62,15 +62,16 @@ export const dbSaveImage = (imageURL: string,imageFullPath: string) => {
lastEditDate: 0,
deleted: false
}
let imageRef = firebaseRef.child(`userFiles/${uid}/files/images`).push(image)
return imageRef.then(() => {
dispatch(addImage({
...image,
id: imageRef.key
}))
})
return imageGalleryService.saveImage(uid,image)
.then((imageKey: string) => {
dispatch(addImage({
...image,
id: imageKey
}))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
@@ -84,16 +85,13 @@ export const dbDeleteImage = (id: string) => {
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
updates[`userFiles/${uid}/files/images/${id}`] = null
return firebaseRef.update(updates).then((result) => {
dispatch(deleteImage(id))
console.log('image removed: ', id)
}, (error) => {
console.log(error)
})
return imageGalleryService.deleteImage(uid,id)
.then(() => {
dispatch(deleteImage(id))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
@@ -105,27 +103,19 @@ export const dbDeleteImage = (id: string) => {
*/
export const dbUploadImage = (file: any, fileName: string) => {
return (dispatch: any, getState: Function) => {
// Create a storage refrence
let storegeFile: any = storageRef.child(`images/${fileName}`)
// Upload file
let task: any = storegeFile.put(file)
dispatch(globalActions.showTopLoading())
// Upload storage bar
task.on('state_changed', (snapshot: any) => {
let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
return imageGalleryService
.uploadImage(file,fileName, (percentage: number) => {
dispatch(globalActions.progressChange(percentage, true))
}, (error: any) => {
dispatch(globalActions.showErrorMessage(error.code))
dispatch(globalActions.hideTopLoading())
}, (complete?: any ) => {
})
.then(() => {
dispatch(globalActions.progressChange(100, false))
dispatch(dbSaveImage(fileName,''))
dispatch(globalActions.hideTopLoading())
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.code))
dispatch(globalActions.hideTopLoading())
})
}
}
@@ -143,44 +133,20 @@ export const dbDownloadImage = (fileName: string) => {
if (getState().imageGallery.imageURLList[fileName] && fileName !== '') {
return
}
if (getState().imageGallery.imageRequests.indexOf(fileName) > -1){
if (getState().imageGallery.imageRequests.indexOf(fileName) > -1) {
return
}
dispatch(sendImageRequest(fileName))
// Create a reference to the file we want to download
let starsRef: any = storageRef.child(`images/${fileName}`)
// Get the download URL
starsRef.getDownloadURL().then((url: string) => {
return imageGalleryService.downloadImage(fileName)
.then((url: string) => {
// Insert url into an <img> tag to 'download'
if (!getState().imageGallery.imageURLList[fileName] || fileName === '')
dispatch(setImageURL(fileName, url))
}).catch((error: any) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object_not_found':
// File doesn't exist
dispatch(globalActions.showErrorMessage('storage/object_not_found'))
break
case 'storage/unauthorized':
// User doesn't have permission to access the object
dispatch(globalActions.showErrorMessage('storage/unauthorized'))
break
case 'storage/canceled':
// User canceled the upload
dispatch(globalActions.showErrorMessage('storage/canceled'))
break
case 'storage/unknown':
// Unknown error occurred, inspect the server response
dispatch(globalActions.showErrorMessage('storage/unknown'))
break
}
if (!getState().imageGallery.imageURLList[fileName] || fileName === '') {
dispatch(setImageURL(fileName, url))
}
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}

View File

@@ -1,17 +1,22 @@
// - Import react components
import moment from 'moment'
import { firebaseRef } from 'app/firebase/'
// - Import domain
import { Notification } from 'domain/notifications'
import { SocialError } from 'domain/common'
// - Import action types
import {NotificationActionType} from 'constants/notificationActionType'
import { NotificationActionType } from 'constants/notificationActionType'
// - Import actions
import * as globalActions from 'actions/globalActions'
import * as userActions from 'actions/userActions'
import { IServiceProvider, ServiceProvide } from 'factories'
import { INotificationService } from 'services/notifications'
const serviceProvider: IServiceProvider = new ServiceProvide()
const notificationService: INotificationService = serviceProvider.createNotificationService()
/* _____________ CRUD DB _____________ */
@@ -19,7 +24,7 @@ import * as userActions from 'actions/userActions'
* Add notificaition to database
* @param {object} newNotify user notificaition
*/
export const dbAddNotify = (newNotify: Notification) => {
export const dbAddNotification = (newNotify: Notification) => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
@@ -32,10 +37,11 @@ export const dbAddNotify = (newNotify: Notification) => {
notifyRecieverUserId: newNotify.notifyRecieverUserId
}
let notifyRef: any = firebaseRef.child(`userNotifies/${newNotify.notifyRecieverUserId}`).push(notify)
return notifyRef.then(() => {
dispatch(addNotify())
}, (error: any) => dispatch(globalActions.showErrorMessage(error.message)))
return notificationService.addNotification(notify)
.then(() => {
dispatch(addNotify())
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -43,84 +49,74 @@ export const dbAddNotify = (newNotify: Notification) => {
/**
* Get all notificaitions from database
*/
export const dbGetNotifies = () => {
export const dbGetNotifications = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let notifiesRef: any = firebaseRef.child(`userNotifies/${uid}`)
return notifiesRef.on('value', (snapshot: any) => {
let notifies: {[notifyId: string]: Notification} = snapshot.val() || {}
Object.keys(notifies).forEach((key => {
if (!getState().user.info[notifies[key].notifierUserId]) {
dispatch(userActions.dbGetUserInfoByUserId(notifies[key].notifierUserId,''))
}
}))
dispatch(addNotifyList(notifies))
})
return notificationService.getNotifications(uid)
.then((notifies: { [notifyId: string]: Notification }) => {
Object.keys(notifies).forEach((key => {
if (!getState().user.info[notifies[key].notifierUserId]) {
dispatch(userActions.dbGetUserInfoByUserId(notifies[key].notifierUserId,''))
}
}))
dispatch(addNotifyList(notifies))
})
}
}
}
/**
* Delete a notificaition from database
* @param {string} id of notificaition
*/
export const dbDeleteNotify = (id: string) => {
export const dbDeleteNotification = (id: string) => {
return (dispatch: any, getState: Function) => {
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
updates[`userNotifies/${uid}/${id}`] = null
return firebaseRef.update(updates).then((result) => {
return notificationService.deleteNotification(id,uid).then(() => {
dispatch(deleteNotify(id))
}, (error) => dispatch(globalActions.showErrorMessage(error.message)))
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
/**
* Make seen a notificaition from database
* @param {string} id of notificaition
*/
export const dbSeenNotify = (id: string) => {
export const dbSeenNotification = (id: string) => {
return (dispatch: any, getState: Function) => {
// Get current user id
let uid: string = getState().authorize.uid
let notify: Notification = getState().notify.userNotifies[id]
let updates: any = {}
updates[`userNotifies/${uid}/${id}`] = {
let updatedNotification: Notification = {
description: notify.description,
url: notify.url,
notifierUserId: notify.notifierUserId,
notifyRecieverUserId: uid,
isSeen: true
}
return firebaseRef.update(updates).then((result) => {
return notificationService.setSeenNotification(id,uid,updatedNotification)
.then(() => {
dispatch(seenNotify(id))
}, (error) => dispatch(globalActions.showErrorMessage(error.message)))
})
.catch((error) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
/* _____________ CRUD State _____________ */
/**
* Add notificaition
* Add notificaition
*/
export const addNotify = () => {
@@ -141,7 +137,6 @@ export const addNotifyList = (userNotifies: {[notifyId: string]: Notification})
}
}
/**
* Delete a notificaition
* @param {string} id of notificaition
@@ -168,5 +163,3 @@ export const clearAllNotifications = () => {
type: NotificationActionType.CLEAR_ALL_DATA_NOTIFY
}
}

View File

@@ -1,11 +1,9 @@
// - Import react components
import { Action } from 'redux'
// - Import firebase component
import firebase, { firebaseRef } from '../firebase'
// - Import domain
import { Post } from 'domain/posts'
import { SocialError } from 'domain/common'
// - Import utility components
import moment from 'moment'
@@ -16,6 +14,12 @@ import { PostActionType } from 'constants/postActionType'
// - Import actions
import * as globalActions from 'actions/globalActions'
import { IServiceProvider, ServiceProvide } from 'factories'
import { IPostService } from 'services/posts'
const serviceProvider: IServiceProvider = new ServiceProvide()
const postService: IPostService = serviceProvider.createPostService()
/* _____________ CRUD DB _____________ */
/**
@@ -48,14 +52,14 @@ export let dbAddPost = (newPost: any, callBack: Function) => {
deleted: false
}
let postRef: any = firebaseRef.child(`userPosts/${uid}/posts`).push(post)
return postRef.then(() => {
return postService.addPost(uid,post).then((postKey: string) => {
dispatch(addPost(uid, {
...post,
id: postRef.key
id: postKey
}))
callBack()
}, (error: any) => dispatch(globalActions.showErrorMessage(error.message)))
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -91,16 +95,17 @@ export const dbAddImagePost = (newPost: any, callBack: Function) => {
deleted: false
}
let postRef: any = firebaseRef.child(`userPosts/${uid}/posts`).push(post)
return postRef.then(() => {
return postService.addPost(uid,post).then((postKey: string) => {
dispatch(addPost(uid, {
...post,
id: postRef.key
id: postKey
}))
callBack()
dispatch(globalActions.hideTopLoading())
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -142,14 +147,15 @@ export const dbUpdatePost = (newPost: any, callBack: Function) => {
disableSharing: newPost.disableSharing !== undefined ? newPost.disableSharing : (post.disableSharing ? post.disableSharing : false),
deleted: false
}
updates[`userPosts/${uid}/posts/${newPost.id}`] = updatedPost
return firebaseRef.update(updates).then((result) => {
return postService.updatePost(uid,newPost.id,updatedPost).then(() => {
dispatch(updatePost(uid, { id: newPost.id, ...updatedPost }))
callBack()
dispatch(globalActions.hideTopLoading())
}, (error) => {
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
@@ -170,15 +176,12 @@ export const dbDeletePost = (id: string) => {
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
updates[`userPosts/${uid}/posts/${id}`] = null
return firebaseRef.update(updates).then((result) => {
return postService.deletePost(uid,id).then(() => {
dispatch(deletePost(uid, id))
dispatch(globalActions.hideTopLoading())
}, (error) => {
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
@@ -190,22 +193,15 @@ export const dbDeletePost = (id: string) => {
* Get all user posts from data base
*/
export const dbGetPosts = () => {
return (dispatch: any, getState: any) => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let postsRef: any = firebaseRef.child(`userPosts/${uid}/posts`)
return postsRef.once('value').then((snapshot: any) => {
let posts: any = snapshot.val() || {}
let parsedPosts: { [postId: string]: Post } = {}
Object.keys(posts).forEach((postId) => {
parsedPosts[postId] = {
id: postId,
...posts[postId]
}
})
dispatch(addPosts(uid, parsedPosts))
return postService.getPosts(uid).then((posts: { [postId: string]: Post }) => {
dispatch(addPosts(uid, posts))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
@@ -220,22 +216,18 @@ export const dbGetPosts = () => {
export const dbGetPostById = (uid: string, postId: string) => {
return (dispatch: any, getState: Function) => {
if (uid) {
let postsRef: any = firebaseRef.child(`userPosts/${uid}/posts/${postId}`)
return postsRef.once('value').then((snapshot: any) => {
const newPost = snapshot.val() || {}
const post = {
id: postId,
...newPost
}
return postService.getPostById(uid,postId).then((post: Post) => {
dispatch(addPost(uid, post))
})
.catch((error: SocialError) => {
dispatch(globalActions.showErrorMessage(error.message))
})
}
}
}
/**
* Get all user posts from data base by user id
* @param uid posts owner identifier
@@ -244,19 +236,8 @@ export const dbGetPostsByUserId = (uid: string) => {
return (dispatch: any, getState: Function) => {
if (uid) {
let postsRef: any = firebaseRef.child(`userPosts/${uid}/posts`)
return postsRef.once('value').then((snapshot: any) => {
let posts: any = snapshot.val() || {}
let parsedPosts: { [postId: string]: Post } = {}
Object.keys(posts).forEach((postId) => {
parsedPosts[postId] = {
id: postId,
...posts[postId]
}
})
dispatch(addPosts(uid, parsedPosts))
return postService.getPosts(uid).then((posts: { [postId: string]: Post }) => {
dispatch(addPosts(uid, posts))
})
}
@@ -268,7 +249,7 @@ export const dbGetPostsByUserId = (uid: string) => {
/**
* Add a normal post
* @param {string} uid is user identifier
* @param {Post} post
* @param {Post} post
*/
export const addPost = (uid: string, post: Post) => {
return {
@@ -303,8 +284,8 @@ export const deletePost = (uid: string, id: string) => {
/**
* Add a list of post
* @param {string} uid
* @param {[object]} posts
* @param {string} uid
* @param {[object]} posts
*/
export const addPosts = (uid: string, posts: { [postId: string]: Post }) => {
return {

View File

@@ -1,21 +1,24 @@
// - Import react components
import { firebaseRef } from 'app/firebase/'
// - Import domain
import { Profile } from 'domain/users'
import { SocialError } from 'domain/common'
// - Import action types
import {UserActionType} from 'constants/userActionType'
import { UserActionType } from 'constants/userActionType'
// - Import actions
import * as globalActions from 'actions/globalActions'
// - Import actions
import * as globalActions from 'actions/globalActions'
import * as userActions from 'actions/userActions'
declare const console: any
import { IServiceProvider, ServiceProvide } from 'factories'
import { IUserService } from 'services/users'
const serviceProvider: IServiceProvider = new ServiceProvide()
const userService: IUserService = serviceProvider.createUserService()
/* _____________ CRUD DB _____________ */
/**
* Get user info from database
*/
@@ -23,11 +26,8 @@ export const dbGetUserInfo = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let userProfileRef: any = firebaseRef.child(`users/${uid}/info`)
return userProfileRef.once('value').then((snapshot: any) => {
let userProfile: Profile = snapshot.val() || {}
return userService.getUserProfile(uid).then((userProfile: Profile) => {
dispatch(addUserInfo(uid, {
avatar: userProfile.avatar,
email: userProfile.email,
@@ -35,7 +35,8 @@ export const dbGetUserInfo = () => {
banner: userProfile.banner,
tagLine: userProfile.tagLine
}))
}, (error: any) => console.log(error))
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -43,16 +44,15 @@ export const dbGetUserInfo = () => {
/**
* Get user info from database
* @param {string} uid
* @param {string} callerKey
* @param {string} uid
* @param {string} callerKey
*/
export const dbGetUserInfoByUserId = (uid: string, callerKey: string) => {
return (dispatch: any, getState: Function) => {
if (uid) {
let userProfileRef: any = firebaseRef.child(`users/${uid}/info`)
return userProfileRef.once('value').then((snapshot: any) => {
let userProfile = snapshot.val() || {}
return userService.getUserProfile(uid).then((userProfile: Profile) => {
dispatch(addUserInfo(uid, {
avatar: userProfile.avatar,
email: userProfile.email,
@@ -60,6 +60,7 @@ export const dbGetUserInfoByUserId = (uid: string, callerKey: string) => {
banner: userProfile.banner,
tagLine: userProfile.tagLine
}))
switch (callerKey) {
case 'header':
dispatch(globalActions.setHeaderTitle(userProfile.fullName))
@@ -69,7 +70,8 @@ export const dbGetUserInfoByUserId = (uid: string, callerKey: string) => {
default:
break
}
}, (error: any) => console.log(error))
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -77,7 +79,7 @@ export const dbGetUserInfoByUserId = (uid: string, callerKey: string) => {
/**
* Updata user information
* @param {object} newInfo
* @param {object} newInfo
*/
export const dbUpdateUserInfo = (newProfile: Profile) => {
return (dispatch: any, getState: Function) => {
@@ -85,24 +87,22 @@ export const dbUpdateUserInfo = (newProfile: Profile) => {
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
let profile = getState().user.info[uid]
let updateProfie: Profile = {
let profile: Profile = getState().user.info[uid]
let updatedProfie: Profile = {
avatar: newProfile.avatar || profile.avatar || '',
banner: newProfile.banner || profile.banner || 'https://firebasestorage.googleapis.com/v0/b/open-social-33d92.appspot.com/o/images%2F751145a1-9488-46fd-a97e-04018665a6d3.JPG?alt=media&token=1a1d5e21-5101-450e-9054-ea4a20e06c57',
email: newProfile.email || profile.email || '',
fullName: newProfile.fullName || profile.fullName || '',
tagLine: newProfile.tagLine || profile.tagLine || ''
}
updates[`users/${uid}/info`] = updateProfie
return firebaseRef.update(updates).then((result) => {
dispatch(updateUserInfo(uid, updateProfie))
return userService.updateUserProfile(uid,updatedProfie).then(() => {
dispatch(updateUserInfo(uid, updatedProfie))
dispatch(closeEditProfile())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -112,27 +112,11 @@ export const dbGetPeopleInfo = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let peopleRef: any = firebaseRef.child(`users`)
return peopleRef.once('value').then((snapshot: any) => {
let people = snapshot.val() || {}
let parsedPeople: {[userId: string]: Profile} = {}
Object.keys(people).forEach((userId) => {
if (userId !== uid) {
let userInfo = people[userId].info
parsedPeople[userId] = {
avatar: userInfo.avatar,
email: userInfo.email,
fullName: userInfo.fullName,
banner: userInfo.banner,
tagLine: userInfo.tagLine
}
}
})
dispatch(addPeopleInfo(parsedPeople))
}, (error: any) => console.log(error))
return userService.getUsersProfile(uid)
.then((usersProfile: {[userId: string]: Profile}) => {
dispatch(addPeopleInfo(usersProfile))
})
.catch((error: SocialError) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -140,7 +124,6 @@ export const dbGetPeopleInfo = () => {
/* _____________ CRUD State _____________ */
/**
* Add user information
* @param {string} uid is the user identifier
@@ -178,7 +161,7 @@ export const updateUserInfo = (uid: string, info: Profile) => {
/**
* User info
* @param {Profile} info
* @param {Profile} info
*/
export const userInfo = (info: Profile) => {
return {
@@ -193,7 +176,6 @@ export const clearAllData = () => {
}
}
/**
* Open edit profile
*/

View File

@@ -1,8 +1,7 @@
import moment from 'moment'
import { firebaseRef } from 'app/firebase/'
// - Import action types
import {VoteActionType} from 'constants/voteActionType'
import { VoteActionType } from 'constants/voteActionType'
// - Import domain
import { Vote } from 'domain/votes'
@@ -11,7 +10,12 @@ import { Vote } from 'domain/votes'
import * as globalActions from 'actions/globalActions'
import * as notifyActions from 'actions/notifyActions'
declare const console: any
import { IServiceProvider, ServiceProvide } from 'factories'
import { IVoteService } from 'services/votes'
const serviceProvider: IServiceProvider = new ServiceProvide()
const voteService: IVoteService = serviceProvider.createVoteService()
/* _____________ CRUD DB _____________ */
/**
@@ -31,24 +35,24 @@ export const dbAddVote = (postId: string,ownerPostUserId: string) => {
userId: uid
}
let voteRef = firebaseRef.child(`postVotes/${postId}`).push(vote)
return voteRef.then(() => {
return voteService.addVote(vote).then((voteKey: string) => {
dispatch(addVote(
{
...vote,
postId: postId,
id: voteRef.key
id: voteKey
}))
if(uid !== ownerPostUserId)
dispatch(notifyActions.dbAddNotify(
{
description:'Vote on your post.',
url:`/${ownerPostUserId}/posts/${postId}`,
notifyRecieverUserId:ownerPostUserId,notifierUserId:uid,
isSeen:false
}))
}, (error) => dispatch(globalActions.showErrorMessage(error.message)))
if (uid !== ownerPostUserId) {
dispatch(notifyActions.dbAddNotification(
{
description: 'Vote on your post.',
url: `/${ownerPostUserId}/posts/${postId}`,
notifyRecieverUserId: ownerPostUserId,notifierUserId:uid,
isSeen: false
}))
}
})
.catch((error) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
@@ -60,18 +64,17 @@ export const dbGetVotes = () => {
return (dispatch: any, getState: Function) => {
let uid: string = getState().authorize.uid
if (uid) {
let votesRef: any = firebaseRef.child(`postVotes`)
return votesRef.on('value',(snapshot: any) => {
let postVotes: {[postId:string]: {[voteId: string]: Vote}} = snapshot.val() || {}
return voteService
.getVotes()
.then((postVotes: { [postId: string]: { [voteId: string]: Vote } }) => {
dispatch(addVoteList(postVotes))
})
}
}
}
/**
* Delete a vote from database
* @param {string} id of vote
@@ -83,25 +86,19 @@ export const dbDeleteVote = (postId: string) => {
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {}
let votes: {[voteId: string]: Vote} = getState().vote.postVotes[postId]
let id: string = Object.keys(votes).filter((key)=> votes[key].userId === uid)[0]
let id: string = Object.keys(votes).filter((key) => votes[key].userId === uid)[0]
updates[`postVotes/${postId}/${id}`] = null
return firebaseRef.update(updates).then((result) => {
return voteService.deleteVote(id,postId).then(() => {
dispatch(deleteVote(id, postId))
})
.catch((error: any) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
/**
* Add a vote
* @param {Vote} vote
* @param {Vote} vote
*/
export const addVote = (vote: Vote) => {
return { type: VoteActionType.ADD_VOTE, payload: vote }
@@ -122,7 +119,7 @@ export const deleteVote = (id: string, postId: string) => {
* Ad a list of vote
* @param {[postId:string]: {[voteId: string]: Vote}} votes a list of vote
*/
export const addVoteList = (votes: {[postId:string]: {[voteId: string]: Vote}}) => {
export const addVoteList = (votes: {[postId: string]: {[voteId: string]: Vote}}) => {
return { type: VoteActionType.ADD_VOTE_LIST, payload: votes }
}