diff --git a/src/client/.env.example b/src/client/.env.example new file mode 100644 index 0000000..c1464a2 --- /dev/null +++ b/src/client/.env.example @@ -0,0 +1,25 @@ +# Since the ".env" file is gitignored, you can use the ".env.example" file to +# build a new ".env" file when you clone the repo. Keep this file up-to-date +# when you add new variables to `.env`. + +# This file will be committed to version control, so make sure not to have any +# secrets in it. If you are cloning this repo, create a copy of this file named +# ".env" and populate it with your secrets. + +# When adding additional environment variables, the schema in "/src/env.mjs" +# should be updated accordingly. + +# Prisma +# https://www.prisma.io/docs/reference/database-reference/connection-urls#env +DATABASE_URL="file:./db.sqlite" + +# Next Auth +# You can generate a new secret on the command line with: +# openssl rand -base64 32 +# https://next-auth.js.org/configuration/options#secret +# NEXTAUTH_SECRET="" +NEXTAUTH_URL="http://localhost:3000" + +# Next Auth Discord Provider +DISCORD_CLIENT_ID="" +DISCORD_CLIENT_SECRET="" diff --git a/src/client/.eslintrc.cjs b/src/client/.eslintrc.cjs new file mode 100644 index 0000000..8b7a0e8 --- /dev/null +++ b/src/client/.eslintrc.cjs @@ -0,0 +1,35 @@ +// eslint-disable-next-line @typescript-eslint/no-var-requires +const path = require("path"); + +/** @type {import("eslint").Linter.Config} */ +const config = { + overrides: [ + { + extends: [ + "plugin:@typescript-eslint/recommended-requiring-type-checking", + ], + files: ["*.ts", "*.tsx"], + parserOptions: { + project: path.join(__dirname, "tsconfig.json"), + }, + }, + ], + parser: "@typescript-eslint/parser", + parserOptions: { + project: path.join(__dirname, "tsconfig.json"), + }, + plugins: ["@typescript-eslint"], + extends: ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"], + rules: { + "@typescript-eslint/consistent-type-imports": [ + "warn", + { + prefer: "type-imports", + fixStyle: "inline-type-imports", + }, + ], + "@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }], + }, +}; + +module.exports = config; diff --git a/src/client/.eslintrc.json b/src/client/.eslintrc.json deleted file mode 100644 index bffb357..0000000 --- a/src/client/.eslintrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "next/core-web-vitals" -} diff --git a/src/client/.gitignore b/src/client/.gitignore index c87c9b3..2971a0b 100644 --- a/src/client/.gitignore +++ b/src/client/.gitignore @@ -8,9 +8,14 @@ # testing /coverage +# database +/prisma/db.sqlite +/prisma/db.sqlite-journal + # next.js /.next/ /out/ +next-env.d.ts # production /build @@ -26,6 +31,8 @@ yarn-error.log* .pnpm-debug.log* # local env files +# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables +.env .env*.local # vercel @@ -33,4 +40,3 @@ yarn-error.log* # typescript *.tsbuildinfo -next-env.d.ts diff --git a/src/client/README.md b/src/client/README.md index 5bc7ca2..fba19ed 100644 --- a/src/client/README.md +++ b/src/client/README.md @@ -1,38 +1,28 @@ -This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). +# Create T3 App -## Getting Started +This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. -First, run the development server: +## What's next? How do I make an app with this? -```bash -npm run dev -# or -yarn dev -# or -pnpm dev -``` +We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary. -Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. +If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help. -You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. - -[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`. - -The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. - -This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. +- [Next.js](https://nextjs.org) +- [NextAuth.js](https://next-auth.js.org) +- [Prisma](https://prisma.io) +- [Tailwind CSS](https://tailwindcss.com) +- [tRPC](https://trpc.io) ## Learn More -To learn more about Next.js, take a look at the following resources: +To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: -- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. -- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. +- [Documentation](https://create.t3.gg/) +- [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials -You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! +You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! -## Deploy on Vercel +## How do I deploy this? -The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. - -Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. +Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel), [Netlify](https://create.t3.gg/en/deployment/netlify) and [Docker](https://create.t3.gg/en/deployment/docker) for more information. diff --git a/src/client/next.config.js b/src/client/next.config.js deleted file mode 100644 index dafb0c8..0000000 --- a/src/client/next.config.js +++ /dev/null @@ -1,8 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = { - experimental: { - appDir: true, - }, -} - -module.exports = nextConfig diff --git a/src/client/next.config.mjs b/src/client/next.config.mjs new file mode 100644 index 0000000..f9b4e26 --- /dev/null +++ b/src/client/next.config.mjs @@ -0,0 +1,22 @@ +/** + * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. + * This is especially useful for Docker builds. + */ +!process.env.SKIP_ENV_VALIDATION && (await import("./src/env.mjs")); + +/** @type {import("next").NextConfig} */ +const config = { + reactStrictMode: true, + + /** + * If you have the "experimental: { appDir: true }" setting enabled, then you + * must comment the below `i18n` config out. + * + * @see https://github.com/vercel/next.js/issues/41980 + */ + i18n: { + locales: ["en"], + defaultLocale: "en", + }, +}; +export default config; diff --git a/src/client/package.json b/src/client/package.json index 15448c4..2a71bd9 100644 --- a/src/client/package.json +++ b/src/client/package.json @@ -3,20 +3,46 @@ "version": "0.1.0", "private": true, "scripts": { - "dev": "next dev", "build": "next build", - "start": "next start", - "lint": "next lint" + "dev": "next dev", + "postinstall": "prisma generate", + "lint": "next lint", + "start": "next start" }, "dependencies": { - "@types/node": "18.15.3", - "@types/react": "18.0.28", - "@types/react-dom": "18.0.11", - "eslint": "8.36.0", - "eslint-config-next": "13.2.4", - "next": "13.2.4", + "@next-auth/prisma-adapter": "^1.0.5", + "@prisma/client": "^4.9.0", + "@tanstack/react-query": "^4.20.2", + "@trpc/client": "^10.9.0", + "@trpc/next": "^10.9.0", + "@trpc/react-query": "^10.9.0", + "@trpc/server": "^10.9.0", + "next": "^13.2.1", + "next-auth": "^4.19.0", "react": "18.2.0", "react-dom": "18.2.0", - "typescript": "5.0.2" + "superjson": "1.9.1", + "zod": "^3.20.6" + }, + "devDependencies": { + "@types/eslint": "^8.21.1", + "@types/node": "^18.14.0", + "@types/prettier": "^2.7.2", + "@types/react": "^18.0.28", + "@types/react-dom": "^18.0.11", + "@typescript-eslint/eslint-plugin": "^5.53.0", + "@typescript-eslint/parser": "^5.53.0", + "autoprefixer": "^10.4.7", + "eslint": "^8.34.0", + "eslint-config-next": "^13.2.1", + "postcss": "^8.4.14", + "prettier": "^2.8.1", + "prettier-plugin-tailwindcss": "^0.2.1", + "prisma": "^4.9.0", + "tailwindcss": "^3.2.0", + "typescript": "^4.9.5" + }, + "ct3aMetadata": { + "initVersion": "7.8.0" } } diff --git a/src/client/postcss.config.cjs b/src/client/postcss.config.cjs new file mode 100644 index 0000000..e305dd9 --- /dev/null +++ b/src/client/postcss.config.cjs @@ -0,0 +1,8 @@ +const config = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; + +module.exports = config; diff --git a/src/client/prettier.config.cjs b/src/client/prettier.config.cjs new file mode 100644 index 0000000..ca28ed9 --- /dev/null +++ b/src/client/prettier.config.cjs @@ -0,0 +1,6 @@ +/** @type {import("prettier").Config} */ +const config = { + plugins: [require.resolve("prettier-plugin-tailwindcss")], +}; + +module.exports = config; diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma new file mode 100644 index 0000000..8259662 --- /dev/null +++ b/src/client/prisma/schema.prisma @@ -0,0 +1,81 @@ +// This is your Prisma schema file, +// learn more about it in the docs: https://pris.ly/d/prisma-schema + +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "sqlite" + // NOTE: When using postgresql, mysql or sqlserver, uncomment the @db.Text annotations in model Account below + // Further reading: + // https://next-auth.js.org/adapters/prisma#create-the-prisma-schema + // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string + url = env("DATABASE_URL") +} + +model Example { + id String @id @default(cuid()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +// Necessary for Next auth +model Account { + id String @id @default(cuid()) + userId String + type String + provider String + providerAccountId String + refresh_token String? // @db.Text + access_token String? // @db.Text + expires_at Int? + token_type String? + scope String? + id_token String? // @db.Text + session_state String? + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([provider, providerAccountId]) +} + +model Session { + id String @id @default(cuid()) + sessionToken String @unique + userId String + expires DateTime + user User @relation(fields: [userId], references: [id], onDelete: Cascade) +} + +model User { + id String @id @default(cuid()) + name String? + email String? @unique + emailVerified DateTime? + image String? + accounts Account[] + sessions Session[] +} + +model VerificationToken { + identifier String + token String @unique + expires DateTime + + @@unique([identifier, token]) +} + +model Books { + id String @id @default(cuid()) + title String + author String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +model Collections { + id String @id @default(cuid()) + title String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} diff --git a/src/client/public/favicon.ico b/src/client/public/favicon.ico new file mode 100644 index 0000000..60c702a Binary files /dev/null and b/src/client/public/favicon.ico differ diff --git a/src/client/public/next.svg b/src/client/public/next.svg deleted file mode 100644 index 5bb00d4..0000000 --- a/src/client/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/client/public/thirteen.svg b/src/client/public/thirteen.svg deleted file mode 100644 index db65b53..0000000 --- a/src/client/public/thirteen.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/client/public/vercel.svg b/src/client/public/vercel.svg deleted file mode 100644 index 1aeda7d..0000000 --- a/src/client/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/client/src/app/api/hello/route.ts b/src/client/src/app/api/hello/route.ts deleted file mode 100644 index d1cc6ee..0000000 --- a/src/client/src/app/api/hello/route.ts +++ /dev/null @@ -1,3 +0,0 @@ -export async function GET(request: Request) { - return new Response('Hello, Next.js!') -} diff --git a/src/client/src/app/favicon.ico b/src/client/src/app/favicon.ico deleted file mode 100644 index 718d6fe..0000000 Binary files a/src/client/src/app/favicon.ico and /dev/null differ diff --git a/src/client/src/app/layout.tsx b/src/client/src/app/layout.tsx deleted file mode 100644 index 3d9d723..0000000 --- a/src/client/src/app/layout.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import './globals.css' - -export const metadata = { - title: 'Create Next App', - description: 'Generated by create next app', -} - -export default function RootLayout({ - children, -}: { - children: React.ReactNode -}) { - return ( - - {children} - - ) -} diff --git a/src/client/src/app/page.tsx b/src/client/src/app/page.tsx deleted file mode 100644 index 32260d7..0000000 --- a/src/client/src/app/page.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import Image from 'next/image' -import { Inter } from 'next/font/google' -import { CssBaseline } from '@material-ui/core'; -import { ThemeProvider } from '@material-ui/core/styles'; -import { theme } from '../theme'; -import styles from './page.module.css' - -const inter = Inter({ subsets: ['latin'] }) - -export default function Home() { - return ( -
-
-

- Get started by editing  - src/app/page.tsx -

-
- - By{' '} - Vercel Logo - -
-
- -
- Next.js Logo -
- 13 -
-
- -
- -

- Docs -> -

-

- Find in-depth information about Next.js features and API. -

-
- - -

- Templates -> -

-

Explore the Next.js 13 playground.

-
- - -

- Deploy -> -

-

- Instantly deploy your Next.js site to a shareable URL with Vercel. -

-
-
-
- ) -} diff --git a/src/client/src/env.mjs b/src/client/src/env.mjs new file mode 100644 index 0000000..fcad3ec --- /dev/null +++ b/src/client/src/env.mjs @@ -0,0 +1,94 @@ +import { z } from "zod"; + +/** + * Specify your server-side environment variables schema here. This way you can ensure the app isn't + * built with invalid env vars. + */ +const server = z.object({ + DATABASE_URL: z.string().url(), + NODE_ENV: z.enum(["development", "test", "production"]), + NEXTAUTH_SECRET: + process.env.NODE_ENV === "production" + ? z.string().min(1) + : z.string().min(1).optional(), + NEXTAUTH_URL: z.preprocess( + // This makes Vercel deployments not fail if you don't set NEXTAUTH_URL + // Since NextAuth.js automatically uses the VERCEL_URL if present. + (str) => process.env.VERCEL_URL ?? str, + // VERCEL_URL doesn't include `https` so it cant be validated as a URL + process.env.VERCEL ? z.string().min(1) : z.string().url(), + ), + // Add `.min(1) on ID and SECRET if you want to make sure they're not empty + DISCORD_CLIENT_ID: z.string(), + DISCORD_CLIENT_SECRET: z.string(), +}); + +/** + * Specify your client-side environment variables schema here. This way you can ensure the app isn't + * built with invalid env vars. To expose them to the client, prefix them with `NEXT_PUBLIC_`. + */ +const client = z.object({ + // NEXT_PUBLIC_CLIENTVAR: z.string().min(1), +}); + +/** + * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. + * middlewares) or client-side so we need to destruct manually. + * + * @type {Record | keyof z.infer, string | undefined>} + */ +const processEnv = { + DATABASE_URL: process.env.DATABASE_URL, + NODE_ENV: process.env.NODE_ENV, + NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET, + NEXTAUTH_URL: process.env.NEXTAUTH_URL, + DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID, + DISCORD_CLIENT_SECRET: process.env.DISCORD_CLIENT_SECRET, + // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, +}; + +// Don't touch the part below +// -------------------------- + +const merged = server.merge(client); + +/** @typedef {z.input} MergedInput */ +/** @typedef {z.infer} MergedOutput */ +/** @typedef {z.SafeParseReturnType} MergedSafeParseReturn */ + +let env = /** @type {MergedOutput} */ (process.env); + +if (!!process.env.SKIP_ENV_VALIDATION == false) { + const isServer = typeof window === "undefined"; + + const parsed = /** @type {MergedSafeParseReturn} */ ( + isServer + ? merged.safeParse(processEnv) // on server we can validate all env vars + : client.safeParse(processEnv) // on client we can only validate the ones that are exposed + ); + + if (parsed.success === false) { + console.error( + "❌ Invalid environment variables:", + parsed.error.flatten().fieldErrors, + ); + throw new Error("Invalid environment variables"); + } + + env = new Proxy(parsed.data, { + get(target, prop) { + if (typeof prop !== "string") return undefined; + // Throw a descriptive error if a server-side env var is accessed on the client + // Otherwise it would just be returning `undefined` and be annoying to debug + if (!isServer && !prop.startsWith("NEXT_PUBLIC_")) + throw new Error( + process.env.NODE_ENV === "production" + ? "❌ Attempted to access a server-side environment variable on the client" + : `❌ Attempted to access server-side environment variable '${prop}' on the client`, + ); + return target[/** @type {keyof typeof target} */ (prop)]; + }, + }); +} + +export { env }; diff --git a/src/client/src/pages/_app.tsx b/src/client/src/pages/_app.tsx new file mode 100644 index 0000000..81e8bcc --- /dev/null +++ b/src/client/src/pages/_app.tsx @@ -0,0 +1,20 @@ +import { type AppType } from "next/app"; +import { type Session } from "next-auth"; +import { SessionProvider } from "next-auth/react"; + +import { api } from "~/utils/api"; + +import "~/styles/globals.css"; + +const MyApp: AppType<{ session: Session | null }> = ({ + Component, + pageProps: { session, ...pageProps }, +}) => { + return ( + + + + ); +}; + +export default api.withTRPC(MyApp); diff --git a/src/client/src/pages/api/auth/[...nextauth].ts b/src/client/src/pages/api/auth/[...nextauth].ts new file mode 100644 index 0000000..8aefbb6 --- /dev/null +++ b/src/client/src/pages/api/auth/[...nextauth].ts @@ -0,0 +1,4 @@ +import NextAuth from "next-auth"; +import { authOptions } from "~/server/auth"; + +export default NextAuth(authOptions); diff --git a/src/client/src/pages/api/trpc/[trpc].ts b/src/client/src/pages/api/trpc/[trpc].ts new file mode 100644 index 0000000..3c744a0 --- /dev/null +++ b/src/client/src/pages/api/trpc/[trpc].ts @@ -0,0 +1,19 @@ +import { createNextApiHandler } from "@trpc/server/adapters/next"; + +import { env } from "~/env.mjs"; +import { createTRPCContext } from "~/server/api/trpc"; +import { appRouter } from "~/server/api/root"; + +// export API handler +export default createNextApiHandler({ + router: appRouter, + createContext: createTRPCContext, + onError: + env.NODE_ENV === "development" + ? ({ path, error }) => { + console.error( + `❌ tRPC failed on ${path ?? ""}: ${error.message}`, + ); + } + : undefined, +}); diff --git a/src/client/src/pages/index.tsx b/src/client/src/pages/index.tsx new file mode 100644 index 0000000..97ec863 --- /dev/null +++ b/src/client/src/pages/index.tsx @@ -0,0 +1,83 @@ +import { type NextPage } from "next"; +import Head from "next/head"; +import Link from "next/link"; +import { signIn, signOut, useSession } from "next-auth/react"; + +import { api } from "~/utils/api"; + +const Home: NextPage = () => { + const hello = api.example.hello.useQuery({ text: "from tRPC" }); + + return ( + <> + + Create T3 App + + + +
+
+

+ Create T3 App +

+
+ +

First Steps →

+
+ Just the basics - Everything you need to know to set up your + database and authentication. +
+ + +

Documentation →

+
+ Learn more about Create T3 App, the libraries it uses, and how + to deploy it. +
+ +
+
+

+ {hello.data ? hello.data.greeting : "Loading tRPC query..."} +

+ +
+
+
+ + ); +}; + +export default Home; + +const AuthShowcase: React.FC = () => { + const { data: sessionData } = useSession(); + + const { data: secretMessage } = api.example.getSecretMessage.useQuery( + undefined, // no input + { enabled: sessionData?.user !== undefined }, + ); + + return ( +
+

+ {sessionData && Logged in as {sessionData.user?.name}} + {secretMessage && - {secretMessage}} +

+ +
+ ); +}; diff --git a/src/client/src/server/api/root.ts b/src/client/src/server/api/root.ts new file mode 100644 index 0000000..93fba92 --- /dev/null +++ b/src/client/src/server/api/root.ts @@ -0,0 +1,14 @@ +import { createTRPCRouter } from "~/server/api/trpc"; +import { exampleRouter } from "~/server/api/routers/example"; + +/** + * This is the primary router for your server. + * + * All routers added in /api/routers should be manually added here. + */ +export const appRouter = createTRPCRouter({ + example: exampleRouter, +}); + +// export type definition of API +export type AppRouter = typeof appRouter; diff --git a/src/client/src/server/api/routers/example.ts b/src/client/src/server/api/routers/example.ts new file mode 100644 index 0000000..73de162 --- /dev/null +++ b/src/client/src/server/api/routers/example.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; + +import { + createTRPCRouter, + publicProcedure, + protectedProcedure, +} from "~/server/api/trpc"; + +export const exampleRouter = createTRPCRouter({ + hello: publicProcedure + .input(z.object({ text: z.string() })) + .query(({ input }) => { + return { + greeting: `Hello ${input.text}`, + }; + }), + + getAll: publicProcedure.query(({ ctx }) => { + return ctx.prisma.example.findMany(); + }), + + getSecretMessage: protectedProcedure.query(() => { + return "you can now see this secret message!"; + }), +}); diff --git a/src/client/src/server/api/trpc.ts b/src/client/src/server/api/trpc.ts new file mode 100644 index 0000000..320ffd6 --- /dev/null +++ b/src/client/src/server/api/trpc.ts @@ -0,0 +1,130 @@ +/** + * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: + * 1. You want to modify request context (see Part 1). + * 2. You want to create a new middleware or type of procedure (see Part 3). + * + * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will + * need to use are documented accordingly near the end. + */ + +/** + * 1. CONTEXT + * + * This section defines the "contexts" that are available in the backend API. + * + * These allow you to access things when processing a request, like the database, the session, etc. + */ +import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; +import { type Session } from "next-auth"; + +import { getServerAuthSession } from "~/server/auth"; +import { prisma } from "~/server/db"; + +type CreateContextOptions = { + session: Session | null; +}; + +/** + * This helper generates the "internals" for a tRPC context. If you need to use it, you can export + * it from here. + * + * Examples of things you may need it for: + * - testing, so we don't have to mock Next.js' req/res + * - tRPC's `createSSGHelpers`, where we don't have req/res + * + * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts + */ +const createInnerTRPCContext = (opts: CreateContextOptions) => { + return { + session: opts.session, + prisma, + }; +}; + +/** + * This is the actual context you will use in your router. It will be used to process every request + * that goes through your tRPC endpoint. + * + * @see https://trpc.io/docs/context + */ +export const createTRPCContext = async (opts: CreateNextContextOptions) => { + const { req, res } = opts; + + // Get the session from the server using the getServerSession wrapper function + const session = await getServerAuthSession({ req, res }); + + return createInnerTRPCContext({ + session, + }); +}; + +/** + * 2. INITIALIZATION + * + * This is where the tRPC API is initialized, connecting the context and transformer. We also parse + * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation + * errors on the backend. + */ +import { initTRPC, TRPCError } from "@trpc/server"; +import superjson from "superjson"; +import { ZodError } from "zod"; + +const t = initTRPC.context().create({ + transformer: superjson, + errorFormatter({ shape, error }) { + return { + ...shape, + data: { + ...shape.data, + zodError: + error.cause instanceof ZodError ? error.cause.flatten() : null, + }, + }; + }, +}); + +/** + * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) + * + * These are the pieces you use to build your tRPC API. You should import these a lot in the + * "/src/server/api/routers" directory. + */ + +/** + * This is how you create new routers and sub-routers in your tRPC API. + * + * @see https://trpc.io/docs/router + */ +export const createTRPCRouter = t.router; + +/** + * Public (unauthenticated) procedure + * + * This is the base piece you use to build new queries and mutations on your tRPC API. It does not + * guarantee that a user querying is authorized, but you can still access user session data if they + * are logged in. + */ +export const publicProcedure = t.procedure; + +/** Reusable middleware that enforces users are logged in before running the procedure. */ +const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { + if (!ctx.session || !ctx.session.user) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + return next({ + ctx: { + // infers the `session` as non-nullable + session: { ...ctx.session, user: ctx.session.user }, + }, + }); +}); + +/** + * Protected (authenticated) procedure + * + * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies + * the session is valid and guarantees `ctx.session.user` is not null. + * + * @see https://trpc.io/docs/procedures + */ +export const protectedProcedure = t.procedure.use(enforceUserIsAuthed); diff --git a/src/client/src/server/auth.ts b/src/client/src/server/auth.ts new file mode 100644 index 0000000..7e6d826 --- /dev/null +++ b/src/client/src/server/auth.ts @@ -0,0 +1,76 @@ +import { type GetServerSidePropsContext } from "next"; +import { + getServerSession, + type NextAuthOptions, + type DefaultSession, +} from "next-auth"; +import DiscordProvider from "next-auth/providers/discord"; +import { PrismaAdapter } from "@next-auth/prisma-adapter"; +import { env } from "~/env.mjs"; +import { prisma } from "~/server/db"; + +/** + * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` + * object and keep type safety. + * + * @see https://next-auth.js.org/getting-started/typescript#module-augmentation + */ +declare module "next-auth" { + interface Session extends DefaultSession { + user: { + id: string; + // ...other properties + // role: UserRole; + } & DefaultSession["user"]; + } + + // interface User { + // // ...other properties + // // role: UserRole; + // } +} + +/** + * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. + * + * @see https://next-auth.js.org/configuration/options + */ +export const authOptions: NextAuthOptions = { + callbacks: { + session({ session, user }) { + if (session.user) { + session.user.id = user.id; + // session.user.role = user.role; <-- put other properties on the session here + } + return session; + }, + }, + adapter: PrismaAdapter(prisma), + providers: [ + DiscordProvider({ + clientId: env.DISCORD_CLIENT_ID, + clientSecret: env.DISCORD_CLIENT_SECRET, + }), + /** + * ...add more providers here. + * + * Most other providers require a bit more work than the Discord provider. For example, the + * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account + * model. Refer to the NextAuth.js docs for the provider you want to use. Example: + * + * @see https://next-auth.js.org/providers/github + */ + ], +}; + +/** + * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. + * + * @see https://next-auth.js.org/configuration/nextjs + */ +export const getServerAuthSession = (ctx: { + req: GetServerSidePropsContext["req"]; + res: GetServerSidePropsContext["res"]; +}) => { + return getServerSession(ctx.req, ctx.res, authOptions); +}; diff --git a/src/client/src/server/db.ts b/src/client/src/server/db.ts new file mode 100644 index 0000000..f3d7be3 --- /dev/null +++ b/src/client/src/server/db.ts @@ -0,0 +1,14 @@ +import { PrismaClient } from "@prisma/client"; + +import { env } from "~/env.mjs"; + +const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }; + +export const prisma = + globalForPrisma.prisma || + new PrismaClient({ + log: + env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"], + }); + +if (env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; diff --git a/src/client/src/types/index.tsx b/src/client/src/types/index.tsx deleted file mode 100644 index ab5cce3..0000000 --- a/src/client/src/types/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -// Path: types/index.tsx - -export interface IBook { - book_id: string - title: string - author: string - categories: string - cover: string - pages: string - progress: string - file_name: string - description: string - date: string - rights: string - tags: string - identifier: string - publisher: string -} diff --git a/src/client/src/utils/api.ts b/src/client/src/utils/api.ts new file mode 100644 index 0000000..f4f4ad5 --- /dev/null +++ b/src/client/src/utils/api.ts @@ -0,0 +1,68 @@ +/** + * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which + * contains the Next.js App-wrapper, as well as your type-safe React Query hooks. + * + * We also create a few inference helpers for input and output types. + */ +import { httpBatchLink, loggerLink } from "@trpc/client"; +import { createTRPCNext } from "@trpc/next"; +import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; +import superjson from "superjson"; + +import { type AppRouter } from "~/server/api/root"; + +const getBaseUrl = () => { + if (typeof window !== "undefined") return ""; // browser should use relative url + if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url + return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost +}; + +/** A set of type-safe react-query hooks for your tRPC API. */ +export const api = createTRPCNext({ + config() { + return { + /** + * Transformer used for data de-serialization from the server. + * + * @see https://trpc.io/docs/data-transformers + */ + transformer: superjson, + + /** + * Links used to determine request flow from client to server. + * + * @see https://trpc.io/docs/links + */ + links: [ + loggerLink({ + enabled: (opts) => + process.env.NODE_ENV === "development" || + (opts.direction === "down" && opts.result instanceof Error), + }), + httpBatchLink({ + url: `${getBaseUrl()}/api/trpc`, + }), + ], + }; + }, + /** + * Whether tRPC should await queries when server rendering pages. + * + * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false + */ + ssr: false, +}); + +/** + * Inference helper for inputs. + * + * @example type HelloInput = RouterInputs['example']['hello'] + */ +export type RouterInputs = inferRouterInputs; + +/** + * Inference helper for outputs. + * + * @example type HelloOutput = RouterOutputs['example']['hello'] + */ +export type RouterOutputs = inferRouterOutputs; diff --git a/src/client/tailwind.config.cjs b/src/client/tailwind.config.cjs new file mode 100644 index 0000000..a82e7e9 --- /dev/null +++ b/src/client/tailwind.config.cjs @@ -0,0 +1,10 @@ +/** @type {import('tailwindcss').Config} */ +const config = { + content: ["./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; + +module.exports = config; diff --git a/src/client/theme.tsx b/src/client/theme.tsx deleted file mode 100644 index 78f5127..0000000 --- a/src/client/theme.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { createTheme } from @material-ui/core/styles; - -const theme = createTheme({ - palette: { - primary: { - main: '#556cd6', - }, - secondary: { - main: '#19857b', - }, - error: { - main: '#f44336', - }, - background: { - default: '#fff', - }, - }, -}); - -export { theme }; diff --git a/src/client/tsconfig.json b/src/client/tsconfig.json index 0c7555f..03ebb74 100644 --- a/src/client/tsconfig.json +++ b/src/client/tsconfig.json @@ -1,8 +1,9 @@ { "compilerOptions": { - "target": "es5", + "target": "es2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, + "checkJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, @@ -14,15 +15,19 @@ "isolatedModules": true, "jsx": "preserve", "incremental": true, - "plugins": [ - { - "name": "next" - } - ], + "noUncheckedIndexedAccess": true, + "baseUrl": ".", "paths": { - "@/*": ["./src/*"] + "~/*": ["./src/*"] } }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "include": [ + ".eslintrc.cjs", + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + "**/*.cjs", + "**/*.mjs" + ], "exclude": ["node_modules"] }