chore: update memo stats api (#387)

This commit is contained in:
boojack 2022-10-31 20:57:07 +08:00 committed by GitHub
parent 40d5686031
commit ef5492074e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 42 additions and 36 deletions

View File

@ -104,7 +104,7 @@ func aclMiddleware(s *Server, next echo.HandlerFunc) echo.HandlerFunc {
}
}
if common.HasPrefixes(path, "/api/memo/all", "/api/memo/:memoId") && c.Request().Method == http.MethodGet {
if common.HasPrefixes(path, "/api/memo/all", "/api/memo/:memoId", "/api/memo/amount", "/api/memo/stats") && c.Request().Method == http.MethodGet {
return next(c)
}

View File

@ -229,13 +229,35 @@ func (s *Server) registerMemoRoutes(g *echo.Group) {
return nil
})
g.GET("/memo/amount", func(c echo.Context) error {
ctx := c.Request().Context()
normalRowStatus := api.Normal
memoFind := &api.MemoFind{
RowStatus: &normalRowStatus,
}
if userID, err := strconv.Atoi(c.QueryParam("userId")); err == nil {
memoFind.CreatorID = &userID
}
memoList, err := s.Store.FindMemoList(ctx, memoFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo list").SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(len(memoList))); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to encode memo amount").SetInternal(err)
}
return nil
})
g.GET("/memo/stats", func(c echo.Context) error {
ctx := c.Request().Context()
normalStatus := api.Normal
memoFind := &api.MemoFind{
RowStatus: &normalStatus,
}
if userID, err := strconv.Atoi(c.QueryParam("creatorId")); err == nil {
if userID, err := strconv.Atoi(c.QueryParam("userId")); err == nil {
memoFind.CreatorID = &userID
}
@ -525,28 +547,4 @@ func (s *Server) registerMemoRoutes(g *echo.Group) {
return c.JSON(http.StatusOK, true)
})
g.GET("/memo/amount", func(c echo.Context) error {
ctx := c.Request().Context()
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
normalRowStatus := api.Normal
memoFind := &api.MemoFind{
CreatorID: &userID,
RowStatus: &normalRowStatus,
}
memoList, err := s.Store.FindMemoList(ctx, memoFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo list").SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(len(memoList))); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to encode memo amount").SetInternal(err)
}
return nil
})
}

View File

@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useAppSelector } from "../store";
import { locationService } from "../services";
import { locationService, userService } from "../services";
import { getMemoStats } from "../helpers/api";
import { DAILY_TIMESTAMP } from "../helpers/consts";
import * as utils from "../helpers/utils";
@ -28,19 +28,18 @@ interface DailyUsageStat {
}
const UsageHeatMap = () => {
const { memos } = useAppSelector((state) => state.memo);
const [allStat, setAllStat] = useState<DailyUsageStat[]>([]);
const [currentStat, setCurrentStat] = useState<DailyUsageStat | null>(null);
const containerElRef = useRef<HTMLDivElement>(null);
const todayTimeStamp = utils.getDateStampByDate(Date.now());
const todayDay = new Date(todayTimeStamp).getDay() + 1;
const nullCell = new Array(7 - todayDay).fill(0);
const usedDaysAmount = (tableConfig.width - 1) * tableConfig.height + todayDay;
const beginDayTimestemp = todayTimeStamp - usedDaysAmount * DAILY_TIMESTAMP;
const { memos } = useAppSelector((state) => state.memo);
const [allStat, setAllStat] = useState<DailyUsageStat[]>(getInitialUsageStat(usedDaysAmount, beginDayTimestemp));
const [currentStat, setCurrentStat] = useState<DailyUsageStat | null>(null);
const containerElRef = useRef<HTMLDivElement>(null);
useEffect(() => {
getMemoStats()
getMemoStats(userService.getCurrentUserId())
.then(({ data: { data } }) => {
const newStat: DailyUsageStat[] = getInitialUsageStat(usedDaysAmount, beginDayTimestemp);
for (const record of data) {

View File

@ -37,7 +37,7 @@ const UserBanner = () => {
}, [isVisitorMode, user, owner]);
useEffect(() => {
getMemoStats()
getMemoStats(userService.getCurrentUserId())
.then(({ data: { data } }) => {
setMemoAmount(data.length);
})

View File

@ -90,8 +90,8 @@ export function getMemoList(memoFind?: MemoFind) {
return axios.get<ResponseObject<Memo[]>>(`/api/memo?${queryList.join("&")}`);
}
export function getMemoStats() {
return axios.get<ResponseObject<number[]>>(`/api/memo/stats`);
export function getMemoStats(userId: UserId) {
return axios.get<ResponseObject<number[]>>(`/api/memo/stats?userId=${userId}`);
}
export function getMemoById(id: MemoId) {

View File

@ -1,5 +1,6 @@
import { locationService } from ".";
import * as api from "../helpers/api";
import { UNKNOWN_ID } from "../helpers/consts";
import store from "../store";
import { setUser, patchUser, setHost, setOwner } from "../store/modules/user";
@ -57,6 +58,14 @@ const userService = {
}
},
getCurrentUserId: () => {
if (userService.isVisitorMode()) {
return userService.getUserIdFromPath() || UNKNOWN_ID;
} else {
return userService.getState().user?.id || UNKNOWN_ID;
}
},
isVisitorMode: () => {
return !(userService.getUserIdFromPath() === undefined);
},