Exploring the Typesafety of Prisma Client Extension Queries

I am working on creating a Prisma Client Extension that can insert specific imports into a model.

const postExtention = Prisma.defineExtension((prisma) =>
  prisma.$extends({
    name: 'postExtention',
    query: {
      post: {
        $allOperations({ operation, args, query }) {
          if (
            operation === 'createMany' ||
            operation === 'updateMany' ||
            operation === 'deleteMany' ||
            operation === 'aggregate' ||
            operation === 'count' ||
            operation === 'groupBy'
          )
            return query(args)

          return query({
            ...args,
            include: {
              ...(args.include || {}),
              user: true
            }
          })
        }
      }
    }
  })
)

// Usage
function getPost (id: string) {
  return prisma.$extends(postExtention).post.findUnique({ where: { id } })
}

// NO user in PostOutput
type PostOutput = Awaited<ReturnType<typeof getPost>>

The issue I am facing is that the PostOutput type is just a basic Prisma.Post type, without the user relation included.

I have tried experimenting with different methods within the extension, like using findUnique instead of $allOperations, but it did not resolve the problem as expected.

The only workaround I discovered was adjusting a generic of the findUnique method:

prisma.$extends(postExtention).post.findUnique<{where: {id: string}, include: {user: boolean}}>({ where: { id } })

However, this approach is not ideal for me.

Can someone provide guidance on how I can modify the extension to ensure that it includes all the specified includes in the result type without having to add to the generic findUnique? Any help would be greatly appreciated.

Answer №1

import { PrismaClient } from "@prisma/client";
import cursorStream from "prisma-cursorstream";

declare global {
  var database: ReturnType<typeof initializeDatabase>;
}

if (!global.database) {
  global.database = initializeDatabase();
}

function initializeDatabase() {
  return new PrismaClient().$extends(cursorStream.default);
}

export default global.database;

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

Encountering difficulties setting a value to a key within an Object in Angular/Typescript

I'm currently working with Angular, and I've encountered an issue while trying to assign a value to a key within my model. Here's a snippet of my code: export class aa{ types: bb[]; } export interface bb{ name: string; age: str ...

Google plugin for the Vercel AI SDK

An error occurred: Type 'GoogleGenerativeAILanguageModel' is not compatible with type 'LanguageModelV1'. The 'doGenerate(...).then' methods are incompatible between these two types. const result = await streamUI({ model ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Enhancing Angular functionality with the addition of values to an array in a separate component

I need help with adding a value to an array in the 2nd component when a button in the 1st component is clicked. I am working on Angular 4. How can I achieve this? @Component({ selector: 'app-sibling', template: ` {{message}} <butt ...

Is a package I overlooked? The 'findOne' property is not found within the 'Schema<Document<any, {}>, Model<any, any>, undefined>'

I have taken over the responsibility of maintaining the websites at my company, and I am encountering the error message (Property 'findOne' does not exist on type 'Schema<Document<any, {}>, Model<any, any>, undefined>' ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Utilize the class type of a method parameter as the method type for another parameter

Here's a quick example illustrating my desired functionality. // Every time, the ACL class will have a different name such as "UsersACL", etc. export class EventsACL { test(): { read: true, write: true } { } } // This function acts ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Using the ngClass directive with a conditional statement: Select 'class1' if true, otherwise select 'class2'

i am currently experimenting with this piece of code <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <button [ngClass]="{'btn': showDirectiveContent === false ? 'btn btn-danger ...

Unexpected directory structure for internal npm module

Here is the package.json I use for building and pushing to an internal package registry: { "name": "@internal/my-project", "version": "0.0.0", "description": "Test package", "type&quo ...

Executing a method from a callback within the data() function in Vue 2.7 – Here's how!

This component uses a third-party module known as HelloWorld. This module has a prop called closeCallbacks, which is an array of callbacks that are triggered when the HelloWorld component is closed. Unfortunately, the functionality of the third-party comp ...

Exploring the Powers of Typescript Interfaces within Interfaces

Can you assist me with implementing an interface wrapped within a second interface? Here is the code snippet for the reducer: import { createSlice } from '@reduxjs/toolkit'; export interface IStep { id: number; label: string; value: string ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

Angular: Implementing default nested routes

I am currently facing a challenge with routing in my Angular application. I have set up a page within a router-output on the route /products. This page contains another router-output which will display one of two possible children routes (/products/profess ...

What is the reason behind TypeScript generics suppressing type errors?

Check out this TypeScript code snippet below. function expectInterface(args: { foo: string }): void {} function passthrough<T>(fields: T): T { return fields } expectInterface({ foo: 'bar', badKey: 'baz', // error }) expec ...

What is the best approach for managing errors within a shared observable in TypeScript?

I'm facing a unique issue and struggling to find someone who has encountered the same problem, which could imply that I am approaching it incorrectly. The http request I am making looks like this: return this.httpClient.post(`${this.route}/typegroups ...

Guide to displaying an input box depending on the selection made in a Mat-Select component

I am working on a mat-select component that offers two options: Individual Customers and Organizational Customers. When selecting Individual Customers, the dropdown should display three options: First Name, Last Name, and Customer Id. However, when choosin ...

Updating Radio Button Value in React Using TypeScript Event Handler

Whenever I try to save different values to the state, I encounter an issue where selecting female results in the male radio button being selected, and vice versa. Do you think it would be better to use a generic 'gender' variable in the state in ...

What causes the variation in typing behavior between specifying props directly on a component versus nesting them inside another prop?

Understanding the next component might be a bit tricky, so let's delve into it (Check playground): type Props<T> = { initValue: T, process: (value: T) => T } export const Input = <T,>({ initValue, process, }: Props<T>): ...

How to import a page from a different component in the Next.js application router

I am currently utilizing the Next.js app router and have organized my folders as follows: app/ ├─ /companies/ │ ├─ page.tsx ├─ /administrators/ │ ├─ page.tsx My objective is to import the companies/page.tsx component into the admini ...