chore: init

This commit is contained in:
Kuizuo
2024-04-26 02:12:44 +08:00
commit 5231e5f565
298 changed files with 44435 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
APP_BASE_URL=http://localhost:5001
+36
View File
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+2
View File
@@ -0,0 +1,2 @@
import { handlers } from '~/auth'
export const { GET, POST } = handlers
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+18
View File
@@ -0,0 +1,18 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
+30
View File
@@ -0,0 +1,30 @@
import type { Metadata } from "next"
import { Inter } from "next/font/google"
import "./globals.css"
import Header from "~/components/header"
import { TRPCReactProvider } from "~/trpc/react"
import { auth } from "~/auth"
const inter = Inter({ subsets: ["latin"] })
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
}
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body className={inter.className}>
<TRPCReactProvider session={await auth()}>
<Header />
{children}
</TRPCReactProvider>
</body>
</html>
)
}
+15
View File
@@ -0,0 +1,15 @@
"use client"
import { Suspense } from "react";
import { auth } from "~/auth";
import { TodoList } from "~/components/todo-list";
export default function Home() {
return <>
<Suspense fallback={null}>
<TodoList></TodoList>
</Suspense>
</>
}
+75
View File
@@ -0,0 +1,75 @@
import NextAuth from "next-auth"
import type { DefaultSession, NextAuthConfig } from "next-auth"
import Credentials from "next-auth/providers/credentials"
declare module "next-auth" {
/**
* Returned by `auth`, `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
authToken: string
} & DefaultSession["user"]
authToken: string
}
}
export const authOptions = {
// Configure one or more authentication providers
providers: [
Credentials({
name: 'Credentials',
credentials: {
username: { label: "Username", type: "text", placeholder: "user" },
password: { label: "Password", type: "password", placeholder: "Aa123456" }
},
async authorize(credentials, req) {
const res = await fetch(process.env.NEXT_PUBLIC_APP_BASE_URL + "/api/auth/login", {
method: 'POST',
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" }
})
const result = await res.json()
// If no error and we have user data, return it
if (result.ok && result) {
const res = await fetch(process.env.NEXT_PUBLIC_APP_BASE_URL + "/api/account/profile", {
method: 'GET',
headers: { "Authorization": "Bearer " + result.data.authToken }
})
const user = await res.json()
return {
name: user.data.username,
email: user.data.email,
image: user.data.avatar,
authToken: result.data.authToken
}
}
// Return null if user data could not be retrieved
return null
}
}),
// ...add more providers here
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.authToken = (user as any).authToken
}
return token
},
async session({ session, token }) {
session.authToken = token.authToken as string
return session
}
},
basePath: "/auth",
session: { strategy: "jwt" },
secret: 'IOfsM7Upq2m/JaRr96ZwPSoNsxE1aIQDNB5sJWcntZI='
} satisfies NextAuthConfig
export const { handlers, auth, signIn, signOut } = NextAuth(authOptions)
+33
View File
@@ -0,0 +1,33 @@
import { signIn, signOut } from "~/auth"
export function SignIn({
provider,
...props
}: { provider?: string }) {
return (
<form
action={async () => {
"use server"
await signIn(provider)
}}
>
<button {...props}>Sign In</button>
</form>
)
}
export function SignOut(props: any) {
return (
<form
action={async () => {
"use server"
await signOut()
}}
className="w-full"
>
<button variant="ghost" className="w-full p-0" {...props}>
Sign Out
</button>
</form>
)
}
+12
View File
@@ -0,0 +1,12 @@
import UserButton from './user-button'
export default function Header() {
return (
<header className="sticky flex justify-center border-b">
<div className="flex items-center justify-between w-full h-16 max-w-3xl px-4 mx-auto sm:px-6">
<div className="flex gap-4 items-center"></div>
<UserButton />
</div>
</header>
)
}
+111
View File
@@ -0,0 +1,111 @@
"use client"
import { AppRouter } from "@server/shared/trpc/trpc.instance"
import { inferProcedureInput } from "@trpc/server"
import { trpc } from "~/trpc/react"
export function TodoList() {
const utils = trpc.useUtils()
const [todos, { refetch }] = trpc.todo.list.useSuspenseQuery({})
const addTodo = trpc.todo.create.useMutation({
async onSuccess() {
// refetches posts after a post is added
await utils.todo.list.invalidate()
},
})
const deleteTodo = trpc.todo.delete.useMutation({
async onSuccess() {
await utils.todo.list.invalidate()
}
})
const updateTodo = trpc.todo.update.useMutation({
async onSuccess() {
await utils.todo.list.invalidate()
}
})
return (
<div className="max-w-80 mx-auto px-4 py-8">
<h1 className="text-2xl font-bold mb-4">Todo List</h1>
<div className="mb-4">
<form
className="py-2 w-4/6"
onSubmit={async (e) => {
/**
* In a real app you probably don't want to use this manually
* Checkout React Hook Form - it works great with tRPC
* @link https://react-hook-form.com/
* @link https://kitchen-sink.trpc.io/react-hook-form
*/
e.preventDefault()
const $form = e.currentTarget
const values = Object.fromEntries(new FormData($form))
type Input = inferProcedureInput<AppRouter['todo']['create']>
// ^?
const input: Input = {
value: values.value as string,
}
try {
await addTodo.mutateAsync(input)
$form.reset()
} catch (cause) {
console.error({ cause }, 'Failed to add todo')
}
}}
>
<div className="inline-flex flex-row gap-y-4 font-semibold">
<input
className="border outline-2 outline-gray-700 rounded-xl px-4 py-3"
id="title"
name="value"
type="text"
placeholder="Todo"
disabled={addTodo.isLoading}
/>
<input
className="cursor-pointer p-2 rounded-md px-4"
type="submit"
disabled={addTodo.isLoading}
/>
{addTodo.error && (
<p style={{ color: 'red' }}>{addTodo.error.message}</p>
)}
</div>
</form>
</div>
<ul className="grid grid-cols-1 gap-4">
{todos.items.map((item) => (
<li key={item.id} className={`shadow-md p-4 rounded-lg inline-flex justify-between items-center`}>
<label className="inline-flex items-center">
<input
type="checkbox"
checked={item.status}
onChange={async () => {
await updateTodo.mutateAsync({
id: item.id,
status: !item.status,
});
}}
className="form-checkbox h-5 w-5 text-blue-600"
/>
<span className="ml-2 text-lg">{item.value}</span>
</label>
<button
onClick={async () =>
deleteTodo.mutateAsync({ id: item.id })
}
className="inline-flex bg-red-500 text-white px-2 py-1 rounded-md">
Delete
</button>
</li>
))}
</ul>
</div>
)
}
+17
View File
@@ -0,0 +1,17 @@
import { auth } from "~/auth"
import { SignIn, SignOut } from "./auth-components"
export default async function UserButton() {
const session = await auth()
if (!session?.user) return <SignIn />
return (
<div className="flex gap-2 items-center">
<span className="hidden text-sm sm:inline-flex">
{session.user.email}
</span>
<SignOut />
</div>
)
}
+9
View File
@@ -0,0 +1,9 @@
import nextConfig from 'next/core-web-vitals'
/** @type {import('typescript-eslint').Config} */
export default [
{
ignores: [".next/**"],
},
...nextConfig,
];
+46
View File
@@ -0,0 +1,46 @@
import { auth } from "~/auth"
const publicRoutes: string[] = [
// '/',
]
const authRoutes = [
// '/auth/signup',
'/auth/signin'
]
export const apiAuthPrefix = "/auth";
export default auth((req) => {
const { nextUrl } = req
const isLoggedIn = !!req.auth;
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
if (isApiAuthRoute) {
return;
}
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(new URL('/', nextUrl));
}
return null;
}
if (!isLoggedIn && !isPublicRoute) {
return Response.redirect(new URL("/auth/signin", nextUrl));
}
return null
})
// Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
}
+13
View File
@@ -0,0 +1,13 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: '/api',
destination: 'http://localhost:5001/api',
},
]
},
};
export default nextConfig;
+34
View File
@@ -0,0 +1,34 @@
{
"name": "web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@t3-oss/env-nextjs": "^0.10.1",
"@tanstack/react-query": "^4.36.1",
"@trpc/client": "10.45.1",
"@trpc/next": "10.45.1",
"@trpc/react-query": "10.45.1",
"@trpc/server": "10.45.1",
"next": "14.2.2",
"next-auth": "5.0.0-beta.16",
"react": "^18",
"react-dom": "^18",
"zod": "3.22.4"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.2.2",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}
+8
View File
@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>

After

Width:  |  Height:  |  Size: 629 B

+20
View File
@@ -0,0 +1,20 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
};
export default config;
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { AppRouter } from "@server/shared/trpc/trpc.instance";
import { Session } from "next-auth";
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 30 * 1000,
},
},
});
let clientQueryClientSingleton: QueryClient | undefined = undefined;
const getQueryClient = () => {
if (typeof window === "undefined") {
// Server: always make a new query client
return createQueryClient();
} else {
// Browser: use singleton pattern to keep the same query client
return (clientQueryClientSingleton ??= createQueryClient());
}
};
export const trpc = createTRPCReact<AppRouter>();
export function TRPCReactProvider(props: {
children: React.ReactNode
session: Session | null
}) {
const queryClient = getQueryClient();
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: process.env.NEXT_PUBLIC_APP_BASE_URL + `/api/trpc`,
headers() {
const token = props.session?.authToken;
return {
Authorization: token ? `Bearer ${token}` : undefined,
}
},
}),
],
}),
);
return (
<QueryClientProvider client={queryClient}>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
{props.children}
</trpc.Provider>
</QueryClientProvider>
);
}
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"~/*": ["./*"],
"@server/*": ["../server/src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}