forked from osdio/noder-react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopic.js
More file actions
138 lines (123 loc) · 2.39 KB
/
topic.js
File metadata and controls
138 lines (123 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import * as types from '../constants/ActionTypes';
const initialState = {
ask: [],
share: [],
job: [],
good: [],
all: [],
topics: {}
};
function indexOf(id, arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id == id) {
return i;
}
}
return -1;
}
function remove(id, arr) {
let index = arr.indexOf(id);
let result = arr.concat([]);
if (index > -1) {
result.splice(index, 1);
}
return result;
}
function upReply(topicId, replyId, userId, state, isUp) {
let topic = state.topics[topicId];
if (!topic) return state;
let replies = topic.replies.concat([]);
let index = indexOf(replyId, replies);
if (index == -1) return state;
let reply = {
...replies[index]
};
if (isUp) {
// up reply
reply.ups = reply.ups.concat([userId]);
}
else {
// down reply
reply.ups = remove(userId, reply.ups);
}
replies[index] = reply;
return {
...state,
topics: {
...state.topics,
[topicId]: {
...topic,
replies: replies
}
}
};
}
function reply(topicId, replyId, content, user, state, id) {
let topic = state.topics[topicId];
if (!topic) return state;
let replies = topic.replies.concat([{
id,
content,
reply_id: replyId,
create_at: new Date(),
ups: [],
author: user
}]);
return {
...state,
topics: {
...state.topics,
[topicId]: {
...topic,
replies: replies
}
}
}
}
export default function (state = initialState, action) {
const {payload, error, meta = {}, type} = action;
const {sequence = {}, tab, id = '0', replyId = '0', userId = '0', content = '', user = {}} = meta;
if (sequence.type === 'start' || error) {
return state;
}
switch (type) {
case types.GET_REDUCER_FROM_ASYNC_STORAGE:
return {
...state,
...payload.topic || initialState
};
case types.GET_TOPICS_BY_TAB:
return {
...state,
[tab]: state[tab].concat(payload)
};
case types.UPDATE_TOPICS_BY_TAB:
return {
...state,
[tab]: payload
};
case types.GET_TOPIC_BY_ID:
return {
...state,
topics: {
...state.topics,
[id]: payload
}
};
case types.REMOVE_TOPIC_CACHE_BY_ID:
delete state.topics[id];
return {
...state,
topics: {
...state.topics,
[id]: undefined
}
};
case types.UP_REPLY:
return upReply(id, replyId, userId, state, payload);
case types.REPLY_TOPIC_BY_ID:
return reply(id, replyId, content, user, state, payload);
default:
return state;
}
}