new website beginning

This commit is contained in:
alex 3
2023-10-22 04:40:50 -04:00
parent 7dd999700e
commit b08637ea2a
35 changed files with 6010 additions and 93 deletions
+25
View File
@@ -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=""
+36
View File
@@ -0,0 +1,36 @@
/** @type {import("eslint").Linter.Config} */
const config = {
parser: "@typescript-eslint/parser",
parserOptions: {
project: true,
},
plugins: ["@typescript-eslint"],
extends: [
"next/core-web-vitals",
"plugin:@typescript-eslint/recommended-type-checked",
"plugin:@typescript-eslint/stylistic-type-checked",
],
rules: {
// These opinionated rules are enabled in stylistic-type-checked above.
// Feel free to reconfigure them to your own preference.
"@typescript-eslint/array-type": "off",
"@typescript-eslint/consistent-type-definitions": "off",
"@typescript-eslint/consistent-type-imports": [
"warn",
{
prefer: "type-imports",
fixStyle: "inline-type-imports",
},
],
"@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }],
"@typescript-eslint/no-misused-promises": [
2,
{
checksVoidReturn: { attributes: false },
},
],
},
};
module.exports = config;
+43
View File
@@ -0,0 +1,43 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# database
/prisma/*.db
/prisma/*.sqlite
/prisma/db.sqlite-journal
# next.js
/.next/
/out/
next-env.d.ts
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
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
.vercel
# typescript
*.tsbuildinfo
+2 -2
View File
@@ -1,2 +1,2 @@
# thatalex.dev
This is the repository for [my website](https://thatalex.dev)!
# Website
This is my website, [alexavfrantz.com](https://alexavfrantz.com)!
-52
View File
@@ -1,52 +0,0 @@
* {
margin: 0 auto;
padding:0;
}
body {
background-color:black;
font-family: 'DM Sans', sans-serif;
}
a {
color:white;
}
a:hover {
color:Gray
}
#container {
height:100vh;
}
#intro {
/* width:40%; */
color:white;
text-align:center;
padding-top:50px;
}
#socials a {
text-decoration:none;
padding:5px;
}
#footer {
text-align:center;
padding-bottom:10px;
}
#notice {
padding-top:2px;
}
/* global classes */
.center {
display: flex;
justify-content: center;
align-items: center;
/* height: 100vh; */
/* width:50vw; */
flex-direction: column;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 372 KiB

-39
View File
@@ -1,39 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/css/main.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@500&display=swap" rel="stylesheet">
<title>alex!</title>
</head>
<body>
<div id="container" class="center" style="color:white;">
<img src="/assets/img/pfp.png" width="150" style="border-radius:50%;" />
<h1>hi, i'm alex!</h1>
<p>part-time QA at <a href="https://medal.tv" target="_blank">Medal.tv</a>, full-time NodeJS/Swift geek</p>
<div id="footer" style="padding-top:10px;">
<div id="socials">
<a href="https://github.com/azpha" target="_blank" rel="noreferrer">
<i class="fa-brands fa-github" style="font-size:30px;"></i>
</a>
<a href="https://twitter.com/avvex__" target="_blank" rel="noreferrer">
<i class="fa-brands fa-twitter" style="font-size:30px;"></i>
</a>
<a href="https://linkedin.com/in/thatalex" target="_blank" rel="noreferrer">
<i class="fa-brands fa-linkedin" style="font-size:30px;"></i>
</a>
<a href="https://mast.thatalex.dev/@alex" rel="me" target="_blank">
<i class="fa-brands fa-mastodon" style="font-size:30px;"></i>
</a>
</div>
<p><a href="mailto:alex@alexavfrantz.com">alex@alexavfrantz.com</a></p>
</div>
</div>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful
* for Docker builds.
*/
await import("./src/env.mjs");
/** @type {import("next").NextConfig} */
const config = {
reactStrictMode: true,
i18n: {
locales: ["en"],
defaultLocale: "en",
},
images: {
remotePatterns: [
{
protocol: "https",
port: '',
hostname: "m.media-amazon.com"
}
]
}
};
export default config;
+4919
View File
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
{
"name": "website",
"version": "0.1.0",
"private": true,
"scripts": {
"build": "next build",
"db:push": "prisma db push",
"db:studio": "prisma studio",
"dev": "next dev",
"postinstall": "prisma generate",
"lint": "next lint",
"start": "next start"
},
"dependencies": {
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^5.1.1",
"@t3-oss/env-nextjs": "^0.7.0",
"@tanstack/react-query": "^4.32.6",
"@trpc/client": "^10.37.1",
"@trpc/next": "^10.37.1",
"@trpc/react-query": "^10.37.1",
"@trpc/server": "^10.37.1",
"next": "^13.5.4",
"next-auth": "^4.23.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"superjson": "^1.13.1",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/eslint": "^8.44.2",
"@types/node": "^18.16.0",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.3.0",
"@typescript-eslint/parser": "^6.3.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.47.0",
"eslint-config-next": "^13.5.4",
"postcss": "^8.4.27",
"prettier": "^3.0.0",
"prettier-plugin-tailwindcss": "^0.5.1",
"prisma": "^5.1.1",
"tailwindcss": "^3.3.3",
"typescript": "^5.1.6"
},
"ct3aMetadata": {
"initVersion": "7.22.0"
},
"packageManager": "npm@10.0.0"
}
+8
View File
@@ -0,0 +1,8 @@
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
module.exports = config;
+6
View File
@@ -0,0 +1,6 @@
/** @type {import('prettier').Config & import('prettier-plugin-tailwindcss').options} */
const config = {
plugins: ["prettier-plugin-tailwindcss"],
};
export default config;
+76
View File
@@ -0,0 +1,76 @@
// 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 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 Post {
id Int @id @default(autoincrement())
type String
name String
reviewContents String
image String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy User @relation(fields: [createdById], references: [id])
createdById String
@@index([name])
}
// 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[]
posts Post[]
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+30
View File
@@ -0,0 +1,30 @@
import Link from "next/link"
type HeaderItemProps = {
content: string,
linkTo: string,
onClick?: any, // don't even wanna bother
newWindow?: boolean
}
export default function HeaderItem(props: HeaderItemProps) {
console.log(props, props.newWindow ? "_blank" : "self")
if (props.onClick) {
return (
<>
<button className="inline hover:text-gray-500 hover:underline pr-2 "
onClick={props.onClick}
>
{props.content}
</button>
</>
)
} else {
return (
<p className="inline pr-2 hover:text-gray-500 hover:underline">
<Link href={props.linkTo} target={props.newWindow ? "_blank" : "_self"}>
{props.content}
</Link>
</p>
)
}
}
+18
View File
@@ -0,0 +1,18 @@
import Image from "next/image"
type ReviewCardProps = {
title: string,
image: string,
url: string
}
export default function ReviewCard(props: ReviewCardProps) {
return (
<>
<div className="inline pr-4 pb-2">
<Image alt={props.title + " cover"} width="160" height="160" src={props.image} />
<p className="font-bold pt-2 text-center">{props.title}</p>
</div>
</>
)
}
+22
View File
@@ -0,0 +1,22 @@
import Link from "next/link";
import {useSession, signIn, signOut} from 'next-auth/react';
import HeaderItem from "./HeaderItem";
export default function Header() {
const { data: session, status } = useSession()
return (
<>
<div className="text-white w-52 pt-2 pb-4 mx-auto">
<p className="text-2xl font-bold">alex</p>
<div className="inline-block pb-2">
<HeaderItem content="home" linkTo="/" />
<HeaderItem content="reviews" linkTo="/reviews" />
<HeaderItem content="contact" linkTo="/contact" />
<HeaderItem content={status == "unauthenticated" ? "login" : "logout" } onClick={status == "authenticated" ? signOut : signIn} linkTo="" />
</div>
<hr />
</div>
</>
)
}
+67
View File
@@ -0,0 +1,67 @@
import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";
export const env = createEnv({
/**
* Specify your server-side environment variables schema here. This way you can ensure the app
* isn't built with invalid env vars.
*/
server: {
DATABASE_URL: z
.string()
.url()
.refine(
(str) => !str.includes("YOUR_MYSQL_URL_HERE"),
"You forgot to change the default URL"
),
NODE_ENV: z
.enum(["development", "test", "production"])
.default("development"),
NEXTAUTH_SECRET:
process.env.NODE_ENV === "production"
? z.string()
: z.string().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() : z.string().url()
),
// Add ` 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_`.
*/
client: {
// NEXT_PUBLIC_CLIENTVAR: z.string(),
},
/**
* 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.
*/
runtimeEnv: {
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,
},
/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
* useful for Docker builds.
*/
skipValidation: !!process.env.SKIP_ENV_VALIDATION,
/**
* Makes it so that empty strings are treated as undefined.
* `SOME_VAR: z.string()` and `SOME_VAR=''` will throw an error.
*/
emptyStringAsUndefined: true,
});
+20
View File
@@ -0,0 +1,20 @@
import { type Session } from "next-auth";
import { SessionProvider } from "next-auth/react";
import { type AppType } from "next/app";
import { api } from "@/utils/api";
import "@/styles/globals.css";
const MyApp: AppType<{ session: Session | null }> = ({
Component,
pageProps: { session, ...pageProps },
}) => {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
};
export default api.withTRPC(MyApp);
+5
View File
@@ -0,0 +1,5 @@
import NextAuth from "next-auth";
import { authOptions } from "@/server/auth";
export default NextAuth(authOptions);
+19
View File
@@ -0,0 +1,19 @@
import { createNextApiHandler } from "@trpc/server/adapters/next";
import { env } from "@/env.mjs";
import { appRouter } from "@/server/api/root";
import { createTRPCContext } from "@/server/api/trpc";
// export API handler
export default createNextApiHandler({
router: appRouter,
createContext: createTRPCContext,
onError:
env.NODE_ENV === "development"
? ({ path, error }) => {
console.error(
`❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`
);
}
: undefined,
});
+80
View File
@@ -0,0 +1,80 @@
import { signIn, signOut, useSession } from "next-auth/react";
import Head from "next/head";
import Link from "next/link";
import { api } from "@/utils/api";
export default function Home() {
const hello = api.post.hello.useQuery({ text: "from tRPC" });
return (
<>
<Head>
<title>Create T3 App</title>
<meta name="description" content="Generated by create-t3-app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className=" flex min-h-screen flex-col items-center justify-center bg-gradient-to-b from-[#2e026d] to-[#15162c]">
<div className="container flex flex-col items-center justify-center gap-12 px-4 py-16 ">
<h1 className="text-5xl font-extrabold tracking-tight text-white sm:text-[5rem]">
Create <span className="text-[hsl(280,100%,70%)]">T3</span> App
</h1>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:gap-8">
<Link
className="flex max-w-xs flex-col gap-4 rounded-xl bg-white/10 p-4 text-white hover:bg-white/20"
href="https://create.t3.gg/en/usage/first-steps"
target="_blank"
>
<h3 className="text-2xl font-bold">First Steps →</h3>
<div className="text-lg">
Just the basics - Everything you need to know to set up your
database and authentication.
</div>
</Link>
<Link
className="flex max-w-xs flex-col gap-4 rounded-xl bg-white/10 p-4 text-white hover:bg-white/20"
href="https://create.t3.gg/en/introduction"
target="_blank"
>
<h3 className="text-2xl font-bold">Documentation →</h3>
<div className="text-lg">
Learn more about Create T3 App, the libraries it uses, and how
to deploy it.
</div>
</Link>
</div>
<div className="flex flex-col items-center gap-2">
<p className="text-2xl text-white">
{hello.data ? hello.data.greeting : "Loading tRPC query..."}
</p>
<AuthShowcase />
</div>
</div>
</main>
</>
);
}
function AuthShowcase() {
const { data: sessionData } = useSession();
const { data: secretMessage } = api.post.getSecretMessage.useQuery(
undefined, // no input
{ enabled: sessionData?.user !== undefined }
);
return (
<div className="flex flex-col items-center justify-center gap-4">
<p className="text-center text-2xl text-white">
{sessionData && <span>Logged in as {sessionData.user?.name}</span>}
{secretMessage && <span> - {secretMessage}</span>}
</p>
<button
className="rounded-full bg-white/10 px-10 py-3 font-semibold text-white no-underline transition hover:bg-white/20"
onClick={sessionData ? () => void signOut() : () => void signIn()}
>
{sessionData ? "Sign out" : "Sign in"}
</button>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { signIn, signOut, useSession } from "next-auth/react";
import Head from "next/head"
import Header from "@/components/header";
export default function Home() {
return (
<main className="min-h-screen bg-black color-white">
<div className="w-1/2 mx-auto text-white">
<Header />
<p>test</p>
</div>
</main>
)
}
+17
View File
@@ -0,0 +1,17 @@
import {useRouter} from 'next/router';
import {useState, useEffect} from 'react'
import {api} from '@/utils/api'
import { useSession } from 'next-auth/react';
export default function ReviewPage() {
const router = useRouter()
const name = router.query.name as string
const {data: bookData} = api.post.getOne.useQuery(name)
const [view,setView] = useState(null)
return (
<>
<p>Post: {router.query.name}</p>
</>
)
}
+68
View File
@@ -0,0 +1,68 @@
import {useSession, getSession} from 'next-auth/react';
import {useState, useEffect, FormEvent} from 'react';
import Header from '@/components/header';
import Router from 'next/router';
import { api } from "@/utils/api";
export default function Page() {
const { data: session, status } = useSession()
const mutation = api.post.create.useMutation()
const [loading, setLoading] = useState(true)
useEffect(() => {
if (status == "unauthenticated") {
console.log('user is unauthenticated!')
Router.replace('/')
} else {
setLoading(false)
}
}, [status])
function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const object = {
name: event.target.title.value,
reviewContents: event.target.review.value,
image: event.target.image.value,
type: event.target.type.value
}
mutation.mutate(object)
}
if (!loading) {
return (
<main className="min-h-screen bg-black color-white">
<div className="w-1/2 mx-auto text-white">
<Header />
<form onSubmit={onSubmit} className="text-black">
<div className="bg-gray-500 text-center">
<label className="font-bold">Title</label><br />
<input name="title" type="text" /><br />
<label className="font-bold">Image URL</label><br />
<input name="image" type="text" /><br />
<label className="font-bold">Content Type (book, movie, tv, game)</label><br />
<input name="type" type="text" /><br />
<label className="font-bold">Review</label><br />
<textarea name="review" />
<button type="submit">submit</button>
</div>
</form>
</div>
</main>
)
} else {
return (
<main>
<p>
Loading..
</p>
</main>
)
}
}
+47
View File
@@ -0,0 +1,47 @@
import Header from "@/components/header"
import ReviewCard from "@/components/ReviewCard"
import {useSession} from 'next-auth/react';
import {useState, useEffect} from 'react';
import { api } from "@/utils/api";
type GenericItemType = {
name: string,
image: string
}
export default function Reviews() {
const { data: sessionData, status } = useSession();
const {data: itemData} = api.post.getAll.useQuery()
const [list, setList] = useState<null | JSX.Element[]>(null)
useEffect(() => {
if (itemData) {
setList(
itemData?.map((v: GenericItemType) => {
return <ReviewCard title={v.name} url={`/reviews/${v.name}`} image={v.image} />
})
)
}
}, [itemData])
return (
<main className="min-h-screen bg-black color-white">
<div className="w-1/2 mx-auto text-white">
<Header />
{
status == "authenticated" ?
<p className="text-center font-bold">
<a href="/reviews/create">
Create
</a>
</p>
:
""
}
<div className="flex flex-wrap justify-center">
{list}
</div>
</div>
</main>
)
}
+14
View File
@@ -0,0 +1,14 @@
import { postRouter } from "@/server/api/routers/post";
import { createTRPCRouter } from "@/server/api/trpc";
/**
* This is the primary router for your server.
*
* All routers added in /api/routers should be manually added here.
*/
export const appRouter = createTRPCRouter({
post: postRouter,
});
// export type definition of API
export type AppRouter = typeof appRouter;
+54
View File
@@ -0,0 +1,54 @@
import { z } from "zod";
import {
createTRPCRouter,
protectedProcedure,
publicProcedure,
} from "@/server/api/trpc";
export const postRouter = createTRPCRouter({
create: protectedProcedure
.input(
z.object({
name: z.string().min(1),
reviewContents: z.string().min(1),
type: z.string().min(1),
image: z.string().min(1)
})
)
.mutation(async ({ ctx, input }) => {
// simulate a slow db call
await new Promise((resolve) => setTimeout(resolve, 1000));
return ctx.db.post.create({
data: {
name: input.name,
reviewContents: input.reviewContents,
type: input.type,
image: input.image,
createdBy: { connect: { id: ctx.session.user.id } },
},
});
}),
getOne: publicProcedure
.input(String)
.query(({ ctx, input }) => {
return ctx.db.post.findFirst({
where: { name: input },
});
}),
getAll: publicProcedure
.query(({ctx}) => {
return ctx.db.post.findMany()
}),
getAllOfType: publicProcedure
.input(String)
.query(({ctx, input}) => {
return ctx.db.post.findMany({
where: { type: input }
})
})
});
+131
View File
@@ -0,0 +1,131 @@
/**
* 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.
*/
import { initTRPC, TRPCError } from "@trpc/server";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { type Session } from "next-auth";
import superjson from "superjson";
import { ZodError } from "zod";
import { getServerAuthSession } from "@/server/auth";
import { db } from "@/server/db";
/**
* 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.
*/
interface 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#-serverapitrpcts
*/
const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
db,
};
};
/**
* 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.
*/
const t = initTRPC.context<typeof createTRPCContext>().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?.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);
+77
View File
@@ -0,0 +1,77 @@
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { type GetServerSidePropsContext } from "next";
import {
getServerSession,
type DefaultSession,
type NextAuthOptions,
} from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import { env } from "@/env.mjs";
import { db } 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: DefaultSession["user"] & {
id: string;
// ...other properties
// role: UserRole;
};
}
// 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 }) => ({
...session,
user: {
...session.user,
id: user.id,
},
}),
},
adapter: PrismaAdapter(db),
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);
};
+16
View File
@@ -0,0 +1,16 @@
import { PrismaClient } from "@prisma/client";
import { env } from "@/env.mjs";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const db =
globalForPrisma.prisma ??
new PrismaClient({
log:
env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"],
});
if (env.NODE_ENV !== "production") globalForPrisma.prisma = db;
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+68
View File
@@ -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<AppRouter>({
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<AppRouter>;
/**
* Inference helper for outputs.
*
* @example type HelloOutput = RouterOutputs['example']['hello']
*/
export type RouterOutputs = inferRouterOutputs<AppRouter>;
+14
View File
@@ -0,0 +1,14 @@
import { type Config } from "tailwindcss";
import { fontFamily } from "tailwindcss/defaultTheme";
export default {
content: ["./src/**/*.tsx"],
theme: {
extend: {
fontFamily: {
sans: ["var(--font-sans)", ...fontFamily.sans],
},
},
},
plugins: [],
} satisfies Config;
+35
View File
@@ -0,0 +1,35 @@
{
"compilerOptions": {
"target": "es2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"checkJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"noUncheckedIndexedAccess": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"plugins": [{ "name": "next" }]
},
"include": [
".eslintrc.cjs",
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.cjs",
"**/*.mjs",
".next/types/**/*.ts"
],
"exclude": ["node_modules"]
}