Instructions for incorporating a TypeScript type into a Prisma model

I am trying to incorporate a Type Board into one of my Prisma models. However, I am encountering an error stating that "Type 'Board' is neither a built-in type, nor refers to another model, custom type, or enum." Can someone provide guidance on how to resolve this issue?

The structure of the Board type is as follows:

export type Board = {
  title: string;
  boardId?: string;
  id?: string;
  orgId: string;
  imageId: string;
  imageThumbUrl: string;
  imageFullUrl: string;
  imageUserName: string;
  imageLinkHTML: string;

  createdAt?: Date;
  updatedAt?: Date;
};

Within schema.prisma:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = "file:./data/dev.db"
  // url      = env("DATABASE_URL")
}


model List {
  id        String @id @default(uuid())
  title     String
  order     Int

  boardId   String
  board     Board @relation(fields: [boardId], references: [id], onDelete: Cascade)

  cards     Card[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([boardId])
}


Answer №1

Board data is housed in MockApi.io database.

As a result, Prisma is not aware of this connection.

If you want to retrieve a Board from a List, you'll need to implement something like the following code:

const list = await prisma.list.findUnique({ where: { id: listId } })
const board = await mockApiIoClient.board.findById(list.boardId) // psuedocode

You should also delete the following line from the schema file:

  board     Board @relation(fields: [boardId], references: [id], onDelete: Cascade)

This relationship cannot be managed by Prisma.

Your code must act as a liaison between the two systems. Therefore, it is not Prisma's responsibility to handle or provide the Board type.

Prisma generates TypeScript types from the database schema. Including a TypeScript type within the schema doesn't align logically.

Answer №2

In Prisma models, you are unable to directly reference a TypeScript type.

Models in Prisma can only refer to other models and enums that are defined within the same schema file.

If you want to incorporate Board information into your model, you have two options: define a model for Board and store the data in your database, or simply store the boardId in the List model and load the Board information through a resolver or an API call.

If you choose to store Board data with the Prisma method:

model List {
  id        String @id @default(uuid())
  title     String
  order     Int

  boardId   String
  board     Board @relation(fields: [boardId], references: [id], onDelete: Cascade)

  cards     Card[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([boardId])
}

model Board {
  id        String @id @default(uuid())
  title String
  //... Other things
  imageLinkHTML: string;

  createdAt?: Date;
  updatedAt?: Date;
}

Alternatively, you could opt for a simpler approach by creating a List model in the database and storing just the boardId:

model List {
  id        String @id @default(uuid())
  title     String
  order     Int

  boardId   String

  cards     Card[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([boardId])
}

When retrieving Board data from mockapi.io, extend the Prisma type with your custom Board type after running npx prisma generate:

import { List } from "@prisma/client";

// Fetch List from your database using Prisma
// Fetch Board from mockapi.io
// Combine List and Board data and Extend the List type with {board: Board}

// Inside of your getAllLists query:
const listData = await prisma.list.findUnique({ where: {
id: yourId }}) // Get one List
const boardData: Board = await fetch("mockapi.io api") // Retrieve Board data from mockapi.io

const newListData: List & {board: Board} = {...listData, board: boardData}

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

Developing an interface that utilizes the values of an enum as keys

Imagine having an enum called status export enum status { PENDING = 'pending', SUCCESS = 'success', FAIL = 'fail' } This enum is used in multiple places and should not be easily replaced. However, other developers migh ...

What causes TypeScript to malfunction when using spread in components?

What is the reason for typescript breaking when props are sent to a component using a spread statement? Here's an example code snippet: type SomeComponentProps = Readonly<{ someTitle: string }> const SomeComponent = ({ someTitle }: SomeCompo ...

What is the best way to retrieve the href attribute when working with cheerio?

Is there a way to retrieve the link using Cheerio in this code snippet? <div class="someClass"> <a href="someLink">Link</a> </div> I attempted to do so, but unfortunately it was unsuccessful. let link = $(&a ...

The overload functionality in Typescript interfaces is not functioning as intended

Here is a snippet of code I'm working with: class A { } class B { } class C { } interface Builder { build(paramOne: A): string; build(paramOne: B, paramTwo: C): number; } class Test implements Builder { build(a: A) { return &apo ...

Filtering a key-value pair from an array of objects using Typescript

I am working with an array of objects containing elements such as position, name, and weight. const elements = [{ position: 3, name: "Lithium", weight: 6.941, ... },{ position: 5, name: "Boron", weight: 10.811, ... }, { position: 6, name: "Carbon", weight: ...

Trying to determine the specific key of an object based on its value in TypeScript?

Looking to create a function that can retrieve the key for a given value. type Items<T> = Exclude<{ [P in keyof T]: [P, T[P]]; }[keyof T], undefined>[]; export const getKeyName = <T extends Record<PropertyKey, unknown>, V>( col ...

Cannot detect react-script in the "npm run build" command when setting up the create-next-app project

Here is the content of my package.json file: "name": "food-recipe", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": &quo ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

Seeking a solution to the useRef problem. Encountering difficulties with React Hook useRef functionality within a NextJS application

Whenever I refresh the page, the 'Ref' value is displayed as null. This causes the if condition blocks not to work. I attempted to modify the useRef values but could only set it to null. When I console log the myDivRef.current, it returns "Ref: ...

When navigating to '/blogs/', the index.js file in Next.js will automatically open

I'm working on a project using next.js and I want to ensure that when I visit 'localhost:3000/blogs/', it opens the index.js page. The index.js file is located in the 'blogs' folder of my project. Currently, it does open properly ...

Retrieving user input from one component to be used in another component in Angular

I'm currently working on a structure that involves a navbar component and a form component https://i.stack.imgur.com/nPRLO.png Initially, I have a navbar component where I load user data using an ID stored in the session. In the right side component ...

Error: Atom key duplication detected in Next.js framework

I am currently using recoil in my Next.js application. Whenever I run Next (whether in development or production), I encounter the following error message: Duplicate atom key "companyData". This is considered a FATAL ERROR in production. However, if it i ...

UI5 Tooling generated an error stating that "sap is not defined" after a self-contained build

Having successfully developed an application using SAPUI5 1.108, I encountered a setback when attempting to deploy it to a system running SAPUI5 version 1.71. The older version lacks certain features, causing the application to fail. In order to address th ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

What is the best way to save objects in the store (ngrx, ngxs) while preserving their methods functionality?

As I delve into the Redux pattern, I realize the importance of storing only plain objects in the Store. However, I find myself wanting to use more complex objects with methods like "hasParent", "isReadonly", and "isValid" in my application. While ngrx all ...

Can you please explain the purpose of the white space in the HTML code?

Currently, I am working on developing a mobile application, and as I start adding styles, I notice a mysterious blank space that seems to be appearing out of nowhere. Can anyone provide any insights or suggestions to help me troubleshoot this issue? https ...

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...