refactor: rename contact with user

This commit is contained in:
Tristan Yang
2022-07-04 16:12:23 +08:00
parent 6083040e2b
commit 101dbdb5ee
76 changed files with 319 additions and 286 deletions
+2 -2
View File
@@ -8,8 +8,8 @@ const tables = [
description: "store channel list"
},
{
storeName: "contacts",
description: "store contact list"
storeName: "users",
description: "store user list"
},
{
storeName: "messageDM",
+5 -5
View File
@@ -6,7 +6,7 @@ import { fullfillMessage } from "../slices/message";
import { fullfillChannelMsg } from "../slices/message.channel";
import { fullfillUserMsg } from "../slices/message.user";
import { fullfillChannels } from "../slices/channels";
import { fullfillContacts } from "../slices/contacts";
import { fullfillContacts } from "../slices/users";
import { fullfillFootprint } from "../slices/footprint";
import { fullfillFileMessage } from "../slices/message.file";
import { fullfillUI } from "../slices/ui";
@@ -17,7 +17,7 @@ const useRehydrate = () => {
const rehydrate = async () => {
const rehydrateData = {
channels: [],
contacts: [],
users: [],
fileMessage: {},
channelMessage: {},
userMessage: {},
@@ -38,9 +38,9 @@ const useRehydrate = () => {
rehydrateData.channels.push(data);
}
break;
case "contacts":
case "users":
if (data) {
rehydrateData.contacts.push(data);
rehydrateData.users.push(data);
}
break;
case "footprint":
@@ -75,7 +75,7 @@ const useRehydrate = () => {
})
);
batch(() => {
dispatch(fullfillContacts(rehydrateData.contacts));
dispatch(fullfillContacts(rehydrateData.users));
dispatch(fullfillServer(rehydrateData.server));
console.log("fullfill channels from indexedDB");
dispatch(fullfillChannels(rehydrateData.channels));
@@ -1,17 +1,17 @@
import clearTable from "./clear.handler";
export default async function handler({ operation, data, payload }) {
const table = window.CACHE["contacts"];
const table = window.CACHE["users"];
if (operation.startsWith("reset")) {
clearTable("contacts");
clearTable("users");
return;
}
switch (operation) {
case "fullfillContacts":
{
const contacts = payload;
const users = payload;
await Promise.all(
contacts.map(({ uid, ...rest }) => {
users.map(({ uid, ...rest }) => {
return table.setItem(uid + "", { uid, ...rest });
})
);
+4 -4
View File
@@ -1,7 +1,7 @@
import { createListenerMiddleware } from "@reduxjs/toolkit";
import rtkqHandler from "./handler.rtkq";
import channelsHandler from "./handler.channels";
import contactsHandler from "./handler.contacts";
import usersHandler from "./handler.users";
import channelMsgHandler from "./handler.channel.msg";
import dmMsgHandler from "./handler.dm.msg";
import serverHandler from "./handler.server";
@@ -15,7 +15,7 @@ const operations = [
"__rtkq",
"channels",
"channelMessage",
"contacts",
"users",
"userMessage",
"reactionMessage",
"fileMessage",
@@ -65,9 +65,9 @@ listenerMiddleware.startListening({
});
}
break;
case "contacts":
case "users":
{
await contactsHandler({
await usersHandler({
operation,
payload,
data: state
+2 -1
View File
@@ -3,6 +3,7 @@ import toast from "react-hot-toast";
import dayjs from "dayjs";
import { updateToken, resetAuthData } from "../slices/auth.data";
import BASE_URL, { tokenHeader } from "../config";
import { RootState } from "../store";
const whiteList = [
"login",
@@ -28,7 +29,7 @@ const baseQuery = fetchBaseQuery({
baseUrl: BASE_URL,
prepareHeaders: (headers, { getState, endpoint }) => {
console.log("req", endpoint);
const { token } = getState().authData;
const { token } = (getState() as RootState).authData;
if (token && !whiteList.includes(endpoint)) {
headers.set(tokenHeader, token);
}
+12 -11
View File
@@ -9,19 +9,20 @@ import { removeChannelSession } from "../slices/message.channel";
import { removeReactionMessage } from "../slices/message.reaction";
import { onMessageSendStarted } from "./handlers";
import handleChatMessage from "../../common/hook/useStreaming/chat.handler";
import { Channel, CreateChannelDTO } from "../../types/channel";
import { RootState } from "../store";
export const channelApi = createApi({
reducerPath: "channelApi",
baseQuery,
refetchOnFocus: true,
endpoints: (builder) => ({
getChannels: builder.query({
getChannels: builder.query<Channel[], void>({
query: () => ({ url: `group` })
}),
getChannel: builder.query({
getChannel: builder.query<Channel, number>({
query: (id) => ({ url: `group/${id}` })
}),
leaveChannel: builder.query({
leaveChannel: builder.query<void, number>({
query: (id) => ({ url: `group/${id}/leave` }),
async onQueryStarted(gid, { dispatch, queryFulfilled }) {
try {
@@ -32,7 +33,7 @@ export const channelApi = createApi({
}
}
}),
createChannel: builder.mutation({
createChannel: builder.mutation<number, CreateChannelDTO>({
query: (data) => ({
url: "group",
method: "POST",
@@ -66,7 +67,7 @@ export const channelApi = createApi({
const { data: messages } = await queryFulfilled;
if (messages?.length) {
messages.forEach((msg) => {
handleChatMessage(msg, dispatch, getState());
handleChatMessage(msg, dispatch, getState() as RootState);
});
}
}
@@ -80,15 +81,15 @@ export const channelApi = createApi({
url: gid
? `/group/create_reg_magic_link?expired_in=3600&max_times=1&gid=${gid}`
: `/group/create_reg_magic_link?expired_in=3600&max_times=1`,
responseHandler: (response) => response.text()
responseHandler: (response: Response) => response.text()
}),
transformResponse: (link) => {
transformResponse: (link: string) => {
// 替换掉域名
const invite = new URL(link);
return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`;
}
}),
removeChannel: builder.query({
removeChannel: builder.query<void, number>({
query: (id) => ({
url: `group/${id}`,
method: "DELETE"
@@ -99,7 +100,7 @@ export const channelApi = createApi({
ui: {
remeberedNavs: { chat: remeberedPath }
}
} = getState();
} = getState() as RootState;
try {
await queryFulfilled;
// 删掉该channel下的所有消息&reaction
@@ -161,7 +162,7 @@ export const channelApi = createApi({
await queryFulfilled;
dispatch(
updateChannel({
id: gid,
gid,
icon: `${BASE_URL}/resource/group_avatar?gid=${gid}&t=${+new Date()}`
})
);
+24 -18
View File
@@ -11,7 +11,16 @@ import { onMessageSendStarted } from "./handlers";
import { normalizeArchiveData } from "../../common/utils";
// import { updateMessage } from "../slices/message";
import baseQuery from "./base.query";
import { OG } from "../../types/common";
type UploadFileResponse = {
path: string;
size: number;
hash: string;
image_properties: {
width: number;
height: number;
};
};
export const messageApi = createApi({
reducerPath: "messageApi",
baseQuery,
@@ -25,25 +34,22 @@ export const messageApi = createApi({
method: "PUT",
body: content
})
// async onQueryStarted({mid,content},{dispatch}){
// dispatch()
// }
}),
reactMessage: builder.mutation({
reactMessage: builder.mutation<number, { mid: number; action: string }>({
query: ({ mid, action }) => ({
url: `/message/${mid}/like`,
method: "PUT",
body: { action }
})
}),
deleteMessage: builder.query({
deleteMessage: builder.query<number, number>({
query: (mid) => ({
url: `/message/${mid}`,
method: "DELETE"
})
}),
prepareUploadFile: builder.mutation({
query: (meta = {}) => ({
prepareUploadFile: builder.mutation<string, { content_type: string; filename: string }>({
query: (meta = { content_type: "", filename: "" }) => ({
url: `/resource/file/prepare`,
method: "POST",
body: meta
@@ -56,21 +62,18 @@ export const messageApi = createApi({
body: { mid_list: mids }
})
}),
uploadFile: builder.mutation({
uploadFile: builder.mutation<UploadFileResponse | {}, FormData>({
query: (formData) => ({
// headers: {
// "content-type": ContentTypes.formData,
// },
url: `/resource/file/upload`,
method: "POST",
body: formData
}),
transformResponse: (data) => {
transformResponse: (data: UploadFileResponse | null) => {
console.log("upload file response", data);
return data ? data : {};
}
}),
getOGInfo: builder.query({
getOGInfo: builder.query<OG, string>({
query: (url) => ({
url: `/resource/open_graphic_parse?url=${encodeURIComponent(url)}`
})
@@ -80,14 +83,14 @@ export const messageApi = createApi({
url: `/resource/archive?file_path=${encodeURIComponent(file_path)}`
})
}),
pinMessage: builder.mutation({
pinMessage: builder.mutation<void, { gid: number; mid: number }>({
query: ({ gid, mid }) => ({
url: `/group/${gid}/pin`,
method: "POST",
body: { mid }
})
}),
unpinMessage: builder.mutation({
unpinMessage: builder.mutation<void, { gid: number; mid: number }>({
query: ({ gid, mid }) => ({
url: `/group/${gid}/unpin`,
method: "POST",
@@ -111,7 +114,7 @@ export const messageApi = createApi({
}
}
}),
removeFavorite: builder.query({
removeFavorite: builder.query<void, number>({
query: (id) => ({
url: `/favorite/${id}`,
method: "DELETE"
@@ -170,7 +173,10 @@ export const messageApi = createApi({
await onMessageSendStarted.call(this, param1, param2, param1.context);
}
}),
readMessage: builder.mutation({
readMessage: builder.mutation<
void,
{ users?: [{ uid: number; mid: number }]; groups?: [{ gid: number; mid: number }] }
>({
query: (data) => ({
url: `/user/read-index`,
method: "POST",
@@ -4,14 +4,14 @@ import { KEY_UID } from "../config";
import baseQuery from "./base.query";
import { resetAuthData } from "../slices/auth.data";
import { updateMute } from "../slices/footprint";
import { fullfillContacts } from "../slices/contacts";
import { fullfillContacts } from "../slices/users";
import BASE_URL, { ContentTypes } from "../config";
import { onMessageSendStarted } from "./handlers";
import handleChatMessage from "../../common/hook/useStreaming/chat.handler";
import { User } from "../../types/auth";
export const contactApi = createApi({
reducerPath: "contactApi",
export const userApi = createApi({
reducerPath: "userApi",
baseQuery,
endpoints: (builder) => ({
getContacts: builder.query({
@@ -30,21 +30,21 @@ export const contactApi = createApi({
async onQueryStarted(data, { dispatch, queryFulfilled }) {
const local_uid = localStorage.getItem(KEY_UID);
try {
const { data: contacts } = await queryFulfilled;
const matchedUser = contacts.find((c) => c.uid == local_uid);
console.log("wtf", contacts, matchedUser);
const { data: users } = await queryFulfilled;
const matchedUser = users.find((c) => c.uid == local_uid);
console.log("wtf", users, matchedUser);
if (!matchedUser) {
// 用户已注销或被禁用
console.log("no matched user, redirect to login");
dispatch(resetAuthData());
} else {
const markedContacts = contacts.map((u) => {
const markedContacts = users.map((u) => {
return u.uid == matchedUser.uid ? { ...u, online: true } : u;
});
dispatch(fullfillContacts(markedContacts));
}
} catch {
console.log("get contact list error");
console.log("get user list error");
}
}
}),
@@ -135,4 +135,4 @@ export const {
useGetContactsQuery,
useLazyGetContactsQuery,
useSendMsgMutation
} = contactApi;
} = userApi;
+2 -2
View File
@@ -18,7 +18,7 @@ export interface State {
draftMixedText: { [key: string]: any };
remeberedNavs: {
chat: null | string;
contact: null | string;
user: null | string;
};
}
@@ -39,7 +39,7 @@ const initialState: State = {
// todo: typo
remeberedNavs: {
chat: null,
contact: null
user: null
}
};
@@ -19,18 +19,18 @@ const initialState: State = {
byId: {}
};
const contactsSlice = createSlice({
name: "contacts",
const usersSlice = createSlice({
name: "users",
initialState,
reducers: {
resetContacts() {
return initialState;
},
fullfillContacts(state, action: PayloadAction<StoredUser[]>) {
const contacts = action.payload || [];
state.ids = contacts.map(({ uid }) => uid);
const users = action.payload || [];
state.ids = users.map(({ uid }) => uid);
state.byId = Object.fromEntries(
contacts.map((c) => {
users.map((c) => {
const { uid } = c;
return [uid, c];
})
@@ -100,5 +100,5 @@ const contactsSlice = createSlice({
});
export const { resetContacts, fullfillContacts, updateUsersByLogs, updateUsersStatus } =
contactsSlice.actions;
export default contactsSlice.reducer;
usersSlice.actions;
export default usersSlice.reducer;
+24 -24
View File
@@ -1,24 +1,24 @@
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { setupListeners } from '@reduxjs/toolkit/query';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import listenerMiddleware from './listener.middleware';
import authDataReducer from './slices/auth.data';
import footprintReducer from './slices/footprint';
import serverReducer from './slices/server';
import uiReducer from './slices/ui';
import channelsReducer from './slices/channels';
import contactsReducer from './slices/contacts';
import reactionMsgReducer from './slices/message.reaction';
import channelMsgReducer from './slices/message.channel';
import userMsgReducer from './slices/message.user';
import favoritesReducer from './slices/favorites';
import fileMsgReducer from './slices/message.file';
import messageReducer from './slices/message';
import { authApi } from './services/auth';
import { contactApi } from './services/contact';
import { channelApi } from './services/channel';
import { messageApi } from './services/message';
import { serverApi } from './services/server';
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import listenerMiddleware from "./listener.middleware";
import authDataReducer from "./slices/auth.data";
import footprintReducer from "./slices/footprint";
import serverReducer from "./slices/server";
import uiReducer from "./slices/ui";
import channelsReducer from "./slices/channels";
import usersReducer from "./slices/users";
import reactionMsgReducer from "./slices/message.reaction";
import channelMsgReducer from "./slices/message.channel";
import userMsgReducer from "./slices/message.user";
import favoritesReducer from "./slices/favorites";
import fileMsgReducer from "./slices/message.file";
import messageReducer from "./slices/message";
import { authApi } from "./services/auth";
import { userApi } from "./services/user";
import { channelApi } from "./services/channel";
import { messageApi } from "./services/message";
import { serverApi } from "./services/server";
const reducer = combineReducers({
authData: authDataReducer,
@@ -26,7 +26,7 @@ const reducer = combineReducers({
footprint: footprintReducer,
server: serverReducer,
favorites: favoritesReducer,
contacts: contactsReducer,
users: usersReducer,
channels: channelsReducer,
reactionMessage: reactionMsgReducer,
userMessage: userMsgReducer,
@@ -35,7 +35,7 @@ const reducer = combineReducers({
message: messageReducer,
[authApi.reducerPath]: authApi.reducer,
[messageApi.reducerPath]: messageApi.reducer,
[contactApi.reducerPath]: contactApi.reducer,
[userApi.reducerPath]: userApi.reducer,
[channelApi.reducerPath]: channelApi.reducer,
[serverApi.reducerPath]: serverApi.reducer
});
@@ -46,7 +46,7 @@ const store = configureStore({
getDefaultMiddleware()
.concat(
authApi.middleware,
contactApi.middleware,
userApi.middleware,
channelApi.middleware,
serverApi.middleware,
messageApi.middleware