开发者

Inconsistent Type assertion in typescript when in Trpc publicProcedure (with prisma)

I am trying to create a public procedure to query a product that is stored in my database. If the product is not found, I am asking Prisma to throw an error, in fact, I am using the findUniqueOrThrow function.

This is what the snippet looks like

getProductById: publicProcedure
    .input(z.object({ pid: z.string() }))
    .query(async ({ ctx, input }) => {
       
      try{
        return await ctx.prisma.pollProduct.findUniqueOrThrow({
          where: {
            pid: input.pid,
          },
        });
      }
      catch(e){
        if(e instanceof Prisma.NotFoundError){
          // At this point productData is CjResponse | undefined
          const {data: productData, isFetched} = trpc.cjApi.getItemById.useQuery({productId: input.pid})

          // In the if statement, productData is CjResponse since we know for a fact that it's not a falsy value
          if( productData && productData.data){
            return ctx.prisma.pollProduct.create({
              data: {
                // As soon as productData is assigned as the value of the description key
                // the value is becomes `any`
                description: productData 
              }
            })
          }
        }
      }
      
    }),

I am considering taking a different approach, but I would like to know if this is wrong on my end or if typescript is tripping. Thank yo开发者_如何学Gou for your time.

Note that I am aware that it would be better to use findUnique and check if the result is null, given that my catch block as of right now would be triggered for any other error. It is simply puzzling to me that typescript would behave like this.

edit: It looks like it doesn't relly appreciate the fact that I am using a trpc query inside a public procedure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜