Migrate post{actions,actionType,reducer} to TypeScript

This commit is contained in:
Qolzam
2017-10-07 12:59:58 +07:00
parent 418453dd02
commit 1810550331
7 changed files with 395 additions and 354 deletions

View File

@@ -1,340 +0,0 @@
// - Import firebase component
import firebase, {firebaseRef} from 'app/firebase/'
// - Import utility components
import moment from 'moment'
// - Import action types
import * as types from 'actionTypes'
// - Import actions
import * as globalActions from 'globalActions'
/* _____________ CRUD DB _____________ */
/**
* Add a normal post
* @param {object} newPost
* @param {function} callBack
*/
export var dbAddPost = (newPost,callBack) => {
return(dispatch,getState) => {
var uid = getState().authorize.uid
var post = {
postTypeId: 0,
creationDate: moment().unix(),
deletationDate: '',
score: 0,
viewCount: 0,
body: newPost.body,
ownerUserId: uid,
ownerDisplayName: newPost.name,
ownerAvatar: newPost.avatar,
lastEditDate: '',
tags: newPost.tags || [],
commentCounter: 0,
image:'',
video:'',
disableComments: newPost.disableComments,
disableSharing: newPost.disableSharing,
deleted:false
}
var postRef = firebaseRef.child(`userPosts/${uid}/posts`).push(post)
return postRef.then(()=>{
dispatch(addPost(uid,{
...post,
id: postRef.key
}))
callBack()
},(error) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
/**
* Add a post with image
* @param {object} newPost
* @param {function} callBack
*/
export const dbAddImagePost = (newPost,callBack) => {
return(dispatch,getState) => {
dispatch(globalActions.showTopLoading())
var uid = getState().authorize.uid
var post = {
postTypeId: 1,
creationDate: moment().unix(),
deletationDate: '',
score: 0,
viewCount: 0,
body: newPost.body,
ownerUserId: uid,
ownerDisplayName: newPost.name,
ownerAvatar: newPost.avatar,
lastEditDate: '',
tags: newPost.tags || [],
commentCounter: 0,
image: newPost.image || '',
imageFullPath: newPost.imageFullPath || '',
video:'',
disableComments: newPost.disableComments ? newPost.disableComments : false,
disableSharing: newPost.disableSharing ? newPost.disableSharing : false,
deleted:false
}
var postRef = firebaseRef.child(`userPosts/${uid}/posts`).push(post)
return postRef.then(()=>{
dispatch(addPost(uid,{
...post,
id: postRef.key
}))
callBack()
dispatch(globalActions.hideTopLoading())
})
}
}
/**
* Update a post from database
* @param {object} newPost
* @param {func} callBack //TODO: anti pattern should change to parent state or move state to redux
*/
export const dbUpdatePost = (newPost,callBack) => {
console.log(newPost)
return (dispatch, getState) => {
dispatch(globalActions.showTopLoading())
// Get current user id
var uid = getState().authorize.uid
// Write the new data simultaneously in the list
let updates = {};
let post = getState().post.userPosts[uid][newPost.id]
let updatedPost = {
postTypeId: post.postTypeId,
creationDate: post.creationDate,
deletationDate: '',
score: post.score,
viewCount: post.viewCount,
body: newPost.body ? newPost.body : post.body || '',
ownerUserId: uid,
ownerDisplayName: post.ownerDisplayName,
ownerAvatar: post.ownerAvatar,
lastEditDate: moment().unix(),
tags: newPost.tags ? newPost.tags : (post.tags || []),
commentCounter: post.commentCounter,
image: newPost.image ? newPost.image : post.image,
video:'',
disableComments: newPost.disableComments !== undefined ? newPost.disableComments : (post.disableComments ? post.disableComments : false),
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) => {
dispatch(updatePost(uid,{id:newPost.id, ...updatedPost}))
callBack()
dispatch(globalActions.hideTopLoading())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
}
}
/**
* Delete a post from database
* @param {string} id is post identifier
*/
export const dbDeletePost = (id) => {
return (dispatch, getState) => {
dispatch(globalActions.showTopLoading())
// Get current user id
var uid = getState().authorize.uid
// Write the new data simultaneously in the list
var updates = {};
updates[`userPosts/${uid}/posts/${id}`] = null;
return firebaseRef.update(updates).then((result) => {
dispatch(deletePost(uid,id))
dispatch(globalActions.hideTopLoading())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
});
}
}
/**
* Get all user posts from data base
*/
export const dbGetPosts = () => {
return (dispatch, getState) => {
var uid = getState().authorize.uid
if (uid) {
var postsRef = firebaseRef.child(`userPosts/${uid}/posts`);
return postsRef.once('value').then((snapshot) => {
var posts = snapshot.val() || {};
var parsedPosts = {};
Object.keys(posts).forEach((postId) => {
parsedPosts[postId]={
id: postId,
...posts[postId]
};
});
dispatch(addPosts(uid,parsedPosts));
});
}
}
}
/**
* Get all user posts from data base
*/
export const dbGetPostById = (uid,postId) => {
return (dispatch, getState) => {
if (uid) {
var postsRef = firebaseRef.child(`userPosts/${uid}/posts/${postId}`);
return postsRef.once('value').then((snapshot) => {
const newPost = snapshot.val() || {};
const post = {
id : postId,
...newPost
}
dispatch(addPost(uid,post));
});
}
}
}
/**
* Get all user posts from data base by user id
*/
export const dbGetPostsByUserId = (uid) => {
return (dispatch, getState) => {
if (uid) {
var postsRef = firebaseRef.child(`userPosts/${uid}/posts`);
return postsRef.once('value').then((snapshot) => {
var posts = snapshot.val() || {};
var parsedPosts = {};
Object.keys(posts).forEach((postId) => {
parsedPosts[postId]={
id: postId,
...posts[postId]
};
});
dispatch(addPosts(uid,parsedPosts));
});
}
}
}
/* _____________ CRUD State _____________ */
/**
* Add a normal post
* @param {string} uid is user identifier
* @param {object} post
*/
export const addPost = (uid,post) => {
return{
type: types.ADD_POST,
payload: {uid,post}
}
}
/**
* Update a post
* @param {string} uid is user identifier
* @param {object} post
*/
export const updatePost = (uid,post) => {
return{
type: types.UPDATE_POST,
payload: {uid,post}
}
}
/**
* Delete a post
* @param {string} uid is user identifier
* @param {string} id is post identifier
*/
export const deletePost = (uid,id) => {
return{
type: types.DELETE_POST,
payload: {uid,id}
}
}
/**
* Add a list of post
* @param {string} uid
* @param {[object]} posts
*/
export const addPosts = (uid,posts) => {
return {
type: types.ADD_LIST_POST,
payload: {uid,posts}
}
}
/**
* Clea all data in post store
*/
export const clearAllData = () => {
return{
type: types.CLEAR_ALL_DATA_POST
}
}
/**
* Add a post with image
* @param {object} post
*/
export const addImagePost = (uid,post) => {
return{
type: types.ADD_IMAGE_POST,
payload: {uid,post}
}
}

343
app/actions/postActions.ts Normal file
View File

@@ -0,0 +1,343 @@
// - Import react components
import { Action } from "redux";
// - Import firebase component
import firebase, { firebaseRef } from '../firebase';
// - Import utility components
import moment from 'moment';
// - Import action types
import { postActionType } from 'constants/postActionType';
// - Import actions
import * as globalActions from 'actions/globalActions';
/* _____________ CRUD DB _____________ */
/**
* Add a normal post
* @param {object} newPost
* @param {function} callBack
*/
export var dbAddPost = (newPost: any, callBack: any) => {
return (dispatch: any, getState: any) => {
var uid = getState().authorize.uid
var post = {
postTypeId: 0,
creationDate: moment().unix(),
deletationDate: '',
score: 0,
viewCount: 0,
body: newPost.body,
ownerUserId: uid,
ownerDisplayName: newPost.name,
ownerAvatar: newPost.avatar,
lastEditDate: '',
tags: newPost.tags || [],
commentCounter: 0,
image: '',
video: '',
disableComments: newPost.disableComments,
disableSharing: newPost.disableSharing,
deleted: false
}
var postRef = firebaseRef.child(`userPosts/${uid}/posts`).push(post)
return postRef.then(() => {
dispatch(addPost(uid, {
...post,
id: postRef.key
}))
callBack()
}, (error: any) => dispatch(globalActions.showErrorMessage(error.message)))
}
}
/**
* Add a post with image
* @param {object} newPost
* @param {function} callBack
*/
export const dbAddImagePost = (newPost: any, callBack: any) => {
return (dispatch: any, getState: any) => {
dispatch(globalActions.showTopLoading())
var uid = getState().authorize.uid
var post = {
postTypeId: 1,
creationDate: moment().unix(),
deletationDate: '',
score: 0,
viewCount: 0,
body: newPost.body,
ownerUserId: uid,
ownerDisplayName: newPost.name,
ownerAvatar: newPost.avatar,
lastEditDate: '',
tags: newPost.tags || [],
commentCounter: 0,
image: newPost.image || '',
imageFullPath: newPost.imageFullPath || '',
video: '',
disableComments: newPost.disableComments ? newPost.disableComments : false,
disableSharing: newPost.disableSharing ? newPost.disableSharing : false,
deleted: false
}
let postRef : any = firebaseRef.child(`userPosts/${uid}/posts`).push(post)
return postRef.then(() => {
dispatch(addPost(uid, {
...post,
id: postRef.key
}))
callBack()
dispatch(globalActions.hideTopLoading())
})
}
}
/**
* Update a post from database
* @param {object} newPost
* @param {func} callBack //TODO: anti pattern should change to parent state or move state to redux
*/
export const dbUpdatePost = (newPost: any, callBack: any) => {
console.log(newPost)
return (dispatch : any, getState: any) => {
dispatch(globalActions.showTopLoading())
// Get current user id
let uid: string = getState().authorize.uid
// Write the new data simultaneously in the list
let updates: any = {};
let post = getState().post.userPosts[uid][newPost.id]
let updatedPost = {
postTypeId: post.postTypeId,
creationDate: post.creationDate,
deletationDate: '',
score: post.score,
viewCount: post.viewCount,
body: newPost.body ? newPost.body : post.body || '',
ownerUserId: uid,
ownerDisplayName: post.ownerDisplayName,
ownerAvatar: post.ownerAvatar,
lastEditDate: moment().unix(),
tags: newPost.tags ? newPost.tags : (post.tags || []),
commentCounter: post.commentCounter,
image: newPost.image ? newPost.image : post.image,
video: '',
disableComments: newPost.disableComments !== undefined ? newPost.disableComments : (post.disableComments ? post.disableComments : false),
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) => {
dispatch(updatePost(uid, { id: newPost.id, ...updatedPost }))
callBack()
dispatch(globalActions.hideTopLoading())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
}
}
/**
* Delete a post from database
* @param {string} id is post identifier
*/
export const dbDeletePost = (id: string) => {
return (dispatch:any, getState:any) => {
dispatch(globalActions.showTopLoading())
// Get current user id
let uid : string = getState().authorize.uid
// Write the new data simultaneously in the list
var updates : any= {};
updates[`userPosts/${uid}/posts/${id}`] = null;
return firebaseRef.update(updates).then((result) => {
dispatch(deletePost(uid, id))
dispatch(globalActions.hideTopLoading())
}, (error) => {
dispatch(globalActions.showErrorMessage(error.message))
dispatch(globalActions.hideTopLoading())
});
}
}
/**
* Get all user posts from data base
*/
export const dbGetPosts = () => {
return (dispatch:any, getState:any) => {
var uid = getState().authorize.uid
if (uid) {
var postsRef = firebaseRef.child(`userPosts/${uid}/posts`);
return postsRef.once('value').then((snapshot) => {
var posts = snapshot.val() || {};
var parsedPosts : any = {};
Object.keys(posts).forEach((postId) => {
parsedPosts[postId] = {
id: postId,
...posts[postId]
};
});
dispatch(addPosts(uid, parsedPosts));
});
}
}
}
/**
* Get all user posts from data base
*/
export const dbGetPostById = (uid:string, postId:string) => {
return (dispatch: any, getState: any) => {
if (uid) {
var postsRef = firebaseRef.child(`userPosts/${uid}/posts/${postId}`);
return postsRef.once('value').then((snapshot) => {
const newPost = snapshot.val() || {};
const post = {
id: postId,
...newPost
}
dispatch(addPost(uid, post));
});
}
}
}
/**
* Get all user posts from data base by user id
*/
export const dbGetPostsByUserId = (uid: string) => {
return (dispatch: any, getState: any) => {
if (uid) {
let postsRef = firebaseRef.child(`userPosts/${uid}/posts`);
return postsRef.once('value').then((snapshot) => {
let posts = snapshot.val() || {};
let parsedPosts: any = {};
Object.keys(posts).forEach((postId) => {
parsedPosts[postId] = {
id: postId,
...posts[postId]
};
});
dispatch(addPosts(uid, parsedPosts));
});
}
}
}
/* _____________ CRUD State _____________ */
/**
* Add a normal post
* @param {string} uid is user identifier
* @param {object} post
*/
export const addPost = (uid: string, post: any) => {
return {
type: postActionType.ADD_POST,
payload: { uid, post }
}
}
/**
* Update a post
* @param {string} uid is user identifier
* @param {object} post
*/
export const updatePost = (uid: string, post: any) => {
return {
type: postActionType.UPDATE_POST,
payload: { uid, post }
}
}
/**
* Delete a post
* @param {string} uid is user identifier
* @param {string} id is post identifier
*/
export const deletePost = (uid: string, id: string) => {
return {
type: postActionType.DELETE_POST,
payload: { uid, id }
}
}
/**
* Add a list of post
* @param {string} uid
* @param {[object]} posts
*/
export const addPosts = (uid: string, posts: any) => {
return {
type: postActionType.ADD_LIST_POST,
payload: { uid, posts }
}
}
/**
* Clea all data in post store
*/
export const clearAllData = () => {
return {
type: postActionType.CLEAR_ALL_DATA_POST
}
}
/**
* Add a post with image
* @param {object} post
*/
export const addImagePost = (uid: string, post: any) => {
return {
type: postActionType.ADD_IMAGE_POST,
payload: { uid, post }
}
}

View File

@@ -0,0 +1,11 @@
export enum postActionType {
ADD_IMAGE_POST = "ADD_IMAGE_POST",
ADD_VIDEO_POST = "ADD_VIDEO_POST",
ADD_POST = "ADD_POST",
UPDATE_POST = "UPDATE_POST",
DELETE_POST = "DELETE_POST",
ADD_LIST_POST = "ADD_LIST_POST",
CLEAR_ALL_DATA_POST = "CLEAR_ALL_DATA_POST"
};

View File

@@ -2,34 +2,58 @@
var uuid = require('uuid');
import moment from 'moment'
import _ from 'lodash'
import {Reducer, Action} from "redux";
// - Import action types
import * as types from 'actionTypes'
import { postActionType } from "constants/postActionType";
/* ---------------- */
// - Import react components
/**
* Default State
* Default post state
*
* @export
* @interface IPostState
*/
var defaultState = {
userPosts: {},
loaded: false
export interface IPostState {
userPosts: any,
loaded: boolean
}
/**
*
*
* @export
* @interface postState
*/
export interface IPostAction {
payload: any,
type: postActionType
}
export class defaultPostState implements IPostState{
userPosts: any = {};
loaded: boolean = false;
}
/**
* Post reducer
* @param {object} state
* @param {object} action
*/
export var postReducer = (state = defaultState, action) => {
export var postReducer = (state : IPostState = new defaultPostState(), action : IPostAction) => {
const { payload } = action
switch (action.type) {
case types.CLEAR_ALL_DATA_POST:
return defaultState
case postActionType.CLEAR_ALL_DATA_POST:
return new defaultPostState()
case types.ADD_IMAGE_POST:
case postActionType.ADD_IMAGE_POST:
return {
...state,
userPosts: {
@@ -41,7 +65,7 @@ export var postReducer = (state = defaultState, action) => {
}
}
case types.ADD_POST:
case postActionType.ADD_POST:
return {
...state,
userPosts: {
@@ -53,7 +77,7 @@ export var postReducer = (state = defaultState, action) => {
}
}
case types.UPDATE_POST:
case postActionType.UPDATE_POST:
return {
...state,
userPosts: {
@@ -68,7 +92,7 @@ export var postReducer = (state = defaultState, action) => {
}
}
case types.DELETE_POST:
case postActionType.DELETE_POST:
let filteredPosts = {}
Object.keys(state.userPosts[payload.uid]).map((key) => {
if (key !== payload.id) {
@@ -84,7 +108,7 @@ export var postReducer = (state = defaultState, action) => {
}
}
}
case types.ADD_LIST_POST:
case postActionType.ADD_LIST_POST:
return {
...state,
userPosts: {

View File

@@ -50,3 +50,4 @@ var store : redux.Store<{}> = redux.createStore(reducer, initialState, redux.co
))
export default store

View File

@@ -52,6 +52,7 @@
"uuid": "^3.0.1"
},
"devDependencies": {
"@types/lodash": "^4.14.77",
"@types/material-ui": "^0.18.2",
"@types/node": "^8.0.33",
"@types/react": "^16.0.10",

View File

@@ -82,10 +82,11 @@ module.exports = {
app: 'app',
components: 'app/components',
reducers: 'app/reducers',
constants: 'app/constants',
db: 'app/db',
store: 'app/store',
applicationStyles: 'app/styles/app.scss',
actions: 'app/actions/actions.jsx',
actions: 'app/actions',
actionTypes: 'app/constants/actionTypes.jsx',
configureStore: 'app/store/configureStore.jsx'