feat: lots of updates

This commit is contained in:
zerosoul
2022-01-27 22:06:44 +08:00
commit e18c7323a6
72 changed files with 12432 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
const BASE_URL = `http://rustchat.com:3000/api`;
export const tokenHeader = "X-API-Key";
export default BASE_URL;
+25
View File
@@ -0,0 +1,25 @@
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import BASE_URL from "../config";
export const authApi = createApi({
reducerPath: "auth",
baseQuery: fetchBaseQuery({ baseUrl: BASE_URL }),
endpoints: (builder) => ({
login: builder.mutation({
query: (credentials) => ({
url: "token/login",
method: "POST",
body: credentials,
}),
// transformResponse: (resp) => {
// console.log("resp", resp);
// if (resp.status == 401) {
// resp.msg = "username or password incorrect";
// }
// return resp;
// },
}),
}),
});
export const { useLoginMutation } = authApi;
+40
View File
@@ -0,0 +1,40 @@
import { fetchBaseQuery } from "@reduxjs/toolkit/query";
import BASE_URL, { tokenHeader } from "../config";
// const whiteList = [
// "/resource/avatar",
// "/resource/company/logo",
// "/resource/thumbnail",
// "/resource/image",
// "/token/login",
// "/token/renew",
// "/user",
// "/admin/system/company",
// ];
const baseQuery = fetchBaseQuery({
baseUrl: BASE_URL,
prepareHeaders: (headers, { getState }) => {
const { token } = getState().authData;
if (token) {
headers.set(tokenHeader, token);
}
return headers;
},
});
const baseQueryWithReauth = async (args, api, extraOptions) => {
let result = await baseQuery(args, api, extraOptions);
if (result.error && result.error.status === 401) {
// try to get a new token with refreshToken
// const refreshResult = await baseQuery('/refreshToken', api, extraOptions);
// if (refreshResult.data) {
// // store the new token
// api.dispatch(tokenReceived(refreshResult.data));
// // retry the initial query
// result = await baseQuery(args, api, extraOptions);
// } else {
// api.dispatch(loggedOut());
// }
}
return result;
};
export default baseQueryWithReauth;
+38
View File
@@ -0,0 +1,38 @@
import { createApi } from "@reduxjs/toolkit/query/react";
import baseQuery from "./base.query";
import { REHYDRATE } from "redux-persist";
export const channelApi = createApi({
reducerPath: "groups",
baseQuery,
extractRehydrationInfo(action, { reducerPath }) {
if (action.type === REHYDRATE) {
return action.payload ? action.payload[reducerPath] : undefined;
}
},
refetchOnFocus: true,
endpoints: (builder) => ({
getChannels: builder.query({
query: () => ({ url: `group` }),
}),
createChannel: builder.mutation({
query: (data) => ({
url: "group",
method: "POST",
body: data,
}),
}),
sendChannelMsg: builder.mutation({
query: ({ gid, message }) => ({
url: `group/${gid}/send`,
method: "POST",
body: message,
}),
}),
}),
});
export const {
useGetChannelsQuery,
useCreateChannelMutation,
useSendChannelMsgMutation,
} = channelApi;
+34
View File
@@ -0,0 +1,34 @@
import { createApi } from "@reduxjs/toolkit/query/react";
import baseQuery from "./base.query";
import BASE_URL from "../config";
import { REHYDRATE } from "redux-persist";
export const contactApi = createApi({
reducerPath: "contacts",
baseQuery,
extractRehydrationInfo(action, { reducerPath }) {
if (action.type === REHYDRATE) {
return action.payload ? action.payload[reducerPath] : undefined;
}
},
endpoints: (builder) => ({
getContacts: builder.query({
query: () => ({ url: `user` }),
transformResponse: (data) => {
return data.map((user) => {
const avatar = `${BASE_URL}/resource/avatar?uid=${user.uid}`;
user.avatar = avatar;
return user;
});
},
}),
sendMsg: builder.mutation({
query: ({ uid, message }) => ({
url: `user/${uid}/send`,
method: "POST",
body: message,
}),
}),
}),
});
export const { useGetContactsQuery, useSendMsgMutation } = contactApi;
+26
View File
@@ -0,0 +1,26 @@
import { createApi } from "@reduxjs/toolkit/query/react";
import BASE_URL from "../config";
// import { REHYDRATE } from 'redux-persist';
import baseQuery from "./base.query";
export const serverApi = createApi({
reducerPath: "server",
baseQuery,
// extractRehydrationInfo(action, { reducerPath }) {
// if (action.type === REHYDRATE) {
// return action.payload ? action.payload[reducerPath] : undefined;
// }
// },
endpoints: (builder) => ({
getServer: builder.query({
query: () => ({ url: `admin/system/company` }),
transformResponse: (data) => {
data.logo = `${BASE_URL}/resource/company/logo`;
return data;
},
}),
}),
});
export const { useGetServerQuery } = serverApi;
+21
View File
@@ -0,0 +1,21 @@
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
user: null,
token: null,
refreshToken: null,
};
const authDataSlice = createSlice({
name: "authData",
initialState,
reducers: {
setAuthData(state, action) {
const { user, token, refresh_token } = action.payload;
state.user = user;
state.token = token;
state.refreshToken = refresh_token;
},
},
});
export const { setAuthData } = authDataSlice.actions;
export default authDataSlice.reducer;
+40
View File
@@ -0,0 +1,40 @@
import { createSlice } from "@reduxjs/toolkit";
import { isObjectEqual } from "../../common/utils";
const initialState = {};
const channelMsgSlice = createSlice({
name: "channelMessage",
initialState,
reducers: {
addChannelMsg(state, action) {
const { id, content, created_at, mid, from_uid } = action.payload;
const newMsg = { content, created_at, from_uid };
if (state[id]) {
let replaceMsg = state[id][mid];
// 如果存在,并且新消息和缓存消息不一样,则替换掉
if (replaceMsg) {
const copyMsg = { ...replaceMsg };
if (!isObjectEqual(copyMsg, newMsg)) {
state[id][mid] = newMsg;
}
} else {
state[id][mid] = newMsg;
}
// let replaceIdx = state[id].findIndex((m) => m.mid == mid);
// if (replaceIdx > -1) {
// const copyMsg = { ...state[id][replaceIdx] };
// console.log("current channel msg", copyMsg, newMsg);
// if (!isObjectEqual(copyMsg, newMsg)) {
// state[id][replaceIdx] = newMsg;
// }
// } else {
// state[id] = [...state[id], newMsg];
// }
} else {
state[id] = { [mid]: newMsg };
}
},
},
});
export const { addChannelMsg } = channelMsgSlice.actions;
export default channelMsgSlice.reducer;
+40
View File
@@ -0,0 +1,40 @@
import { createSlice } from "@reduxjs/toolkit";
import { isObjectEqual } from "../../common/utils";
const initialState = {};
const userMsgSlice = createSlice({
name: "userMessage",
initialState,
reducers: {
addUserMsg(state, action) {
const { id, content, created_at, mid, from_uid } = action.payload;
const newMsg = { content, created_at, from_uid };
if (state[id]) {
let replaceMsg = state[id][mid];
// 如果存在,并且新消息和缓存消息不一样,则替换掉
if (replaceMsg) {
const copyMsg = { ...replaceMsg };
if (!isObjectEqual(copyMsg, newMsg)) {
state[id][mid] = newMsg;
}
} else {
state[id][mid] = newMsg;
}
// let replaceIdx = state[id].findIndex((m) => m.mid == mid);
// if (replaceIdx > -1) {
// const copyMsg = { ...state[id][replaceIdx] };
// console.log("current user msg", copyMsg, newMsg);
// if (!isObjectEqual(copyMsg, newMsg)) {
// state[id][replaceIdx] = newMsg;
// }
// } else {
// state[id] = [...state[id], newMsg];
// }
} else {
state[id] = { [mid]: newMsg };
}
},
},
});
export const { addUserMsg } = userMsgSlice.actions;
export default userMsgSlice.reducer;
+52
View File
@@ -0,0 +1,52 @@
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import storage from "redux-persist/lib/storage";
import {
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import authDataReducer from "./slices/auth.data";
import channelMsgReducer from "./slices/message.channel";
import userMsgReducer from "./slices/message.user";
import { authApi } from "./services/auth";
import { contactApi } from "./services/contact";
import { channelApi } from "./services/channel";
import { serverApi } from "./services/server";
const persistConfig = {
key: "root",
version: 1,
storage,
};
const persistedReducer = persistReducer(
persistConfig,
combineReducers({
userMsg: userMsgReducer,
channelMsg: channelMsgReducer,
authData: authDataReducer,
[authApi.reducerPath]: authApi.reducer,
[contactApi.reducerPath]: contactApi.reducer,
[channelApi.reducerPath]: channelApi.reducer,
[serverApi.reducerPath]: serverApi.reducer,
})
);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}).concat(
authApi.middleware,
contactApi.middleware,
channelApi.middleware,
serverApi.middleware
),
});
setupListeners(store.dispatch);
export default store;