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) return next(c)
} }

View File

@ -229,13 +229,35 @@ func (s *Server) registerMemoRoutes(g *echo.Group) {
return nil 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 { g.GET("/memo/stats", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
normalStatus := api.Normal normalStatus := api.Normal
memoFind := &api.MemoFind{ memoFind := &api.MemoFind{
RowStatus: &normalStatus, 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 memoFind.CreatorID = &userID
} }
@ -525,28 +547,4 @@ func (s *Server) registerMemoRoutes(g *echo.Group) {
return c.JSON(http.StatusOK, true) 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 { useCallback, useEffect, useRef, useState } from "react";
import { useAppSelector } from "../store"; import { useAppSelector } from "../store";
import { locationService } from "../services"; import { locationService, userService } from "../services";
import { getMemoStats } from "../helpers/api"; import { getMemoStats } from "../helpers/api";
import { DAILY_TIMESTAMP } from "../helpers/consts"; import { DAILY_TIMESTAMP } from "../helpers/consts";
import * as utils from "../helpers/utils"; import * as utils from "../helpers/utils";
@ -28,19 +28,18 @@ interface DailyUsageStat {
} }
const UsageHeatMap = () => { 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 todayTimeStamp = utils.getDateStampByDate(Date.now());
const todayDay = new Date(todayTimeStamp).getDay() + 1; const todayDay = new Date(todayTimeStamp).getDay() + 1;
const nullCell = new Array(7 - todayDay).fill(0); const nullCell = new Array(7 - todayDay).fill(0);
const usedDaysAmount = (tableConfig.width - 1) * tableConfig.height + todayDay; const usedDaysAmount = (tableConfig.width - 1) * tableConfig.height + todayDay;
const beginDayTimestemp = todayTimeStamp - usedDaysAmount * DAILY_TIMESTAMP; 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(() => { useEffect(() => {
getMemoStats() getMemoStats(userService.getCurrentUserId())
.then(({ data: { data } }) => { .then(({ data: { data } }) => {
const newStat: DailyUsageStat[] = getInitialUsageStat(usedDaysAmount, beginDayTimestemp); const newStat: DailyUsageStat[] = getInitialUsageStat(usedDaysAmount, beginDayTimestemp);
for (const record of data) { for (const record of data) {

View File

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

View File

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

View File

@ -1,5 +1,6 @@
import { locationService } from "."; import { locationService } from ".";
import * as api from "../helpers/api"; import * as api from "../helpers/api";
import { UNKNOWN_ID } from "../helpers/consts";
import store from "../store"; import store from "../store";
import { setUser, patchUser, setHost, setOwner } from "../store/modules/user"; 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: () => { isVisitorMode: () => {
return !(userService.getUserIdFromPath() === undefined); return !(userService.getUserIdFromPath() === undefined);
}, },