MadMax
MadMax
Explore posts from servers
TtRPC
Created by MadMax on 4/1/2024 in #❓-help
Tried to access "$types.prototype" which is not available at runtime
It works now thanks for working on this...
8 replies
TtRPC
Created by MadMax on 4/1/2024 in #❓-help
Tried to access "$types.prototype" which is not available at runtime
Please help
8 replies
TtRPC
Created by MadMax on 4/1/2024 in #❓-help
Tried to access "$types.prototype" which is not available at runtime
and this is root.ts
import { initTRPC } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";

import { db } from "@/server/db";
import { getServerSession } from "@/lib/server-session";

export const createTRPCContext = async (opts: { headers: Headers }) => {
const session = await getServerSession();
return {
session,
db,
...opts,
};
};

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,
},
};
},
});
export const createCallerFactory = t.createCallerFactory;

export const createTRPCRouter = t.router;

export const procedure = t.procedure;
import { initTRPC } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";

import { db } from "@/server/db";
import { getServerSession } from "@/lib/server-session";

export const createTRPCContext = async (opts: { headers: Headers }) => {
const session = await getServerSession();
return {
session,
db,
...opts,
};
};

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,
},
};
},
});
export const createCallerFactory = t.createCallerFactory;

export const createTRPCRouter = t.router;

export const procedure = t.procedure;
All other files are as it is that comes from create t3 app
8 replies
TtRPC
Created by MadMax on 4/1/2024 in #❓-help
Tried to access "$types.prototype" which is not available at runtime
React.tsx
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpLink, loggerLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { useState } from "react";
import SuperJSON from "superjson";

import { type AppRouter } from "@/server/api/root";

const createQueryClient = () => new QueryClient();

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
return (clientQueryClientSingleton ??= createQueryClient());
};

export const api = createTRPCReact<AppRouter>();

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),
}),
httpLink({
transformer: SuperJSON,
url: getBaseUrl() + "/api/trpc",
headers: () => {
const headers = new Headers();
headers.set("x-trpc-source", "nextjs-react");
return headers;
},
}),
],
}),
);

return (
<QueryClientProvider client={queryClient}>
<api.Provider client={trpcClient} queryClient={queryClient}>
{props.children}
</api.Provider>
</QueryClientProvider>
);
}

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}`;
}
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpLink, loggerLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { useState } from "react";
import SuperJSON from "superjson";

import { type AppRouter } from "@/server/api/root";

const createQueryClient = () => new QueryClient();

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
return (clientQueryClientSingleton ??= createQueryClient());
};

export const api = createTRPCReact<AppRouter>();

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),
}),
httpLink({
transformer: SuperJSON,
url: getBaseUrl() + "/api/trpc",
headers: () => {
const headers = new Headers();
headers.set("x-trpc-source", "nextjs-react");
return headers;
},
}),
],
}),
);

return (
<QueryClientProvider client={queryClient}>
<api.Provider client={trpcClient} queryClient={queryClient}>
{props.children}
</api.Provider>
</QueryClientProvider>
);
}

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}`;
}
8 replies
TTCTheo's Typesafe Cult
Created by Mike Pollard on 1/23/2024 in #questions
Is the backend of this stack a lambdalith (lambda monolith) when hosted serverless?
all the stuff is done in a one lambda api pages everything
6 replies
TTCTheo's Typesafe Cult
Created by JulieCezar on 1/26/2024 in #questions
Relations using Drizzle and Planetscale
firstly planetscale does support foreign key constraints for relations you have to define them both ways user -> many posts post -> one user that way its kind of guranteed that you are getting and inserting right data depends upon if you did it correctly all your other points relate to data access patterns which is upon you to implement correctly read drizzle docs they are great
5 replies
TtRPC
Created by MadMax on 1/21/2024 in #❓-help
How to infer query types on client?
on client
type tenatType = RouterOutputs["tenant"]["getUsers"] | undefined;
const test: tenatType = trpc.tenant.getUsers.useQuery().data
type tenatType = RouterOutputs["tenant"]["getUsers"] | undefined;
const test: tenatType = trpc.tenant.getUsers.useQuery().data
test has type User[] an empty array
6 replies
TtRPC
Created by MadMax on 1/21/2024 in #❓-help
How to infer query types on client?
getUsers: procedure.query(async ({ ctx }): Promise<User[]> => {
const res = await getAllUsers(ctx.user.tenant_id);
if (res.isError() || !res.value) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Users not found",
});
}
return res.value;
})
getUsers: procedure.query(async ({ ctx }): Promise<User[]> => {
const res = await getAllUsers(ctx.user.tenant_id);
if (res.isError() || !res.value) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Users not found",
});
}
return res.value;
})
hovering over value clearly has type
(property) Result<{ name: string; email: string | null; permissions: unknown; role: string | null; id: string; createdAt: string | null; tenantId: string | null; cognitoId: string | null; }[], Error>.value: {
name: string;
email: string | null;
permissions: unknown;
role: string | null;
id: string;
createdAt: string | null;
tenantId: string | null;
cognitoId: string | null;
}[]
(property) Result<{ name: string; email: string | null; permissions: unknown; role: string | null; id: string; createdAt: string | null; tenantId: string | null; cognitoId: string | null; }[], Error>.value: {
name: string;
email: string | null;
permissions: unknown;
role: string | null;
id: string;
createdAt: string | null;
tenantId: string | null;
cognitoId: string | null;
}[]
6 replies
TTCTheo's Typesafe Cult
Created by Chen on 1/18/2024 in #questions
Running TSC on tRPC client runs type checking on tRPC server
@Scythern you should create separate files for handler and router and router file should only export types nothing else like
const appRouter = router()
export type AppRouter = typeof appRouter;
const appRouter = router()
export type AppRouter = typeof appRouter;
3 replies
TtRPC
Created by MadMax on 1/21/2024 in #❓-help
How to infer query types on client?
While this works I wonder why
getTenant: procedure.query(async ({ ctx }) => {
const res = await getTenantById(ctx.user.tenant_id);
if (res.isError() || !res.value) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Tenant not found",
});
}
return {
name: res.value.name,
website: res.value.website,
email: res.value.email,
picture: res.value.picture,
};
}),
getTenant: procedure.query(async ({ ctx }) => {
const res = await getTenantById(ctx.user.tenant_id);
if (res.isError() || !res.value) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Tenant not found",
});
}
return {
name: res.value.name,
website: res.value.website,
email: res.value.email,
picture: res.value.picture,
};
}),
6 replies
TtRPC
Created by MadMax on 1/21/2024 in #❓-help
How to infer query types on client?
This also doesnt work
return res.value as Tenant
return res.value as Tenant
hovering over test2 shows this data is still type any
(property) getTenant: DecoratedQuery<RootConfig<{
ctx: {
user: IdToken;
};
meta: object;
errorShape: DefaultErrorShape;
transformer: typeof SuperJSON;
}>, QueryProcedure<{
input: void;
output: Tenant;
}>>
(property) getTenant: DecoratedQuery<RootConfig<{
ctx: {
user: IdToken;
};
meta: object;
errorShape: DefaultErrorShape;
transformer: typeof SuperJSON;
}>, QueryProcedure<{
input: void;
output: Tenant;
}>>
6 replies
TTCTheo's Typesafe Cult
Created by MadMax on 11/27/2023 in #questions
Getting role undefined in session even though it exist in db
at drizzle adapter im getting
ts Type AdapterUser
is not assignable to type Awaitable<AdapterUser>
Property 'role' is missing in type

ts Type AdapterUser
is not assignable to type Awaitable<AdapterUser>
Property 'role' is missing in type

7 replies
TTCTheo's Typesafe Cult
Created by MadMax on 11/27/2023 in #questions
Getting role undefined in session even though it exist in db
export const users = mysqlTable(
"user",
{
id: varchar("id", { length: 255 }).notNull().primaryKey(),
name: varchar("name", { length: 255 }),
email: varchar("email", { length: 255 }).notNull(),
emailVerified: timestamp("emailVerified", {
mode: "date",
fsp: 3,
}).default(sql`CURRENT_TIMESTAMP(3)`),
image: varchar("image", { length: 255 }),
tenantId: varchar("tenantId", { length: 255 }),
role: mysqlEnum("role", ["user", "admin"]).default("admin"),
},
(user) => ({
emailIdx: index("email_idx").on(user.email),
tenantIdIdx: index("tenantId_idx").on(user.tenantId),
}),
);
export const users = mysqlTable(
"user",
{
id: varchar("id", { length: 255 }).notNull().primaryKey(),
name: varchar("name", { length: 255 }),
email: varchar("email", { length: 255 }).notNull(),
emailVerified: timestamp("emailVerified", {
mode: "date",
fsp: 3,
}).default(sql`CURRENT_TIMESTAMP(3)`),
image: varchar("image", { length: 255 }),
tenantId: varchar("tenantId", { length: 255 }),
role: mysqlEnum("role", ["user", "admin"]).default("admin"),
},
(user) => ({
emailIdx: index("email_idx").on(user.email),
tenantIdIdx: index("tenantId_idx").on(user.tenantId),
}),
);
7 replies