Prisma comes equipped with a vast array of parameters to be included

I'm in the process of transitioning from TypeORM to Prisma.

TypeORM

const user = await getUser("123", ["car", "car.wheels"])
static async getUser(
    userId: string,
    relations: string[]
  ) {
  return await UserEntity.findOne(
    {
      where: {
               id: userId
             },
      relations: relations
    }
  )
}

When using Prisma, the equivalent of relations in TypeORM is handled with the include function. How can I pass a variable relation into a Prisma function?

Answer №1

Here is the current method we use: you must convert your relations from a string array to a dictionary structure.

// Initialize variable with default includes
    const userInclusion = <Prisma.UserEntityInclude >{ include1: false, include2: false };
    // Map string relations to dictionary
    relations?.forEach(value =>{
     userInclusion[value as keyof typeof userInclusion] = true;
    })
  let args: Prisma.UserEntityFindUniqueArgs = { where: { id: userId } };
  if (relations.length > 0) {
            args = {
                ...args,
                include: userInclusion
            };
        }
     }
  const user = await UserEntity.findOne(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

Tips for utilizing automatic type detection in TypeScript when employing the '==' operator

When using '==' to compare a string and number for equality, const a = '1234'; const b = 1234; // The condition will always return 'false' due to the mismatched types of 'string' and 'number'. const c = a = ...

How can Angular developers properly implement token refreshing in their applications?

Recently, I've been struggling with implementing a logic in my code. I have a specific requirement: Whenever there is a signed request (signed - means it has a JWT token for authenticated users) made to the API backend, the API backend may respond w ...

Unable to retrieve dynamically generated object property from an array in AngularJS 2+

Here is an example of an items array: this.itemList = [ { id: 1, name: 'a', address: 'as dasf a' }, { id: 2, name: 'b', address: 'as dasf a' }, { id: 3, name: 'c', address: 'as dasf a' } ]; ...

Image paths becoming unresponsive following package upgrades

My Angular2 application was originally built using angular-cli (v 1.0.0) and webpack2. Within a component, I had the ability to reference an image like so: <div class="country-flag"> <img [src]="src/assets/flags/32/jp.png" [width]="flagIconSiz ...

Is there a way to customize the size of the image using dangerouslySetInnerHTML in React?

While utilizing dangerouslySetInnerHTML to display article HTML in a React component, I encountered an issue where an image from the HTML content exceeded the page width. Is there a way to resize the image within dangerouslySetInnerHTML? Or can the maxim ...

Tips for preventing the creation of .d.ts.map files while using tsc to exclusively generate declaration files

When I create a build using tsup, I encounter numerous errors with the dts option. The official tsup documentation also mentions that typescript declarations generated by tools other than tsc may not be perfect. As a result, I have decided to use tsc for ...

The extend keyword in TypeScript causing issues with type inference

Why is TypeScript showing an error in the code below? type A = { kind: "a" } type B = { kind: "b" } const a = (a: A): void => undefined const b = (b: B): void => undefined const c = <C extends A | B>(c: C): void => (c.kind == "a" ? a(c) : ...

Angular is throwing an error stating that the argument type 'typeof MsalService' cannot be assigned to the parameter type 'MsalService'

I'm currently facing a challenge in creating an instance of a class in TypeScript/Angular. Within my project, there is a specific scenario where I need to call a method from an exported function that is located within another class in TypeScript. co ...

What's the most effective way to constrain focus within a Modal Component?

Currently working on a library of components in Angular 8, one of the components being a modal that displays a window dialog. The goal is to prevent focus from moving outside the modal so that users can only focus on the buttons inside by using the Tab but ...

The React useState hook is not functioning as anticipated

I am having an issue with my useState hook that manages the state of selected checkboxes. The selected checkboxes should be instantly displayed in the UI within my filter, but currently they are only shown when the filter component is closed and reopened. ...

Issue with Framer-motion animation not triggering on exit

Here is a link to the code sandbox In this gif demonstration, it's evident that the notifications are not triggering the exit animation when removed from the DOM (usually after 6 seconds). Why is this happening? I've followed all the suggestion ...

The mistake occurs when attempting to access a class property generated by a class constructor, resulting in a type error due to reading properties of

I'm having trouble building an Express API in TypeScript using Node.js. I am new to Express and I have been learning Node, JavaScript, and TypeScript since 2022, so I apologize if the question is not too complex. The issue I'm facing is trying to ...

What is the best way to set up the base href in Angular 2 while incorporating Electron?

In order to prevent Angular 2 from throwing exceptions, I must set either <base> in the HTML or use APP_BASE_HREF during bootstrap. However, if I do so, Electron throws exceptions in browser_adapter.ts when attempting to match a route, as it thinks i ...

Obtain varied results from the Knockout module

In my application, I am utilizing Knockout and Typescript. One of the classes in my code is as follows: class Address { State :string; ZIP: string; Street: string; } I want to create a component that will handle the updating of an object of ...

Unable to display grid items in React material-ui grid list

export interface FlatsGridProps { flats: IClusterFlats[]; } export const FlatsGrid: React.StatelessComponent<FlatsGridProps> = (props: FlatsGridProps) => { if (props.flats.length === 0) { return (<div> empty </di ...

When utilizing custom ngDoBootstrap and createCustomElement in Angular, the router fails to recognize the URL being used

WHEN I implement a custom ngDoBootstrap function instead of the default bootstrap: [AppComponent] like shown below: @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, HelloComponent ], exports: ...

Explore the sibling data of a specific node with the power of Firebase Cloud Functions

I am currently working with Firebase real-time database and Firebase cloud functions (using Typescript). Below is the structure of my database nodes: Orders Node: orders |- {Push ID} |--billing_id |--orders_id Shippings Node: shippings |- {Push I ...

Encountering challenges while developing a react application with TypeScript

An error has occurred: G:\ReactProj\my-app\node_modules\react-scripts\scripts\utils\verifyTypeScriptSetup.js:239 appTsConfig.compilerOptions[option] = value; ^ TypeError: Cannot assign to read only property 'jsx&apo ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

What is the best way to observe a function and provide a simulated result from within a different function using jasmine?

Query: How can I access the reference of getWindowSize within getBreakpoint() to perform spying on it? Additionally, how can I use callFake to return mock data? media-query.ts export const widthBasedBreakpoints: Array<number> = [ 576, 768, 99 ...