使用T3堆栈(Nextjs pages router+TRPC+prisma),我试图通过
getStaticProps
.
我有两条动态路线:
/[householdId]/shopping-list/[id].tsx
在里面
[id].tsx
s
getStaticProps
我正在访问这两个动态值,以便通过TRPC预取数据。
然而
家庭ID
由于某些原因在TRPC路由中变得未定义,即使它在仍处于
getStaticProps
这个
身份证件
价值工程。
[id].tsx getStaticProps部件:
export const getStaticProps: GetStaticProps = async (context) => {
const id = context.params?.id
const householdId = context.params?.householdId
const ssg = createProxySSGHelpers({
router: appRouter,
ctx: {
userId: null,
userOrgs: null,
prisma,
},
transformer: superjson,
})
if (id && householdId) {
// throw new Error(`id value: ${id}, householdId value: ${householdId}`) // this obviously is only for testing, but it shows that householdId has a value
await ssg.shoppingLists.getById.prefetch({ id, householdId })
}
return {
props: {
trpcState: ssg.dehydrate(),
id,
householdId,
},
}
}
从prisma检索数据的TRPC路由
export const shoppingLists = createTRPCRouter({
getById: publicProcedure
.input(
z.object({
id: z.string(),
householdId: z.any() // it will crash unless it's any, since householdId arrives undefined
})
)
.query(async (opts) => {
const id = opts.input.id
const householdId = opts.input.householdId
console.log("id - ", id)
console.log("household - ", householdId) // undefined
// logic to check if the authed user is a member of the household / organization
const userOrganizations = Object.keys(opts.ctx.userOrgs)
const isUserPartOfHousehold = userOrganizations.includes(householdId)
if (!isUserPartOfHousehold) {
throw new TRPCError({
code: "UNAUTHORIZED",
cause: "User not part of organization.",
})
}
const list = await prisma.shoppingList.findUnique({
where: {
id: opts.input.id,
},
include: {
items: true,
},
})
if (!list) throw new TRPCError({ code: "NOT_FOUND" })
return list
}),
create: privateProcedure
.input(
z.object({
name: z.string().min(1).max(280),
householdId: z.string(),
})
)
.mutation(async ({ ctx, input }) => {
const createdById = ctx.userId
const list = await ctx.prisma.shoppingList.create({
data: {
createdById,
name: input.name,
householdId: input.householdId,
},
})
return list
}),
})
证明householdId在中具有值
[id].tsx
s
getStaticProps
:
我真的被上面的事情弄糊涂了,因为好像什么都有。