Develop a TypeScript utility function for Prisma

Having trouble inferring the correct type for my utility function:

function customUtilityFunction<
  P, R, A extends unknown[]
>(
  prismaArgs /* Make "where" field optional as it is already defined inside findUnique method below */,
  fn: (
    prismaData /* Need to dynamically determine the same type as prismaData defined inside async function below based on prismaArgs */,
    ...args: A
  ) => Promise<R>
){
  return async function(...args: A){
    const prismaData = await prisma.session.findUnique({
      ...prismaArgs,
      where: {
        ...prismaArgs.where,
        sessionId: getSessionId()
      }
    })
    return await fn(prismaData, ...args)
  }
}

const dynamicFn = customUtilityFunction(
  { 
    include: {
      user: { userId: true }
    }
  },
  async (prismaData, arg1, arg2) => {
    //    ^? (parameter) prismaData: { ...sessionField, user: { userId: string } }
  }
)

dynamicFn(arg1, arg2)

Successfully achieved type inference on prismaData, but used methods like casting and any that are not best practices. Seeking a more proper solution.

Answer №1

This is my approach to solving the problem:

export function validateUser<
  R,
  S extends Omit<Prisma.SessionFindUniqueArgs, 'where'>,
  A extends unknown[],
>(
  prismaArgs: S,
  fn: (
    prismaData: Prisma.SessionGetPayload<typeof newPrismaArgs>,
    ...args: A
  ) => Promise<R>
) {
  const newPrismaArgs = {
    ...prismaArgs,
    where: {
      ...prismaWhereSafeSession(),
    },
  };
  return async function (...args: A) {
    const prismaData = (await prisma.session.findUnique(
      newPrismaArgs
    )) as Prisma.SessionGetPayload<typeof newPrismaArgs> | null;

    if (!prismaData) {
      redirectToLogin();
    }

    return await fn(prismaData, ...args);
  };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with routing during startup of Ionic 4 application

We are currently working on a project using Ionic 4 along with Angular framework. One of the issues we are facing is related to logging into the application. Below is a screenshot illustrating the error: Here is the snippet of my code: import { NgModul ...

Tips for converting text input in a textbox to a Date value

My knowledge of Angular is limited, and we are currently using Angular 10. In our application, there is a textbox where users need to input a date in the format 10202020. This value should then be reformatted as 10/20/2020 and displayed back in the same ...

The tRPC setData hook is limited in its ability to access all data necessary for optimistic UI updates

As I integrate mutations using tRPC and React Query to optimistically update my UI upon adding a new item, I've encountered an issue. The problem lies in the query I'm updating, which requires specific properties like auto-generated IDs or datab ...

Troubleshooting Typescript compilation issues following an upgrade to a React Native project

I am facing a challenge while updating a react native project from version 0.63.3 to 0.67.0. When attempting to run npm run tsc, I encounter numerous errors indicating that the typescript packages are not compatible with their original packages. Here is a ...

Create a new contact in Prisma by establishing a self-referential relationship

My Prisma schema looks like this: model User { userId Int @id @default(autoincrement()) registeredAt DateTime @default(now()) firstName String @db.VarChar(250) lastName String @db.VarChar(250) email St ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

What is the most effective way to determine the data type of a value associated with a key in an interface?

In my TypeScript interface, I have defined the following structure: MyInterface { 'key1': number | string; 'key2': string; 'key3': SomeOtherInterface; } I am looking to create a new type that utilizes the properties of ...

Accessing an external API through a tRPC endpoint (tRPC Promise is resolved before processing is complete)

I want to utilize OpenAI's API within my Next.js + tRPC application. It appears that my front-end is proceeding without waiting for the back-end to finish the API request, resulting in an error due to the response still being undefined. Below is my e ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

How can I provide type annotations for search parameters in Next.js 13?

Within my Next.js 13 project, I've implemented a login form structure as outlined below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "n ...

Is it possible to utilize instanceof to verify whether a certain variable is of a class constructor type in TypeScript?

I am currently facing an issue with a function that takes a constructor as a parameter and creates an instance based on that constructor. When attempting to check the type of the constructor, I encountered an error. Below are some snippets of code that I ...

Prevent coverage tracking for files or paths enclosed in square brackets in jest

I am trying to exclude a specific file from test coverage in Jest by modifying the collectCoverageFrom array. The file name contains square brackets, and I have added an entry with a negation for this file. collectCoverageFrom: [ './src/**/*.{js ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

Testing Angular 11 methods using Jest unit tests within a .then block

Currently, I am running jest unit tests in Angular 11 and facing an issue while testing methods within the .then method. It seems like the test methods are not being executed at the expect method. I need guidance on how to structure the test code to ens ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...