From b54b581b1534104f27afea7836cd24a802b9e685 Mon Sep 17 00:00:00 2001 From: Ahoorast Date: Wed, 20 May 2026 18:08:41 +0330 Subject: [PATCH] batman --- README.md | 29 +++++++++ drizzle.config.ts | 12 ++++ eslint.config.js | 58 +++++++++++++++++ next.config.js | 10 +++ package.json | 57 +++++++++++++++++ postcss.config.js | 5 ++ prettier.config.js | 4 ++ public/favicon.ico | Bin 0 -> 15406 bytes src/app/_components/post.tsx | 50 +++++++++++++++ src/app/api/trpc/[trpc]/route.ts | 34 ++++++++++ src/app/layout.tsx | 29 +++++++++ src/app/page.tsx | 53 ++++++++++++++++ src/env.js | 44 +++++++++++++ src/server/api/root.ts | 23 +++++++ src/server/api/routers/post.ts | 30 +++++++++ src/server/api/trpc.ts | 106 +++++++++++++++++++++++++++++++ src/server/db/index.ts | 18 ++++++ src/server/db/schema.ts | 26 ++++++++ src/styles/globals.css | 6 ++ src/trpc/query-client.ts | 25 ++++++++ src/trpc/react.tsx | 78 +++++++++++++++++++++++ src/trpc/server.ts | 30 +++++++++ start-database.sh | 88 +++++++++++++++++++++++++ tsconfig.json | 42 ++++++++++++ 24 files changed, 857 insertions(+) create mode 100644 README.md create mode 100644 drizzle.config.ts create mode 100644 eslint.config.js create mode 100644 next.config.js create mode 100644 package.json create mode 100644 postcss.config.js create mode 100644 prettier.config.js create mode 100644 public/favicon.ico create mode 100644 src/app/_components/post.tsx create mode 100644 src/app/api/trpc/[trpc]/route.ts create mode 100644 src/app/layout.tsx create mode 100644 src/app/page.tsx create mode 100644 src/env.js create mode 100644 src/server/api/root.ts create mode 100644 src/server/api/routers/post.ts create mode 100644 src/server/api/trpc.ts create mode 100644 src/server/db/index.ts create mode 100644 src/server/db/schema.ts create mode 100644 src/styles/globals.css create mode 100644 src/trpc/query-client.ts create mode 100644 src/trpc/react.tsx create mode 100644 src/trpc/server.ts create mode 100755 start-database.sh create mode 100644 tsconfig.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..67943c7 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# Create T3 App + +This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. + +## What's next? How do I make an app with this? + +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. + +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. + +- [Next.js](https://nextjs.org) +- [NextAuth.js](https://next-auth.js.org) +- [Prisma](https://prisma.io) +- [Drizzle](https://orm.drizzle.team) +- [Tailwind CSS](https://tailwindcss.com) +- [tRPC](https://trpc.io) + +## Learn More + +To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: + +- [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 [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! + +## How do I deploy this? + +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/drizzle.config.ts b/drizzle.config.ts new file mode 100644 index 0000000..ea84b6e --- /dev/null +++ b/drizzle.config.ts @@ -0,0 +1,12 @@ +import { type Config } from "drizzle-kit"; + +import { env } from "~/env"; + +export default { + schema: "./src/server/db/schema.ts", + dialect: "postgresql", + dbCredentials: { + url: env.DATABASE_URL, + }, + tablesFilter: ["novin_*"], +} satisfies Config; diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..5409663 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,58 @@ +import { FlatCompat } from "@eslint/eslintrc"; +import tseslint from 'typescript-eslint'; +// @ts-ignore -- no types for this plugin +import drizzle from "eslint-plugin-drizzle"; + +const compat = new FlatCompat({ + baseDirectory: import.meta.dirname, +}); + +export default tseslint.config( + { + ignores: ['.next'] + }, + ...compat.extends("next/core-web-vitals"), + { + files: ['**/*.ts', '**/*.tsx'], + plugins: { + drizzle, + }, + extends: [ + ...tseslint.configs.recommended, + ...tseslint.configs.recommendedTypeChecked, + ...tseslint.configs.stylisticTypeChecked + ], + rules: { + "@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/require-await": "off", + "@typescript-eslint/no-misused-promises": [ + "error", + { checksVoidReturn: { attributes: false } }, + ], + "drizzle/enforce-delete-with-where": [ + "error", + { drizzleObjectName: ["db", "ctx.db"] }, + ], + "drizzle/enforce-update-with-where": [ + "error", + { drizzleObjectName: ["db", "ctx.db"] }, + ], + }, + }, + { + linterOptions: { + reportUnusedDisableDirectives: true + }, + languageOptions: { + parserOptions: { + projectService: true + } + } + } +) diff --git a/next.config.js b/next.config.js new file mode 100644 index 0000000..121c4f4 --- /dev/null +++ b/next.config.js @@ -0,0 +1,10 @@ +/** + * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful + * for Docker builds. + */ +import "./src/env.js"; + +/** @type {import("next").NextConfig} */ +const config = {}; + +export default config; diff --git a/package.json b/package.json new file mode 100644 index 0000000..fc9cc79 --- /dev/null +++ b/package.json @@ -0,0 +1,57 @@ +{ + "name": "novin", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "next build", + "check": "next lint && tsc --noEmit", + "db:generate": "drizzle-kit generate", + "db:migrate": "drizzle-kit migrate", + "db:push": "drizzle-kit push", + "db:studio": "drizzle-kit studio", + "dev": "next dev --turbo", + "format:check": "prettier --check \"**/*.{ts,tsx,js,jsx,mdx}\" --cache", + "format:write": "prettier --write \"**/*.{ts,tsx,js,jsx,mdx}\" --cache", + "lint": "next lint", + "lint:fix": "next lint --fix", + "preview": "next build && next start", + "start": "next start", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@t3-oss/env-nextjs": "^0.12.0", + "@tanstack/react-query": "^5.69.0", + "@trpc/client": "^11.0.0", + "@trpc/react-query": "^11.0.0", + "@trpc/server": "^11.0.0", + "drizzle-orm": "^0.41.0", + "next": "^15.2.3", + "postgres": "^3.4.4", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "server-only": "^0.0.1", + "superjson": "^2.2.1", + "zod": "^3.24.2" + }, + "devDependencies": { + "@eslint/eslintrc": "^3.3.1", + "@tailwindcss/postcss": "^4.0.15", + "@types/node": "^20.14.10", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "drizzle-kit": "^0.30.5", + "eslint": "^9.23.0", + "eslint-config-next": "^15.2.3", + "eslint-plugin-drizzle": "^0.2.3", + "postcss": "^8.5.3", + "prettier": "^3.5.3", + "prettier-plugin-tailwindcss": "^0.6.11", + "tailwindcss": "^4.0.15", + "typescript": "^5.8.2", + "typescript-eslint": "^8.27.0" + }, + "ct3aMetadata": { + "initVersion": "7.40.0" + } +} diff --git a/postcss.config.js b/postcss.config.js new file mode 100644 index 0000000..c2ddf74 --- /dev/null +++ b/postcss.config.js @@ -0,0 +1,5 @@ +export default { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; diff --git a/prettier.config.js b/prettier.config.js new file mode 100644 index 0000000..da332bd --- /dev/null +++ b/prettier.config.js @@ -0,0 +1,4 @@ +/** @type {import('prettier').Config & import('prettier-plugin-tailwindcss').PluginOptions} */ +export default { + plugins: ["prettier-plugin-tailwindcss"], +}; diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..60c702aac13409c82c4040f8fee9603eb84aa10c GIT binary patch literal 15406 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 A#Q*>R literal 0 HcmV?d00001 diff --git a/src/app/_components/post.tsx b/src/app/_components/post.tsx new file mode 100644 index 0000000..5618b40 --- /dev/null +++ b/src/app/_components/post.tsx @@ -0,0 +1,50 @@ +"use client"; + +import { useState } from "react"; + +import { api } from "~/trpc/react"; + +export function LatestPost() { + const [latestPost] = api.post.getLatest.useSuspenseQuery(); + + const utils = api.useUtils(); + const [name, setName] = useState(""); + const createPost = api.post.create.useMutation({ + onSuccess: async () => { + await utils.post.invalidate(); + setName(""); + }, + }); + + return ( +
+ {latestPost ? ( +

Your most recent post: {latestPost.name}

+ ) : ( +

You have no posts yet.

+ )} +
{ + e.preventDefault(); + createPost.mutate({ name }); + }} + className="flex flex-col gap-2" + > + setName(e.target.value)} + className="w-full rounded-full bg-white/10 px-4 py-2 text-white" + /> + +
+
+ ); +} diff --git a/src/app/api/trpc/[trpc]/route.ts b/src/app/api/trpc/[trpc]/route.ts new file mode 100644 index 0000000..f41a82e --- /dev/null +++ b/src/app/api/trpc/[trpc]/route.ts @@ -0,0 +1,34 @@ +import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; +import { type NextRequest } from "next/server"; + +import { env } from "~/env"; +import { appRouter } from "~/server/api/root"; +import { createTRPCContext } from "~/server/api/trpc"; + +/** + * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when + * handling a HTTP request (e.g. when you make requests from Client Components). + */ +const createContext = async (req: NextRequest) => { + return createTRPCContext({ + headers: req.headers, + }); +}; + +const handler = (req: NextRequest) => + fetchRequestHandler({ + endpoint: "/api/trpc", + req, + router: appRouter, + createContext: () => createContext(req), + onError: + env.NODE_ENV === "development" + ? ({ path, error }) => { + console.error( + `❌ tRPC failed on ${path ?? ""}: ${error.message}`, + ); + } + : undefined, + }); + +export { handler as GET, handler as POST }; diff --git a/src/app/layout.tsx b/src/app/layout.tsx new file mode 100644 index 0000000..e9c9cbf --- /dev/null +++ b/src/app/layout.tsx @@ -0,0 +1,29 @@ +import "~/styles/globals.css"; + +import { type Metadata } from "next"; +import { Geist } from "next/font/google"; + +import { TRPCReactProvider } from "~/trpc/react"; + +export const metadata: Metadata = { + title: "Create T3 App", + description: "Generated by create-t3-app", + icons: [{ rel: "icon", url: "/favicon.ico" }], +}; + +const geist = Geist({ + subsets: ["latin"], + variable: "--font-geist-sans", +}); + +export default function RootLayout({ + children, +}: Readonly<{ children: React.ReactNode }>) { + return ( + + + {children} + + + ); +} diff --git a/src/app/page.tsx b/src/app/page.tsx new file mode 100644 index 0000000..d7121d8 --- /dev/null +++ b/src/app/page.tsx @@ -0,0 +1,53 @@ +import Link from "next/link"; + +import { LatestPost } from "~/app/_components/post"; +import { api, HydrateClient } from "~/trpc/server"; + +export default async function Home() { + const hello = await api.post.hello({ text: "from tRPC" }); + + void api.post.getLatest.prefetch(); + + return ( + +
+
+

+ 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 ? hello.greeting : "Loading tRPC query..."} +

+
+ + +
+
+
+ ); +} diff --git a/src/env.js b/src/env.js new file mode 100644 index 0000000..6ca7f3e --- /dev/null +++ b/src/env.js @@ -0,0 +1,44 @@ +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(), + NODE_ENV: z + .enum(["development", "test", "production"]) + .default("development"), + }, + + /** + * 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, + // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, + }, + /** + * 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, +}); diff --git a/src/server/api/root.ts b/src/server/api/root.ts new file mode 100644 index 0000000..b341fc4 --- /dev/null +++ b/src/server/api/root.ts @@ -0,0 +1,23 @@ +import { postRouter } from "~/server/api/routers/post"; +import { createCallerFactory, 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; + +/** + * Create a server-side caller for the tRPC API. + * @example + * const trpc = createCaller(createContext); + * const res = await trpc.post.all(); + * ^? Post[] + */ +export const createCaller = createCallerFactory(appRouter); diff --git a/src/server/api/routers/post.ts b/src/server/api/routers/post.ts new file mode 100644 index 0000000..4bbf615 --- /dev/null +++ b/src/server/api/routers/post.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; + +import { createTRPCRouter, publicProcedure } from "~/server/api/trpc"; +import { posts } from "~/server/db/schema"; + +export const postRouter = createTRPCRouter({ + hello: publicProcedure + .input(z.object({ text: z.string() })) + .query(({ input }) => { + return { + greeting: `Hello ${input.text}`, + }; + }), + + create: publicProcedure + .input(z.object({ name: z.string().min(1) })) + .mutation(async ({ ctx, input }) => { + await ctx.db.insert(posts).values({ + name: input.name, + }); + }), + + getLatest: publicProcedure.query(async ({ ctx }) => { + const post = await ctx.db.query.posts.findFirst({ + orderBy: (posts, { desc }) => [desc(posts.createdAt)], + }); + + return post ?? null; + }), +}); diff --git a/src/server/api/trpc.ts b/src/server/api/trpc.ts new file mode 100644 index 0000000..4e24ba4 --- /dev/null +++ b/src/server/api/trpc.ts @@ -0,0 +1,106 @@ +/** + * 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 } from "@trpc/server"; +import superjson from "superjson"; +import { ZodError } from "zod"; + +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. + * + * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each + * wrap this and provides the required context. + * + * @see https://trpc.io/docs/server/context + */ +export const createTRPCContext = async (opts: { headers: Headers }) => { + return { + db, + ...opts, + }; +}; + +/** + * 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().create({ + transformer: superjson, + errorFormatter({ shape, error }) { + return { + ...shape, + data: { + ...shape.data, + zodError: + error.cause instanceof ZodError ? error.cause.flatten() : null, + }, + }; + }, +}); + +/** + * Create a server-side caller. + * + * @see https://trpc.io/docs/server/server-side-calls + */ +export const createCallerFactory = t.createCallerFactory; + +/** + * 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; + +/** + * Middleware for timing procedure execution and adding an artificial delay in development. + * + * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating + * network latency that would occur in production but not in local development. + */ +const timingMiddleware = t.middleware(async ({ next, path }) => { + const start = Date.now(); + + if (t._config.isDev) { + // artificial delay in dev + const waitMs = Math.floor(Math.random() * 400) + 100; + await new Promise((resolve) => setTimeout(resolve, waitMs)); + } + + const result = await next(); + + const end = Date.now(); + console.log(`[TRPC] ${path} took ${end - start}ms to execute`); + + return result; +}); + +/** + * 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.use(timingMiddleware); diff --git a/src/server/db/index.ts b/src/server/db/index.ts new file mode 100644 index 0000000..1287189 --- /dev/null +++ b/src/server/db/index.ts @@ -0,0 +1,18 @@ +import { drizzle } from "drizzle-orm/postgres-js"; +import postgres from "postgres"; + +import { env } from "~/env"; +import * as schema from "./schema"; + +/** + * Cache the database connection in development. This avoids creating a new connection on every HMR + * update. + */ +const globalForDb = globalThis as unknown as { + conn: postgres.Sql | undefined; +}; + +const conn = globalForDb.conn ?? postgres(env.DATABASE_URL); +if (env.NODE_ENV !== "production") globalForDb.conn = conn; + +export const db = drizzle(conn, { schema }); diff --git a/src/server/db/schema.ts b/src/server/db/schema.ts new file mode 100644 index 0000000..d9b73b1 --- /dev/null +++ b/src/server/db/schema.ts @@ -0,0 +1,26 @@ +// Example model schema from the Drizzle docs +// https://orm.drizzle.team/docs/sql-schema-declaration + +import { index, pgTableCreator } from "drizzle-orm/pg-core"; + +/** + * This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same + * database instance for multiple projects. + * + * @see https://orm.drizzle.team/docs/goodies#multi-project-schema + */ +export const createTable = pgTableCreator((name) => `novin_${name}`); + +export const posts = createTable( + "post", + (d) => ({ + id: d.integer().primaryKey().generatedByDefaultAsIdentity(), + name: d.varchar({ length: 256 }), + createdAt: d + .timestamp({ withTimezone: true }) + .$defaultFn(() => /* @__PURE__ */ new Date()) + .notNull(), + updatedAt: d.timestamp({ withTimezone: true }).$onUpdate(() => new Date()), + }), + (t) => [index("name_idx").on(t.name)] +); diff --git a/src/styles/globals.css b/src/styles/globals.css new file mode 100644 index 0000000..8fe04fa --- /dev/null +++ b/src/styles/globals.css @@ -0,0 +1,6 @@ +@import "tailwindcss"; + +@theme { + --font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif, + "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; +} diff --git a/src/trpc/query-client.ts b/src/trpc/query-client.ts new file mode 100644 index 0000000..bda6439 --- /dev/null +++ b/src/trpc/query-client.ts @@ -0,0 +1,25 @@ +import { + defaultShouldDehydrateQuery, + QueryClient, +} from "@tanstack/react-query"; +import SuperJSON from "superjson"; + +export 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, + }, + dehydrate: { + serializeData: SuperJSON.serialize, + shouldDehydrateQuery: (query) => + defaultShouldDehydrateQuery(query) || + query.state.status === "pending", + }, + hydrate: { + deserializeData: SuperJSON.deserialize, + }, + }, + }); diff --git a/src/trpc/react.tsx b/src/trpc/react.tsx new file mode 100644 index 0000000..378290c --- /dev/null +++ b/src/trpc/react.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { QueryClientProvider, type QueryClient } from "@tanstack/react-query"; +import { httpBatchStreamLink, loggerLink } from "@trpc/client"; +import { createTRPCReact } from "@trpc/react-query"; +import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; +import { useState } from "react"; +import SuperJSON from "superjson"; + +import { type AppRouter } from "~/server/api/root"; +import { createQueryClient } from "./query-client"; + +let clientQueryClientSingleton: QueryClient | undefined = undefined; +const getQueryClient = () => { + if (typeof window === "undefined") { + // Server: always make a new query client + return createQueryClient(); + } + // Browser: use singleton pattern to keep the same query client + clientQueryClientSingleton ??= createQueryClient(); + + return clientQueryClientSingleton; +}; + +export const api = createTRPCReact(); + +/** + * 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; + +export function TRPCReactProvider(props: { children: React.ReactNode }) { + const queryClient = getQueryClient(); + + const [trpcClient] = useState(() => + api.createClient({ + links: [ + loggerLink({ + enabled: (op) => + process.env.NODE_ENV === "development" || + (op.direction === "down" && op.result instanceof Error), + }), + httpBatchStreamLink({ + transformer: SuperJSON, + url: getBaseUrl() + "/api/trpc", + headers: () => { + const headers = new Headers(); + headers.set("x-trpc-source", "nextjs-react"); + return headers; + }, + }), + ], + }) + ); + + return ( + + + {props.children} + + + ); +} + +function getBaseUrl() { + if (typeof window !== "undefined") return window.location.origin; + if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; + return `http://localhost:${process.env.PORT ?? 3000}`; +} diff --git a/src/trpc/server.ts b/src/trpc/server.ts new file mode 100644 index 0000000..91e557e --- /dev/null +++ b/src/trpc/server.ts @@ -0,0 +1,30 @@ +import "server-only"; + +import { createHydrationHelpers } from "@trpc/react-query/rsc"; +import { headers } from "next/headers"; +import { cache } from "react"; + +import { createCaller, type AppRouter } from "~/server/api/root"; +import { createTRPCContext } from "~/server/api/trpc"; +import { createQueryClient } from "./query-client"; + +/** + * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when + * handling a tRPC call from a React Server Component. + */ +const createContext = cache(async () => { + const heads = new Headers(await headers()); + heads.set("x-trpc-source", "rsc"); + + return createTRPCContext({ + headers: heads, + }); +}); + +const getQueryClient = cache(createQueryClient); +const caller = createCaller(createContext); + +export const { trpc: api, HydrateClient } = createHydrationHelpers( + caller, + getQueryClient +); diff --git a/start-database.sh b/start-database.sh new file mode 100755 index 0000000..955ad4e --- /dev/null +++ b/start-database.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Use this script to start a docker container for a local development database + +# TO RUN ON WINDOWS: +# 1. Install WSL (Windows Subsystem for Linux) - https://learn.microsoft.com/en-us/windows/wsl/install +# 2. Install Docker Desktop or Podman Deskop +# - Docker Desktop for Windows - https://docs.docker.com/docker-for-windows/install/ +# - Podman Desktop - https://podman.io/getting-started/installation +# 3. Open WSL - `wsl` +# 4. Run this script - `./start-database.sh` + +# On Linux and macOS you can run this script directly - `./start-database.sh` + +# import env variables from .env +set -a +source .env + +DB_PASSWORD=$(echo "$DATABASE_URL" | awk -F':' '{print $3}' | awk -F'@' '{print $1}') +DB_PORT=$(echo "$DATABASE_URL" | awk -F':' '{print $4}' | awk -F'\/' '{print $1}') +DB_NAME=$(echo "$DATABASE_URL" | awk -F'/' '{print $4}') +DB_CONTAINER_NAME="$DB_NAME-postgres" + +if ! [ -x "$(command -v docker)" ] && ! [ -x "$(command -v podman)" ]; then + echo -e "Docker or Podman is not installed. Please install docker or podman and try again.\nDocker install guide: https://docs.docker.com/engine/install/\nPodman install guide: https://podman.io/getting-started/installation" + exit 1 +fi + +# determine which docker command to use +if [ -x "$(command -v docker)" ]; then + DOCKER_CMD="docker" +elif [ -x "$(command -v podman)" ]; then + DOCKER_CMD="podman" +fi + +if ! $DOCKER_CMD info > /dev/null 2>&1; then + echo "$DOCKER_CMD daemon is not running. Please start $DOCKER_CMD and try again." + exit 1 +fi + +if command -v nc >/dev/null 2>&1; then + if nc -z localhost "$DB_PORT" 2>/dev/null; then + echo "Port $DB_PORT is already in use." + exit 1 + fi +else + echo "Warning: Unable to check if port $DB_PORT is already in use (netcat not installed)" + read -p "Do you want to continue anyway? [y/N]: " -r REPLY + if ! [[ $REPLY =~ ^[Yy]$ ]]; then + echo "Aborting." + exit 1 + fi +fi + +if [ "$($DOCKER_CMD ps -q -f name=$DB_CONTAINER_NAME)" ]; then + echo "Database container '$DB_CONTAINER_NAME' already running" + exit 0 +fi + +if [ "$($DOCKER_CMD ps -q -a -f name=$DB_CONTAINER_NAME)" ]; then + $DOCKER_CMD start "$DB_CONTAINER_NAME" + echo "Existing database container '$DB_CONTAINER_NAME' started" + exit 0 +fi + +if [ "$DB_PASSWORD" = "password" ]; then + echo "You are using the default database password" + read -p "Should we generate a random password for you? [y/N]: " -r REPLY + if ! [[ $REPLY =~ ^[Yy]$ ]]; then + echo "Please change the default password in the .env file and try again" + exit 1 + fi + # Generate a random URL-safe password + DB_PASSWORD=$(openssl rand -base64 12 | tr '+/' '-_') + if [[ "$(uname)" == "Darwin" ]]; then + # macOS requires an empty string to be passed with the `i` flag + sed -i '' "s#:password@#:$DB_PASSWORD@#" .env + else + sed -i "s#:password@#:$DB_PASSWORD@#" .env + fi +fi + +$DOCKER_CMD run -d \ + --name $DB_CONTAINER_NAME \ + -e POSTGRES_USER="postgres" \ + -e POSTGRES_PASSWORD="$DB_PASSWORD" \ + -e POSTGRES_DB="$DB_NAME" \ + -p "$DB_PORT":5432 \ + docker.io/postgres && echo "Database container '$DB_CONTAINER_NAME' was successfully created" diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..3eb759e --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,42 @@ +{ + "compilerOptions": { + /* Base Options: */ + "esModuleInterop": true, + "skipLibCheck": true, + "target": "es2022", + "allowJs": true, + "resolveJsonModule": true, + "moduleDetection": "force", + "isolatedModules": true, + "verbatimModuleSyntax": true, + + /* Strictness */ + "strict": true, + "noUncheckedIndexedAccess": true, + "checkJs": true, + + /* Bundled projects */ + "lib": ["dom", "dom.iterable", "ES2022"], + "noEmit": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "preserve", + "plugins": [{ "name": "next" }], + "incremental": true, + + /* Path Aliases */ + "baseUrl": ".", + "paths": { + "~/*": ["./src/*"] + } + }, + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + "**/*.cjs", + "**/*.js", + ".next/types/**/*.ts" + ], + "exclude": ["node_modules", "generated"] +}