Skip to content

Commit

Permalink
trpc intial setup
Browse files Browse the repository at this point in the history
  • Loading branch information
amitsingh-007 committed Oct 9, 2024
1 parent 59d7063 commit 2f779fa
Show file tree
Hide file tree
Showing 12 changed files with 233 additions and 33 deletions.
31 changes: 1 addition & 30 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,36 +1,7 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.env
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
2 changes: 2 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import("./src/server/env.mjs");

/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
Expand Down
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"start": "pnpm build && next start",
"lint": "next lint",
"deploy:preview": "vercel",
"deploy": "vercel --prod"
"deploy": "vercel --prod",
"env": "vercel env pull .env"
},
"dependencies": {
"@hookform/resolvers": "3.9.0",
Expand All @@ -21,7 +22,11 @@
"@radix-ui/react-select": "2.1.1",
"@radix-ui/react-slot": "1.1.0",
"@radix-ui/react-tabs": "1.1.1",
"@t3-oss/env-nextjs": "0.11.1",
"@tanstack/react-query": "5.56.2",
"@trpc/client": "10.45.2",
"@trpc/react-query": "10.45.2",
"@trpc/server": "10.45.2",
"add": "2.0.6",
"class-variance-authority": "0.7.0",
"clsx": "2.1.1",
Expand Down
74 changes: 74 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions src/app/api/trpc/[trpc]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { appRouter } from "@/server/api/routers/root";
import { createTRPCContext } from "@/server/api/trpc";
import env from "@/server/env.mjs";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { type NextRequest } from "next/server";

const handler = (req: NextRequest) => {
return fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
createContext: () => createTRPCContext(req),
onError:
env.NEXT_PUBLIC_VERCEL_ENV === "production"
? undefined
: ({ path, error }) => {
console.error(`tRPC failed on ${path}: ${error}`);
},
});
};
export { handler as GET, handler as POST };
5 changes: 4 additions & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ export default function Home() {
<h2 className="scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0">
Dashboard
</h2>
<Tabs defaultValue="dashboard-table" className="flex flex-col items-center mt-4 mx-auto">
<Tabs
defaultValue="dashboard-table"
className="flex flex-col items-center mt-4 mx-auto"
>
<TabsList className="mx-auto">
<TabsTrigger value="dashboard-table">Dashboard</TabsTrigger>
<TabsTrigger value="dashboard-history">Historical View</TabsTrigger>
Expand Down
8 changes: 8 additions & 0 deletions src/helpers/firebase/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
signInWithPopup,
signOut,
User,
getIdToken,
} from "firebase/auth";
import firebaseApp from ".";

Expand Down Expand Up @@ -41,3 +42,10 @@ export const getCurrentUser = () => {

export const onAuthStateChange = (callback: NextOrObserver<User>) =>
onAuthStateChanged(auth, callback);

export const getClientIdToken = async () => {
if (!auth.currentUser) {
return null;
}
return getIdToken(auth.currentUser, true);
};
15 changes: 15 additions & 0 deletions src/server/api/routers/root.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { t } from "../trpc";

const extensionRouter = t.router({
hello: t.procedure.query(() => {
return {
text: "Hello World!",
};
}),
});

export const appRouter = t.router({
extension: extensionRouter,
});

export type AppRouter = typeof appRouter;
48 changes: 48 additions & 0 deletions src/server/api/trpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { TRPCError, initTRPC } from "@trpc/server";
// import { ITRPCContext } from "./@types/trpc";
// import {
// getFirebaseUser,
// verifyAuthToken,
// } from "./services/firebaseAdminService";
// import { getAuthBearer, getIpAddress } from "./utils/headers";

interface ITRPCContext {}

// const getLoggedInUser = async (idToken: string | undefined) => {
// if (!idToken) {
// return null;
// }
// try {
// const { uid } = await verifyAuthToken(idToken, true);
// return await getFirebaseUser(uid);
// } catch (error) {
// console.error(error);
// throw new TRPCError({
// code: "UNAUTHORIZED",
// message: "Firebase authorization failed",
// });
// }
// };

const getAuthBearer = (req: Request) =>
req.headers.get("authorization")?.split?.("Bearer ")?.[1];

export const createTRPCContext = async (
req: Request
): Promise<ITRPCContext> => {
const { headers } = req;
const bearerToken = getAuthBearer(req);
// const user = await getLoggedInUser(bearerToken);

return {
// user,
};
};

export const t = initTRPC
.context<Awaited<ReturnType<typeof createTRPCContext>>>()
.create({
errorFormatter({ shape }) {
return shape;
},
});
17 changes: 17 additions & 0 deletions src/server/env.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";

const env = createEnv({
server: {
VERCEL_URL: z.string().url(),
},
client: {
NEXT_PUBLIC_VERCEL_ENV: z.enum(["development", "production"]),
},
experimental__runtimeEnv: {
NEXT_PUBLIC_VERCEL_ENV: process.env.NEXT_PUBLIC_VERCEL_ENV,
VERCEL_URL: process.env.VERCEL_URL,
},
});

export default env;
30 changes: 30 additions & 0 deletions src/trpc-client/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { getClientIdToken } from "@/helpers/firebase/auth";
import { AppRouter } from "@/server/api/routers/root";
import env from "@/server/env.mjs";
import { createTRPCProxyClient, httpBatchLink, loggerLink } from "@trpc/client";

const getBaseUrl = () => {
if (typeof window !== "undefined") {
return "";
}
return env.VERCEL_URL;
};

export const api = createTRPCProxyClient<AppRouter>({
links: [
loggerLink({
enabled: (opts) => {
if (env.NEXT_PUBLIC_VERCEL_ENV === "development") {
return true;
}
return opts.direction === "down" && opts.result instanceof Error;
},
}),
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
headers: async () => ({
authorization: `Bearer ${await getClientIdToken()}`,
}),
}),
],
});
8 changes: 7 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"src/**/*.mjs"
],
"exclude": ["node_modules"]
}

0 comments on commit 2f779fa

Please sign in to comment.