Skip to content

Commit

Permalink
chore(website): tweaks pageview (#212)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope authored Mar 4, 2023
1 parent c6ba12e commit 22efeb8
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 48 deletions.
46 changes: 0 additions & 46 deletions packages/website/api/addViewer.ts

This file was deleted.

53 changes: 53 additions & 0 deletions packages/website/api/pageview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const DEFAULT_PAGEVIEW_RESPONSE = { viewer: 0, visited: 0 };

export interface PageViewData {
viewer: number;
visited: number;
}

export const updatePageview = async (
pathname: string
): Promise<PageViewData> => {
const hasVisited = window.localStorage.getItem("visited");
const hasVisitedCurrentPath = window.localStorage.getItem(
`visited-${pathname}`
);

if (!hasVisited) {
window.localStorage.setItem("visited", "true");
}

if (!hasVisitedCurrentPath) {
window.localStorage.setItem(`visited-${pathname}`, "true");
}

try {
const { statusCode, data } = await fetch(
`/api/public/viewer?isNew=${!hasVisited}&isNewByPath=${!hasVisitedCurrentPath}`,
{ method: "POST" }
).then((res) => res.json());

return statusCode === 233 ? DEFAULT_PAGEVIEW_RESPONSE : data;
} catch (err) {
console.log(err);
throw err;
}
};

export const addViewerWithApiRoute = async () => {
let isNew = true;
if (window.localStorage.getItem("visited")) {
isNew = false;
} else {
window.localStorage.setItem("visited", "true");
}
try {
const url = `/api/viewer?isNew=${isNew}`;
const res = await fetch(url);
const data = await res.json();
return data;
} catch (err) {
console.log(err);
throw err;
}
};
4 changes: 2 additions & 2 deletions packages/website/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type { AppProps } from "next/app";
import { GlobalContext, GlobalState } from "../utils/globalContext";
import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";
import { addViewer } from "../api/addViewer";
import { updatePageview } from "../api/pageview";
import Head from "next/head";

function MyApp({ Component, pageProps }: AppProps) {
Expand All @@ -30,7 +30,7 @@ function MyApp({ Component, pageProps }: AppProps) {
}
const pathname = window.location.pathname;
console.log("[更新访客]", reason, pathname);
const { viewer, visited } = await addViewer(pathname);
const { viewer, visited } = await updatePageview(pathname);
setGlobalState({ ...globalState, viewer: viewer, visited: visited });
},
[globalState, setGlobalState]
Expand Down

0 comments on commit 22efeb8

Please sign in to comment.