Skip to content

Commit

Permalink
Merge pull request #8 from hanbings/main
Browse files Browse the repository at this point in the history
整体重构(WIP)
  • Loading branch information
helight authored Mar 21, 2024
2 parents d804807 + ae65ebf commit 478ba7f
Show file tree
Hide file tree
Showing 34 changed files with 571 additions and 542 deletions.
11 changes: 4 additions & 7 deletions src/common/message.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
export default class Message<T> {
constructor(
public status: number,
public message: string,
public data: T
) {
}
export default interface Message<T> {
status: number,
message: string,
data: T,
}
22 changes: 7 additions & 15 deletions src/common/token.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
export class Token {
constructor(
// TOKEN
public token: string,
// 所属账号
public belong: string,
// TOKEN 类型
public type: TokenType,
// 创建时间
public created: number,
// 失效时间
public expire: number
) {
}
export interface Token {
token: string,
belong: string,
type: TokenType,
created: number,
expire: number,
}

export enum TokenType {
OAUTH_TOKEN = "oauth_token",
ACCOUNT_API_KEY = "account_api_key",
EMAIL_VERIFY_CODE = "email_verify_code"
EMAIL_VERIFY_CODE = "email_verify_code",
}
4 changes: 2 additions & 2 deletions src/data/account.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Generated} from "kysely";
import crypto from "crypto";
import {Generated} from "kysely"
import crypto from "crypto"

export class AccountTable {
constructor(
Expand Down
2 changes: 1 addition & 1 deletion src/data/repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Generated} from "kysely";
import {Generated} from "kysely"

export class RepositoryTable {
constructor(
Expand Down
2 changes: 1 addition & 1 deletion src/data/statistic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Generated} from "kysely";
import {Generated} from "kysely"

export class StatisticTable {
constructor(
Expand Down
44 changes: 22 additions & 22 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,44 +1,44 @@
import '@/styles/globals.css'
import App from "next/app";
import {Token} from "@/common/token";
import {Account} from "@/common/account";
import {withRouter} from "next/router";
import App from "next/app"
import {Token} from "@/common/token"
import {Account} from "@/common/account"
import {withRouter} from "next/router"

export class State {
public static token: Token | null = null;
public static account: Account | null = null;
public static token: Token | null = null
public static account: Account | null = null

// 从 localStorage 中读取 token 和 account
public static load() {
if (typeof window !== "undefined") {
const token = localStorage.getItem("token");
const account = localStorage.getItem("account");
const token = localStorage.getItem("token")
const account = localStorage.getItem("account")
if (token !== null && account !== null) {
State.token = JSON.parse(token);
State.account = JSON.parse(account);
State.token = JSON.parse(token)
State.account = JSON.parse(account)
}
}
}

// 清理 localStorage 中的 token 和 account
public static clear() {
if (typeof window !== "undefined") {
localStorage.removeItem("token");
localStorage.removeItem("account");
localStorage.removeItem("token")
localStorage.removeItem("account")
}

State.token = null;
State.account = null;
State.token = null
State.account = null
}

// 写入 localStorage
public static save(token: Token, account: Account) {
State.token = token;
State.account = account;
State.token = token
State.account = account

if (typeof window !== "undefined") {
localStorage.setItem("token", JSON.stringify(State.token));
localStorage.setItem("account", JSON.stringify(State.account));
localStorage.setItem("token", JSON.stringify(State.token))
localStorage.setItem("account", JSON.stringify(State.account))
}
}

Expand All @@ -52,10 +52,10 @@ export class State {

class MyApp extends App {
render() {
const {Component, pageProps, router} = this.props;
const WithRouterComponent = withRouter(Component);
return <WithRouterComponent {...pageProps} router={router}/>;
const {Component, pageProps, router} = this.props
const WithRouterComponent = withRouter(Component)
return <WithRouterComponent {...pageProps} router={router}/>
}
}

export default MyApp;
export default MyApp
56 changes: 28 additions & 28 deletions src/pages/account.tsx
Original file line number Diff line number Diff line change
@@ -1,55 +1,55 @@
import {Inter} from 'next/font/google'
import Navbar from "@/pages/components/Navbar";
import Button from "@/pages/components/Button";
import {State} from "@/pages/_app";
import {Account} from "@/common/account";
import {Repository} from "@/common/repository";
import {useEffect, useState} from "react";
import Message from "@/common/message";
import {Token} from "@/common/token";
import {useRouter} from "next/router";
import Input from "@/pages/components/Input";
import Navbar from "@/pages/components/Navbar"
import Button from "@/pages/components/Button"
import {State} from "@/pages/_app"
import {Account} from "@/common/account"
import {Repository} from "@/common/repository"
import {useEffect, useState} from "react"
import Message from "@/common/message"
import {Token} from "@/common/token"
import {useRouter} from "next/router"
import Input from "@/pages/components/Input"

const inter = Inter({subsets: ['latin']})

interface Response {
id: string;
account: Account;
repositories: Repository[];
id: string
account: Account
repositories: Repository[]
}

export default function AccountPage() {
(function () {
State.load()
}());

const router = useRouter();
const token = State.token as Token;
const router = useRouter()
const token = State.token as Token

// 不要在任意 return 后使用 useState,因为这会导致每次渲染都会重置 state
const [result, setResult] = useState<Response>();
const [result, setResult] = useState<Response>()

useEffect(() => {
// 获取账号信息的逻辑
// 这里的 Token 在 isLogin 校验中判定为非空 那么这里一定不为空
fetch('/api/account', {headers: {'Authorization': token.token}})
.then(result => result.json() as Promise<Message<Response>>)
.then(data => setResult(data.data));
.then(data => setResult(data.data))

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [])

const copy = () => {
const input = document.createElement('input');
input.value = token.token;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
const input = document.createElement('input')
input.value = token.token
document.body.appendChild(input)
input.select()
document.execCommand('copy')
document.body.removeChild(input)
};

const [email, setEmail] = useState<string>('');
const [password, setPassword] = useState<string>('');
const [email, setEmail] = useState<string>('')
const [password, setPassword] = useState<string>('')

const login = () => {
fetch('/api/login',
Expand All @@ -65,11 +65,11 @@ export default function AccountPage() {
})
.then(result => result.json())
.then(() => router.push("/account")
.then(ignore => 0));
.then(ignore => 0))
}

const update = (org: string, project: string) => {
router.push(`/upload?update_organization=${org}&update_project=${project}`).then(ignore => 0);
router.push(`/upload?update_organization=${org}&update_project=${project}`).then(ignore => 0)
}

function renderLogin() {
Expand Down
64 changes: 36 additions & 28 deletions src/pages/api/account.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,46 @@
import type {NextApiRequest, NextApiResponse} from 'next'
import Message from "@/common/message";
import CacheService from "@/services/cache";
import {Token} from "@/common/token";
import DatabaseService from "@/services/database";
import {Repository} from "@/common/repository";
import {Account} from "@/common/account";
import CacheService from "@/services/cache"
import {Token} from "@/common/token"
import DatabaseService from "@/services/database"
import {Repository} from "@/common/repository"
import {Account} from "@/common/account"
import Message from "@/common/message"

export default async function handler(req: NextApiRequest, res: NextApiResponse<{}>) {
if (req.method === 'GET') {
// 查询 Token
const header = req.headers['authorization'];
export default async function handler(req: NextApiRequest, res: NextApiResponse<Message<any>>) {
if (req.method !== 'GET') {
res.status(400).json({status: 400, message: 'request method not match.', data: null})
return
}

if (header === undefined || header === null) {
res.status(400).json(new Message(400, 'token is invalid.', null));
return;
}
// 查询 Token
const header = req.headers['authorization'];

if (header === undefined || header === null) {
res.status(400).json({status: 400, message: 'token is invalid.', data: null})
return
}

const tokens = new CacheService<Token>();
const token = await tokens.get(header as string) as Token;
const tokens = new CacheService<Token>()
const token = await tokens.get(header as string) as Token

// 查询账号信息
const accounts = new DatabaseService<Account>();
const id = token.belong;
const account = await accounts.readAccountById(id);
// 查询账号信息
const accounts = new DatabaseService<Account>()
const id = token.belong
const account = await accounts.readAccountById(id)

// 查询仓库列表
const repositories = new DatabaseService<Repository>();
const repos = await repositories.readRepositoryByAccount(id);
// 查询仓库列表
const repositories = new DatabaseService<Repository>()
const repos = await repositories.readRepositoryByAccount(id)

res.status(200).json(new Message(200, 'success.',
{
res.status(200).json(
{
status: 200,
message: 'success.',
data: {
id: id,
account: account.length !== 0 ? account[0] : {},
repositories: repos
}));
} else res.status(400).json(new Message(400, 'request method not match.', null));
repositories: repos,
}
}
);
}
13 changes: 8 additions & 5 deletions src/pages/api/data.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import {NextApiRequest, NextApiResponse} from "next";
import {NextApiRequest, NextApiResponse} from "next"
import Message from "@/common/message";

export default async function handler(req: NextApiRequest, res: NextApiResponse<{}>) {
if (req.method === 'GET') {
res.status(200).json(new Message(200, 'OK', null));
} else res.status(400).json(new Message(400, 'request method not match.', null));
export default async function handler(req: NextApiRequest, res: NextApiResponse<Message<any>>) {
if (req.method !== 'GET') {
res.status(400).json({status: 400, message: 'request method not match.', data: null})
return
}

res.status(200).json({status: 200, message: 'OK', data: null})
}
Loading

0 comments on commit 478ba7f

Please sign in to comment.