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 }
}

View File

@@ -1,101 +1,100 @@
export interface IMasterProps{
export interface IMasterProps {
/**
* Close gloal message
*
*
* @type {Function}
* @memberof IMasterProps
*/
closeMessage: Function,
closeMessage: Function,
/**
* Show progress bar information
*
*
* @type {*}
* @memberof IMasterProps
*/
progress:any,
progress: any,
/**
* Login a user
*
*
* @type {Function}
* @memberof IMasterProps
*/
login: Function,
login: Function,
/**
* Global state
*
*
* @type {*}
* @memberof IMasterProps
*/
global:any,
global: any,
/**
* Set flag {false} which user data has not loaded
*
*
* @type {Function}
* @memberof IMasterProps
*/
defaultDataDisable: Function,
defaultDataDisable: Function,
/**
* Logout current user
*
*
* @type {Function}
* @memberof IMasterProps
*/
logout: Function,
logout: Function,
/**
* Clear user date from store
*
*
* @type {Function}
* @memberof IMasterProps
*/
clearData: Function,
clearData: Function,
/**
* Prepare default data for a guest user
*
* Prepare default data for a guest user
*
* @type {Function}
* @memberof IMasterProps
*/
loadDataGuest: Function,
loadDataGuest: Function,
/**
* Set flag {true} which all user data has loaded
*
*
* @type {Function}
* @memberof IMasterProps
*/
defaultDataEnable: Function,
defaultDataEnable: Function,
/**
* Load user data into store
*
*
* @type {Function}
* @memberof IMasterProps
*/
loadData: Function,
loadData: Function,
/**
* If all data from all entities are loaded {true} if not {false}
*
*
* @type {Boolean}
* @memberof IMasterProps
*/
loaded:Boolean,
loaded: Boolean,
/**
* If current user is guest {true} if no
*
*
* @type {Boolean}
* @memberof IMasterProps
*/
guest:Boolean,
guest: Boolean,
/**
* If current user is authed {true} if not {false}
*
*
* @type {Boolean}
* @memberof IMasterProps
*/
authed: Boolean,
authed: Boolean,
/**
* Authed user identifier
*
*
* @type {string}
* @memberof IMasterProps
*/
uid: string
}
uid: string
}

View File

@@ -1,3 +1,4 @@
/// <reference types="@types/material-ui" />
// - Import react components
import React, { Component } from 'react'
import { connect } from 'react-redux'
@@ -33,7 +34,7 @@ import * as notifyActions from 'actions/notifyActions'
/* ------------------------------------ */
// - Create Master component class
export class Master extends Component<IMasterProps,IMasterState> {
export class Master extends Component<IMasterProps, IMasterState> {
static isPrivate = true
// Constructor
@@ -108,45 +109,44 @@ export class Master extends Component<IMasterProps,IMasterState> {
*/
public render (): React.ReactElement<{}> {
const {progress, global} = this.props
const { progress, global } = this.props
return (
<div id='master'>
<div className='master__progress' style={{display: (progress.visible ? 'block' : 'none' )}}>
<LinearProgress mode='determinate' value={progress.percent} />
</div>
<div className='master__loading animate-fading2' style={{display: ( global.showTopLoading ? 'flex' : 'none' )}}>
<div className='title'>Loading ... </div>
</div>
<div className='master__progress' style={{ display: (progress.visible ? 'block' : 'none') }}>
<LinearProgress mode='determinate' value={progress.percent} />
</div>
<div className='master__loading animate-fading2' style={{ display: (global.showTopLoading ? 'flex' : 'none') }}>
<div className='title'>Loading ... </div>
</div>
<MasterLoading activeLoading={this.state.loading || !(this.props.loaded || this.props.guest)} handleLoading={this.handleLoading} />
{(!this.state.loading && (this.props.loaded || this.props.guest))
? (<Switch>
<Route path='/signup' component={Signup} />
<Route path='/settings' component={Settings} />
<Route path='/login' render={() => {
console.log('this.props.authed: ', this.props.authed, 'this.props: ', this.props)
return (
this.props.authed
? <Redirect to='/' />
: <Login />
)
}
} />
<Route render={() => <Home uid={this.props.uid}/>} />
? (<Switch>
<Route path='/signup' component={Signup} />
<Route path='/settings' component={Settings} />
<Route path='/login' render={() => {
console.log('this.props.authed: ', this.props.authed, 'this.props: ', this.props)
return (
this.props.authed
? <Redirect to='/' />
: <Login />
)
}
} />
<Route render={() => <Home uid={this.props.uid} />} />
</Switch>) : ''
</Switch>) : ''
}
<Snackbar
open={this.props.global.messageOpen}
message={this.props.global.message}
autoHideDuration={4000}
style={{left: '1%', transform: 'none'}}
style={{ left: '1%', transform: 'none' }}
/>
</div>
)
}
}
@@ -157,11 +157,11 @@ const mapDispatchToProps = (dispatch: any, ownProps: any) => {
return {
loadData: () => {
dispatch(commentActions.dbGetComments())
dispatch(imageGalleryActions.downloadForImageGallery())
dispatch(imageGalleryActions.dbGetImageGallery())
dispatch(postActions.dbGetPosts())
dispatch(userActions.dbGetUserInfo())
dispatch(voteActions.dbGetVotes())
dispatch(notifyActions.dbGetNotifies())
dispatch(notifyActions.dbGetNotifications())
dispatch(circleActions.dbGetCircles())
},
@@ -202,7 +202,7 @@ const mapDispatchToProps = (dispatch: any, ownProps: any) => {
* @param {object} state
*/
const mapStateToProps = (state: any) => {
const {authorize, global, user, post, comment, imageGallery , vote, notify,circle } = state
const { authorize, global, user, post, comment, imageGallery, vote, notify, circle } = state
return {
guest: authorize.guest,
uid: authorize.uid,

View File

@@ -1,61 +1,69 @@
import { BaseDomain } from 'domain/common'
export class Comment extends BaseDomain {
/**
* Post identifier that comment belong to
*
* Comment identifier
*
* @type {string}
* @memberof Comment
*/
public postId: string
public id?: string | null
/**
* Comment text
*
* @type {string}
* @memberof Comment
*/
public text: string
/**
* Post identifier that comment belong to
*
* @type {string}
* @memberof Comment
*/
public postId: string
/**
* Comment score
*
* @type {number}
* @memberof Comment
*/
public score: number
/**
* Comment text
*
* @type {string}
* @memberof Comment
*/
public text: string
/**
* Comment creation date
*
* @type {number}
* @memberof Comment
*/
public creationDate:number
/**
* Comment score
*
* @type {number}
* @memberof Comment
*/
public score: number
/**
* Comment owner full name
*
* @type {string}
* @memberof Comment
*/
public userDisplayName: string
/**
* Comment creation date
*
* @type {number}
* @memberof Comment
*/
public creationDate: number
/**
* Comment owner avater address
*
* @type {string}
* @memberof Comment
*/
public userAvatar: string
/**
* Comment owner full name
*
* @type {string}
* @memberof Comment
*/
public userDisplayName: string
/**
* Comment owner identifier
*
* @type {string}
* @memberof Comment
*/
public userId: string
}
/**
* Comment owner avater address
*
* @type {string}
* @memberof Comment
*/
public userAvatar: string
/**
* Comment owner identifier
*
* @type {string}
* @memberof Comment
*/
public userId: string
}

View File

@@ -1,45 +1,43 @@
export class SocialError{
constructor(code: string, description: string){
this._code = code
this._description = description
this._isError = true
}
export class SocialError {
/**
* Error code
*
*
* @type {string}
* @memberof SocialError
*/
private _code : string
public get code() : string {
return this._code
}
private _code: string
public get code (): string {
return this._code
}
/**
* Error description
*
* Error message
*
* @type {string}
* @memberof SocialError
*/
private _description : string
public get description() : string {
return this._description
}
private _message: string
public get message (): string {
return this._message
}
/**
* If is error {true} if not {false}
*
*
* @type {Boolean}
* @memberof SocialError
*/
private _isError : Boolean
public get isError() : Boolean {
return this._isError
}
}
private _isError: Boolean
public get isError (): Boolean {
return this._isError
}
constructor (code: string, message: string) {
this._code = code
this._message = message
this._isError = true
}
}

View File

@@ -4,66 +4,66 @@ export class Image extends BaseDomain {
/**
* Image identifier
*
*
* @type {string}
* @memberof Image
*/
public id?: string | null
public id?: string | null
/**
* Image creation date
*
*
* @type {number}
* @memberof Image
*/
public creationDate: number
public creationDate: number
/**
* Image delete date
*
*
* @type {string}
* @memberof Image
*/
public deleteDate: string
public deleteDate: string
/**
* Image URL address
*
*
* @type {string}
* @memberof Image
*/
public URL: string
public URL: string
/**
* Image folder name with image name {folderName/imageName}
*
*
* @type {string}
* @memberof Image
*/
public fullPath: string
public fullPath: string
/**
* Image owner identifier
*
*
* @type {string}
* @memberof Image
*/
public ownerUserId: string
public ownerUserId: string
/**
* Last edit date
*
*
* @type {number}
* @memberof Image
*/
public lastEditDate: number
public lastEditDate: number
/**
* If the image was deleted {true} or not {false}
*
*
* @type {Boolean}
* @memberof Image
*/
public deleted: Boolean
}
public deleted: Boolean
}

View File

@@ -1,45 +1,45 @@
import { BaseDomain } from 'domain/common'
export class Notification extends BaseDomain {
/**
* Description of notification
*
*
* @type {string}
* @memberof Notification
*/
public description: string
public description: string
/**
* The URL which notification refer to
*
*
* @type {string}
* @memberof Notification
*/
public url: string
public url: string
/**
* The identifier of the user who makes the notification
*
*
* @type {string}
* @memberof Notification
*/
public notifierUserId: string
public notifierUserId: string
/**
* The identifier of the user who receive the notification
*
*
* @type {string}
* @memberof Notification
*/
public notifyRecieverUserId: string
public notifyRecieverUserId: string
/**
* If the notification is seen {true} or not {false}
*
*
* @type {Boolean}
* @memberof Notification
*/
public isSeen: Boolean
}
public isSeen: Boolean
}

View File

@@ -1,10 +1,76 @@
import {IAuthorizeService} from 'services/authorize/IAuthorizeService'
export interface IServiceProvider{
/**
* Create authorize service
*
* @memberof IServiceProvider
*/
createAuthorizeService : () => IAuthorizeService
import { IAuthorizeService } from 'services/authorize/IAuthorizeService'
import { ICircleService } from 'services/circles'
import { ICommentService } from 'services/comments'
import { ICommonService } from 'services/common'
import { IImageGalleryService } from 'services/imageGallery'
import { INotificationService } from 'services/notifications'
import { IPostService } from 'services/posts'
import { IUserService } from 'services/users'
import { IVoteService } from 'services/votes'
}
export interface IServiceProvider {
/**
* Create authorize service
*
* @memberof IServiceProvider
*/
createAuthorizeService: () => IAuthorizeService
/**
* Create instant for Circle Service
*
* @memberof ServiceProvide
*/
createCircleService: () => ICircleService
/**
* Create instant for Comment Service
*
* @memberof ServiceProvide
*/
createCommentService: () => ICommentService
/**
* Create instant for Common Service
*
* @memberof ServiceProvide
*/
createCommonService: () => ICommonService
/**
* Create instant for ImageGallery Service
*
* @memberof ServiceProvide
*/
createImageGalleryService: () => IImageGalleryService
/**
* Create instant for Notification Service
*
* @memberof ServiceProvide
*/
createNotificationService: () => INotificationService
/**
* Create instant for Post Service
*
* @memberof ServiceProvide
*/
createPostService: () => IPostService
/**
* Create instant for User Service
*
* @memberof ServiceProvide
*/
createUserService: () => IUserService
/**
* Create instant for Vote Service
*
* @memberof ServiceProvide
*/
createVoteService: () => IVoteService
}

View File

@@ -2,25 +2,114 @@
import { IServiceProvider } from 'factories'
import { IAuthorizeService } from 'services/authorize'
import { ICircleService } from 'services/circles'
import { ICommentService } from 'services/comments'
import { ICommonService } from 'services/common'
import { IImageGalleryService } from 'services/imageGallery'
import { INotificationService } from 'services/notifications'
import { IPostService } from 'services/posts'
import { IUserService } from 'services/users'
import { IVoteService } from 'services/votes'
//#endregion
//#region Service implemented classes
// - Firebase services
import { AuthorizeService } from 'firebaseServices/authorize'
// - Firebase services
import { AuthorizeService } from 'firebaseServices/authorize'
import { CircleService } from 'firebaseServices/circles'
import { CommentService } from 'firebaseServices/comments'
import { CommonService } from 'firebaseServices/common'
import { ImageGalleryService } from 'firebaseServices/imageGallery'
import { NotificationService } from 'firebaseServices/notifications'
import { PostService } from 'firebaseServices/posts'
import { UserService } from 'firebaseServices/users'
import { VoteService } from 'firebaseServices/votes'
//#endregion
export class ServiceProvide implements IServiceProvider {
/**
* Create instant for AuthorizeService
*
* @memberof ServiceProvide
*/
createAuthorizeService: () => IAuthorizeService = () => {
return new AuthorizeService()
}
}
/**
* Create instant for Authorize Service
*
* @memberof ServiceProvide
*/
createAuthorizeService: () => IAuthorizeService = () => {
return new AuthorizeService()
}
/**
* Create instant for Circle Service
*
* @memberof ServiceProvide
*/
createCircleService: () => ICircleService = () => {
return new CircleService()
}
/**
* Create instant for Comment Service
*
* @memberof ServiceProvide
*/
createCommentService: () => ICommentService = () => {
return new CommentService()
}
/**
* Create instant for Common Service
*
* @memberof ServiceProvide
*/
createCommonService: () => ICommonService = () => {
return new CommonService()
}
/**
* Create instant for ImageGallery Service
*
* @memberof ServiceProvide
*/
createImageGalleryService: () => IImageGalleryService = () => {
return new ImageGalleryService()
}
/**
* Create instant for Notification Service
*
* @memberof ServiceProvide
*/
createNotificationService: () => INotificationService = () => {
return new NotificationService()
}
/**
* Create instant for Post Service
*
* @memberof ServiceProvide
*/
createPostService: () => IPostService = () => {
return new PostService()
}
/**
* Create instant for User Service
*
* @memberof ServiceProvide
*/
createUserService: () => IUserService = () => {
return new UserService()
}
/**
* Create instant for Vote Service
*
* @memberof ServiceProvide
*/
createVoteService: () => IVoteService = () => {
return new VoteService()
}
}

View File

@@ -30,10 +30,10 @@ export class AuthorizeService implements IAuthorizeService {
resolve(new LoginUser(result.uid))
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
reject(new SocialError(error.code, error.message))
})
})
}
})
}
/**
* Logs out the user
@@ -41,19 +41,19 @@ export class AuthorizeService implements IAuthorizeService {
* @returns {Promise<void>}
* @memberof IAuthorizeService
*/
public logout: () => Promise<void> = () => {
return new Promise<void>((resolve, reject) => {
firebaseAuth()
public logout: () => Promise<void> = () => {
return new Promise<void>((resolve, reject) => {
firebaseAuth()
.signOut()
.then((result) => {
resolve()
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
reject(new SocialError(error.code, error.message))
})
})
}
})
}
/**
* Register a user
@@ -61,24 +61,24 @@ export class AuthorizeService implements IAuthorizeService {
* @returns {Promise<void>}
* @memberof IAuthorizeService
*/
public registerUser: (user: User) => Promise<RegisterUserResult> = (user) => {
return new Promise<RegisterUserResult>((resolve, reject) => {
firebaseAuth()
public registerUser: (user: User) => Promise<RegisterUserResult> = (user) => {
return new Promise<RegisterUserResult>((resolve, reject) => {
firebaseAuth()
.createUserWithEmailAndPassword(user.email as string, user.password as string)
.then((signupResult) => {
firebaseRef.child(`users/${signupResult.uid}/info`)
firebaseRef.child(`users/${signupResult.uid}/info`)
.set({
...user,
...user,
avatar: 'noImage'
})
.then((result) => {
resolve(new RegisterUserResult(signupResult.uid))
resolve(new RegisterUserResult(signupResult.uid))
})
.catch((error: any) => reject(new SocialError(error.name, error.message)))
})
.catch((error: any) => reject(new SocialError(error.code, error.message)))
})
}
})
}
/**
* Update user password
@@ -87,25 +87,20 @@ export class AuthorizeService implements IAuthorizeService {
* @memberof IAuthorizeService
*/
public updatePassword: (newPassword: string) => Promise<void> = (newPassword) => {
console.log('====================================')
console.log('update password')
console.log('====================================')
return new Promise<void>((resolve, reject) => {
let user = firebaseAuth().currentUser
console.log('====================================')
console.log(user)
console.log('====================================')
if (user) {
user.updatePassword(newPassword).then(() => {
// Update successful.
resolve()
}).catch((error: any) => {
// An error happened.
reject(new SocialError(error.code, error.message))
})
}
return new Promise<void>((resolve, reject) => {
let user = firebaseAuth().currentUser
if (user) {
user.updatePassword(newPassword).then(() => {
// Update successful.
resolve()
}).catch((error: any) => {
// An error happened.
reject(new SocialError(error.code, error.message))
})
}
})
}
}

View File

@@ -1,7 +1,6 @@
// - Import react components
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { ICircleService } from 'services/circles'
import { Circle, UserFollower } from 'domain/circles'
@@ -9,19 +8,113 @@ import { User } from 'domain/users'
/**
* Firbase circle service
*
*
* @export
* @class CircleService
* @implements {ICircleService}
*/
export class CircleService implements ICircleService {
addCircle: (userId: string, circle: Circle) => Promise<string>
addFollowingUser: (userId: string, circleId: string, userCircle: User, userFollower: UserFollower, userFollowingId: string) => Promise<void>
deleteFollowingUser: (userId: string, circleId: string, userFollowingId: string) => Promise<void>
updateCircle: (userId: string, circle: Circle, circleId: string) => Promise<void>
deleteCircle: (circleId: string, userId: string) => Promise<void>
getCircles: () => Promise<{ [circleId: string]: Circle }>
getCirclesByUserId: (userId: string) => Promise<{ [circleId: string]: Circle }>
public addCircle: (userId: string, circle: Circle)
=> Promise<string> = (userId, circle) => {
return new Promise<string>((resolve,reject) => {
let circleRef = firebaseRef.child(`userCircles/${userId}/circles`).push(circle)
circleRef.then(() => {
resolve(circleRef.key as string)
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
}
})
}
public addFollowingUser: (userId: string, circleId: string, userCircle: User, userFollower: UserFollower, userFollowingId: string)
=> Promise<void> = (userId, circleId, userCircle, userFollower, userFollowingId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userCircles/${userId}/circles/${circleId}/users/${userFollowingId}`] = userCircle
updates[`userCircles/${userFollowingId}/circles/-Followers/users/${userId}`] = userFollower
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public deleteFollowingUser: (userId: string, circleId: string, userFollowingId: string)
=> Promise<void> = (userId, circleId, userFollowingId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userCircles/${userId}/circles/${circleId}/users/${userFollowingId}`] = null
updates[`userCircles/${userFollowingId}/circles/-Followers/users/${userId}`] = null
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public updateCircle: (userId: string, circleId: string, circle: Circle)
=> Promise<void> = (userId, circleId, circle) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userCircles/${userId}/circles/${circleId}`] = circle
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public deleteCircle: (userId: string, circleId: string)
=> Promise<void> = (userId, circleId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userCircles/${userId}/circles/${circleId}`] = null
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public getCircles: (userId: string) => Promise<{ [circleId: string]: Circle }> = (userId) => {
return new Promise<{ [circleId: string]: Circle }>((resolve,reject) => {
let circlesRef: any = firebaseRef.child(`userCircles/${userId}/circles`)
circlesRef.once('value').then((snapshot: any) => {
let circles: any = snapshot.val() || {}
let parsedCircles: { [circleId: string]: Circle } = {}
Object.keys(circles).forEach((circleId) => {
parsedCircles[circleId] = {
id: circleId,
...circles[circleId]
}
})
resolve(parsedCircles)
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
}

View File

@@ -1,5 +1,5 @@
import { AuthorizeService } from './CircleService'
import { CircleService } from './CircleService'
export {
AuthorizeService
}
CircleService
}

View File

@@ -3,15 +3,69 @@ import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { ICommentService } from 'services/comments'
import { Comment } from 'domain/comments'
/**
* Firbase comment service
*
*
* @export
* @class CommentService
* @implements {ICommentService}
*/
export class CommentService implements ICommentService {
public addComment: (postId: string, comment: Comment)
=> Promise<string> = (postId, comment) => {
return new Promise<string>((resolve,reject) => {
let commentRef: any = firebaseRef.child(`postComments/${postId}`).push(comment)
commentRef.then(() => {
resolve(commentRef.key)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public getComments: ()
=> Promise<{ [postId: string]: { [commentId: string]: Comment } }> = () => {
return new Promise<{ [postId: string]: { [commentId: string]: Comment }}>((resolve,reject) => {
let commentsRef: any = firebaseRef.child(`postComments`)
commentsRef.on('value', (snapshot: any) => {
let comments: {[postId: string]: {[commentId: string]: Comment}} = snapshot!.val() || {}
resolve(comments)
})
})
}
}
public updateComment: (userId: string, postId: string, comment: Comment)
=> Promise<void> = (userId, postId, comment) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`postComments/${postId}/${userId}`] = comment
firebaseRef.update(updates)
.then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public deleteComment: (commentId: string, postId: string)
=> Promise<void> = (commentId, postId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`postComments/${postId}/${commentId}`] = null
firebaseRef.update(updates)
.then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
}

View File

@@ -1,17 +1,110 @@
// - Import react components
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { firebaseRef, firebaseAuth, storageRef } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { IImageGalleryService } from 'services/imageGallery'
import { Image } from 'domain/imageGallery'
/**
* Firbase image gallery service
*
*
* @export
* @class ImageGalleryService
* @implements {IImageGalleryService}
*/
export class ImageGalleryService implements IImageGalleryService {
public getImageGallery: (userId: string)
=> Promise<Image[]> = (userId) => {
return new Promise<Image[]>((resolve,reject) => {
let imagesRef: any = firebaseRef.child(`userFiles/${userId}/files/images`)
}
imagesRef.once('value').then((snapshot: any) => {
let images = snapshot.val() || {}
let parsedImages: Image[] = []
Object.keys(images).forEach((imageId) => {
parsedImages.push({
id: imageId,
...images[imageId]
})
})
resolve(parsedImages)
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public saveImage: (userId: string, image: Image)
=> Promise<string> = (userId, image) => {
return new Promise<string>((resolve,reject) => {
let imageRef = firebaseRef.child(`userFiles/${userId}/files/images`).push(image)
imageRef.then(() => {
resolve(imageRef.key!)
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public deleteImage: (userId: string, imageId: string)
=> Promise<void> = (userId, imageId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userFiles/${userId}/files/images/${imageId}`] = null
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public uploadImage: (file: any, fileName: string, progressCallback: Function)
=> Promise<void> = (file, fileName, progressCallback) => {
return new Promise<void>((resolve,reject) => {
let storegeFile: any = storageRef.child(`images/${fileName}`)
// Upload file
let task: any = storegeFile.put(file)
// Upload storage bar
task.on('state_changed', (snapshot: any) => {
let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
progressCallback(percentage)
}, (error: any) => {
reject(new SocialError(error.code, error.message))
}, () => {
resolve()
})
})
}
public downloadImage: (fileName: string)
=> Promise<string> = (fileName) => {
return new Promise<string>((resolve,reject) => {
// 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) => {
resolve(url)
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
}

View File

@@ -2,16 +2,71 @@
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { Notification } from 'domain/notifications'
import { INotificationService } from 'services/notifications'
/**
* Firbase notification service
*
*
* @export
* @class NotificationService
* @implements {INotificationService}
*/
export class NotificationService implements INotificationService {
public addNotification: (notification: Notification)
=> Promise<void> = (notification: Notification) => {
return new Promise<void>((resolve,reject) => {
firebaseRef.child(`userNotifies/${notification.notifyRecieverUserId}`)
.push(notification)
.then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
}
public getNotifications: (userId: string)
=> Promise<{ [notifyId: string]: Notification }> = (userId) => {
return new Promise<{ [notifyId: string]: Notification }>((resolve,reject) => {
let notifiesRef: any = firebaseRef.child(`userNotifies/${userId}`)
notifiesRef.on('value', (snapshot: any) => {
let notifies: {[notifyId: string]: Notification} = snapshot.val() || {}
resolve(notifies)
})
})
}
public deleteNotification: (notificationId: string, userId: string)
=> Promise <void> = (notificationId, userId) => {
return new Promise<void>((resolve, reject) => {
let updates: any = {}
updates[`userNotifies/${userId}/${notificationId}`] = null
firebaseRef.update(updates)
.then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
public setSeenNotification: (notificationId: string, userId: string, notification: Notification)
=> Promise <void> = (notificationId, userId, notification) => {
return new Promise<void>((resolve, reject) => {
let updates: any = {}
updates[`userNotifies/${userId}/${notificationId}`] = notification
firebaseRef.update(updates)
.then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code, error.message))
})
})
}
}

View File

@@ -2,16 +2,100 @@
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { Post } from 'domain/posts'
import { IPostService } from 'services/posts'
/**
* Firbase post service
*
*
* @export
* @class PostService
* @implements {IPostService}
*/
export class PostService implements IPostService {
public addPost: (userId: string, post: Post)
=> Promise<string> = (userId, post) => {
return new Promise<string>((resolve,reject) => {
let postRef: any = firebaseRef.child(`userPosts/${userId}/posts`).push(post)
postRef.then(() => {
resolve(postRef.key)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
}
public updatePost: (userId: string, postId: string, post: Post)
=> Promise<void> = (userId, postId, post) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userPosts/${userId}/posts/${postId}`] = post
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public deletePost: (userId: string, postId: string)
=> Promise<void> = (userId, postId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`userPosts/${userId}/posts/${postId}`] = null
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public getPosts: (userId: string)
=> Promise<{ [postId: string]: Post }> = (userId) => {
return new Promise<{ [postId: string]: Post }>((resolve,reject) => {
let postsRef: any = firebaseRef.child(`userPosts/${userId}/posts`)
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]
}
})
resolve(parsedPosts)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public getPostById: (userId: string, postId: string)
=> Promise<Post> = (userId, postId) => {
return new Promise<Post>((resolve,reject) => {
let postsRef: any = firebaseRef.child(`userPosts/${userId}/posts/${postId}`)
postsRef.once('value').then((snapshot: any) => {
let newPost = snapshot.val() || {}
let post: Post = {
id: postId,
...newPost
}
resolve(post)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
}

View File

@@ -2,16 +2,72 @@
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { Profile } from 'domain/users'
import { IUserService } from 'services/users'
/**
* Firbase user service
*
*
* @export
* @class UserService
* @implements {IUserService}
*/
export class UserService implements IUserService {
public getUserProfile: (userId: string)
=> Promise<Profile> = (userId) => {
return new Promise<Profile>((resolve,reject) => {
let userProfileRef: any = firebaseRef.child(`users/${userId}/info`)
userProfileRef.once('value').then((snapshot: any) => {
let userProfile: Profile = snapshot.val() || {}
resolve(userProfile)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
}
public updateUserProfile: (userId: string, profile: Profile)
=> Promise<void> = (userId, profile) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`users/${userId}/info`] = profile
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public getUsersProfile: (userId: string)
=> Promise<{ [userId: string]: Profile }> = (userId) => {
return new Promise<{ [userId: string]: Profile }>((resolve,reject) => {
let usersProfileRef: any = firebaseRef.child(`users`)
usersProfileRef.once('value').then((snapshot: any) => {
let usersProfile: any = snapshot.val() || {}
let parsedusersProfile: {[userId: string]: Profile} = {}
Object.keys(usersProfile).forEach((userId) => {
if (userId !== userId) {
let userInfo = usersProfile[userId].info
parsedusersProfile[userId] = {
avatar: userInfo.avatar,
email: userInfo.email,
fullName: userInfo.fullName,
banner: userInfo.banner,
tagLine: userInfo.tagLine
}
}
})
resolve(parsedusersProfile)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
}

View File

@@ -2,16 +2,56 @@
import { firebaseRef, firebaseAuth } from 'app/firebase/'
import { SocialError } from 'domain/common'
import { Vote } from 'domain/votes'
import { IVoteService } from 'services/votes'
/**
* Firbase vote service
*
*
* @export
* @class VoteService
* @implements {IVoteService}
*/
export class VoteService implements IVoteService {
public addVote: (vote: Vote)
=> Promise<string> = (vote) => {
return new Promise<string>((resolve,reject) => {
let voteRef = firebaseRef.child(`postVotes/${vote.postId}`)
.push(vote)
voteRef.then(() => {
resolve(voteRef.key!)
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
public getVotes: ()
=> Promise<{ [postId: string]: { [voteId: string]: Vote } }> = () => {
return new Promise<{ [postId: string]: { [voteId: string]: Vote } }>((resolve,reject) => {
let votesRef: any = firebaseRef.child(`postVotes`)
}
votesRef.on('value',(snapshot: any) => {
let postVotes: {[postId: string]: {[voteId: string]: Vote}} = snapshot.val() || {}
resolve(postVotes)
})
})
}
public deleteVote: (voteId: string, postId: string)
=> Promise<void> = (voteId, postId) => {
return new Promise<void>((resolve,reject) => {
let updates: any = {}
updates[`postVotes/${postId}/${voteId}`] = null
firebaseRef.update(updates).then(() => {
resolve()
})
.catch((error: any) => {
reject(new SocialError(error.code,error.message))
})
})
}
}

View File

@@ -2,4 +2,4 @@ import { VoteService } from './VoteService'
export {
VoteService
}
}

View File

@@ -1,26 +1,25 @@
import { Circle } from 'domain/circles'
/**
* Circle state
*
* Circle state
*
* @export
* @class CircleState
*/
export class CircleState {
export class CircleState {
/**
* The list of Circles belong to users
*
*
* @type {({[userId: string]: {[circleId: string]: Circle}} | null)}
* @memberof CircleState
*/
userCircles: {[userId: string]: {[circleId: string]: Circle}} = {}
userCircles: {[userId: string]: {[circleId: string]: Circle}} = {}
/**
* If user circles are loaded {true} or not {false}
*
*
* @type {Boolean}
* @memberof CircleState
*/
loaded: Boolean = false
}
loaded: Boolean = false
}

View File

@@ -7,16 +7,15 @@ import { User } from 'domain/users'
import { Comment } from 'domain/comments'
// - Import action types
import {CommentActionType} from 'constants/commentActionType'
import { CommentActionType } from 'constants/commentActionType'
import { CommentState } from './CommentState'
import { ICommentAction } from './ICommentAction'
/**
* Comment reducer
* @param state
* @param action
* @param state
* @param action
*/
export let commentReducer = (state: CommentState = new CommentState(), action: ICommentAction) => {
let { payload } = action
@@ -31,7 +30,7 @@ export let commentReducer = (state: CommentState = new CommentState(), action: I
[payload.postId]: {
...state.postComments![payload.postId],
[payload.id]: {
...payload.comment,
...payload,
editorStatus: false
}
}
@@ -44,7 +43,7 @@ export let commentReducer = (state: CommentState = new CommentState(), action: I
postComments: {
...payload
},
loaded:true
loaded: true
}
case CommentActionType.UPDATE_COMMENT:
return {
@@ -112,12 +111,9 @@ export let commentReducer = (state: CommentState = new CommentState(), action: I
case CommentActionType.CLEAR_ALL_DATA_COMMENT:
return new CommentState()
default:
return state
}
}

View File

@@ -1,13 +1,13 @@
import {ImageGalleryActionType} from 'constants/imageGalleryActionType'
import { ImageGalleryActionType } from 'constants/imageGalleryActionType'
/**
* ImageGallery action interface
*
*
* @export
* @interface IImageGalleryAction
*/
export interface IImageGalleryAction {
payload: any,
type: ImageGalleryActionType
}
export interface IImageGalleryAction {
payload: any,
type: ImageGalleryActionType
}

View File

@@ -6,16 +6,15 @@ import _ from 'lodash'
import { Notification } from 'domain/notifications'
// - Import action types
import {NotificationActionType} from 'constants/notificationActionType'
import { NotificationActionType } from 'constants/notificationActionType'
import { NotificationState } from './NotificationState'
import { INotificationAction } from './INotificationAction'
/**
* Notify actions
* @param {object} state
* @param {object} action
* @param {object} state
* @param {object} action
*/
export let notificationReducer = (state: NotificationState = new NotificationState(), action: INotificationAction) => {
let { payload } = action
@@ -24,29 +23,29 @@ export let notificationReducer = (state: NotificationState = new NotificationSta
/* _____________ CRUD _____________ */
case NotificationActionType.ADD_NOTIFY:
return state
case NotificationActionType.ADD_NOTIFY_LIST:
return {
...state,
userNotifies: {
...payload
},
loaded:true
loaded: true
}
case NotificationActionType.SEEN_NOTIFY:
case NotificationActionType.SEEN_NOTIFY:
return {
...state,
userNotifies: {
...state.userNotifies,
[payload]:{
[payload]: {
...state.userNotifies![payload],
isSeen:true
isSeen: true
}
},
loaded:true
loaded: true
}
case NotificationActionType.DELETE_NOTIFY:
let parsedNotifies = {}
Object.keys(state.userNotifies!).map((id) => {
@@ -58,19 +57,16 @@ export let notificationReducer = (state: NotificationState = new NotificationSta
return {
...state,
userNotifies: {
...parsedNotifies
...parsedNotifies
}
}
case NotificationActionType.CLEAR_ALL_DATA_NOTIFY:
return new NotificationState()
default:
return state
}
}

View File

@@ -1,13 +1,13 @@
import {UserActionType} from 'constants/userActionType'
import { UserActionType } from 'constants/userActionType'
/**
* User action interface
*
*
* @export
* @interface IUserAction
*/
export interface IUserAction {
payload: any,
type: UserActionType
}
export interface IUserAction {
payload: any,
type: UserActionType
}

View File

@@ -1,12 +1,9 @@
import { User } from 'domain/users'
import { LoginUser, RegisterUserResult } from 'domain/authorize'
/**
* Authentication service interface
*
*
* @export
* @interface IAuthorizeService
*/
@@ -14,28 +11,28 @@ export interface IAuthorizeService {
/**
* Login the user
*
*
* @returns {Promise<void>}
* @memberof IAuthorizeService
*/
login: (email: string, password: string) => Promise<LoginUser>
login: (email: string, password: string) => Promise<LoginUser>
/**
/**
* Logs out the user
*
* @returns {Promise<void>}
* @memberof IAuthorizeService
*/
logout: () => Promise<void>
logout: () => Promise<void>
/**
* @returns {Promise<void>}
*/
updatePassword: (newPassword: string) => Promise<void>
updatePassword: (newPassword: string) => Promise<void>
/**
* @returns {Promise<void>}
*/
registerUser: (user: User) => Promise<RegisterUserResult>
registerUser: (user: User) => Promise<RegisterUserResult>
}

View File

@@ -2,4 +2,4 @@ import { IAuthorizeService } from './IAuthorizeService'
export {
IAuthorizeService
}
}

View File

@@ -3,17 +3,16 @@ import { Circle, UserFollower } from 'domain/circles'
/**
* Circle service interface
*
*
* @export
* @interface ICircleService
*/
export interface ICircleService {
addCircle: (userId: string, circle: Circle) => Promise<string>
addFollowingUser: (userId: string, circleId:string, userCircle: User, userFollower: UserFollower, userFollowingId: string) => Promise<void>
deleteFollowingUser: (userId: string, circleId: string,userFollowingId: string) => Promise<void>
updateCircle: (userId: string, circle: Circle, circleId: string) => Promise<void>
deleteCircle: (circleId: string, userId: string) => Promise<void>
getCircles: () => Promise<{ [circleId: string]: Circle }>
getCirclesByUserId: (userId: string) => Promise<{ [circleId: string]: Circle }>
}
addCircle: (userId: string, circle: Circle) => Promise<string>
addFollowingUser: (userId: string, circleId: string, userCircle: User, userFollower: UserFollower, userFollowingId: string) => Promise<void>
deleteFollowingUser: (userId: string, circleId: string,userFollowingId: string) => Promise<void>
updateCircle: (userId: string, circleId: string, circle: Circle) => Promise<void>
deleteCircle: (userId: string, circleId: string) => Promise<void>
getCircles: (userId: string) => Promise<{ [circleId: string]: Circle }>
}

View File

@@ -1,15 +1,18 @@
import { User } from 'domain/users'
import { Comment } from 'domain/comments'
/**
* Comment service interface
*
*
* @export
* @interface ICommentService
*/
export interface ICommentService {
addComment: (postId: string, comment: Comment) => Promise<string>
getComments: () => Promise< {[postId: string]: {[commentId: string]: Comment}} >
updateComment: (userId: string, postId: string, comment: Comment) => Promise<void>
deleteComment: (commentId: string, postId: string) => Promise<void>
}
}

View File

@@ -2,4 +2,4 @@ import { ICommentService } from './ICommentService'
export {
ICommentService
}
}

View File

@@ -1,16 +1,11 @@
import { User } from 'domain/users'
/**
* Common service interface
*
*
* @export
* @interface ICommonService
*/
export interface ICommonService {
}
}

View File

@@ -2,4 +2,4 @@ import { ICommonService } from './ICommonService'
export {
ICommonService
}
}

View File

@@ -1,15 +1,16 @@
import { User } from 'domain/users'
import { Image } from 'domain/imageGallery'
/**
* Image gallery service interface
*
*
* @export
* @interface IImageGalleryService
*/
export interface IImageGalleryService {
}
getImageGallery: (userId: string) => Promise<Image[]>
saveImage: (userId: string, image: Image) => Promise<string>
deleteImage: (userId: string, imageId: string) => Promise<void>
uploadImage: (file: any, fileName: string, progressCallback: Function) => Promise<void>
downloadImage: (fileName: string) => Promise<string>
}

View File

@@ -2,4 +2,4 @@ import { IImageGalleryService } from './IImageGalleryService'
export {
IImageGalleryService
}
}

View File

@@ -1,15 +1,16 @@
import { User } from 'domain/users'
import { Notification } from 'domain/notifications'
/**
* Notification service interface
*
*
* @export
* @interface INotificationService
*/
export interface INotificationService {
}
addNotification: (notification: Notification) => Promise<void>
getNotifications: (userId: string) => Promise<{[notifyId: string]: Notification}>
deleteNotification: (notificationId: string, userId: string) => Promise<void>
setSeenNotification: (notificationId: string, userId: string, notification: Notification) => Promise<void>
}

View File

@@ -1,15 +1,16 @@
import { User } from 'domain/users'
import { Post } from 'domain/posts'
/**
* Post service interface
*
*
* @export
* @interface IPostService
*/
export interface IPostService {
}
addPost: (userId: string, post: Post) => Promise<string>
updatePost: (userId: string, postId: string, post: Post) => Promise<void>
deletePost: (userId: string,postId: string) => Promise<void>
getPosts: (userId: string) => Promise<{ [postId: string]: Post }>
getPostById: (userId: string, postId: string) => Promise<Post>
}

View File

@@ -2,4 +2,4 @@ import { IPostService } from './IPostService'
export {
IPostService
}
}

View File

@@ -1,15 +1,13 @@
import { User } from 'domain/users'
import { User, Profile } from 'domain/users'
/**
* User service interface
*
*
* @export
* @interface IUserService
*/
export interface IUserService {
}
getUserProfile: (userId: string) => Promise<Profile>
updateUserProfile: (userId: string, profile: Profile) => Promise<void>
getUsersProfile: (userId: string) => Promise<{[userId: string]: Profile}>
}

View File

@@ -2,4 +2,4 @@ import { IUserService } from './IUserService'
export {
IUserService
}
}

View File

@@ -1,4 +1,5 @@
import { User } from 'domain/users'
import { Vote } from 'domain/votes'
/**
* Vote service interface
@@ -7,5 +8,7 @@ import { User } from 'domain/users'
* @interface IVoteService
*/
export interface IVoteService {
addVote: (vote: Vote) => Promise<string>
getVotes: () => Promise<{[postId: string]: {[voteId: string]: Vote}}>
deleteVote: (voteId: string, postId: string) => Promise<void>
}

View File

@@ -2,4 +2,4 @@ import { IVoteService } from './IVoteService'
export {
IVoteService
}
}