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

Removing special characters when pasting into text box in Angular 2 or higher versions

To ensure that special characters are trimmed or removed when pasting into a textbox inside the TypeScript component file (with extension .ts), utilize a function within the TypeScript component itself. The modified text should be displayed in the textbox ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

Installation of Shadcn UI results in the disruption of Tailwind CSS

The Shadcn UI was performing well for a few weeks until yesterday. When I ran my NextJS app on my local host, the tailwind styling stopped working. To troubleshoot, I created a new NextJS 13 app in a different location, and everything worked fine - tailwin ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

Redirect Conditions in NextJS

One scenario: a blog with an extensive library of content cataloged by Google. Every piece is accessible via www.site.com/post1. When migrating this blog to NextJS, the posts are now located at www.site.com/blog/post1. Redirects using 301 have successful ...

Enhancing MUI themes by incorporating module augmentation for multiple typings

I am looking to create a repository with two directories, each using MUI and TypeScript. Both directories will have their own theme defined in one ThemeProvider per root. In the main index.tsx file in the root directory, I want to specify which component t ...

The TypeScript error "Issue with Type Assertion: 'This expression is not callable Type'...' has no call signatures" occurs when there is a missing semicolon

Here's a simplified version of our original code: const start: number = 10 const end: number = 20 (someElement as HTMLInputElement).setSelectionRange(start, end) We encountered an error with the 20, where a red squiggly line appeared indicating ...

What is the best way to display toasts in React server components?

I am currently working with Next.js 14 and utilizing the app router for my project. Within my application, I have two server components: A List page located at /products, which displays multiple products A Product Details page located at /products/{id}. ...

Issue with setting cookies in Node.js using Express

Recently I made the switch from regular JavaScript to TypeScript for my project. Everything seems to be functioning properly, except for session handling. This is the current setup of my project: Server.ts App.ts /db/mongo/MongoHandler.ts and some other ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

Do I still need to include getStaticPaths if I am already utilizing Link within the HTML in getStaticProps?

If I utilize getStaticProps to render a page as a table of contents, will NextJS automatically generate those pages statically by following the links and calling getStaticProps for each one? In this scenario, the file /page/[id].js represents a dynamic pa ...

Generate types based on properties of a nested interface dynamically

Consider the setup provided: enum FormGroups { customer = 'customer', address = 'address', } interface Customer { 'firstName': string; } interface Address { 'street': string; } interface SomeFormEvent { ...

Leveraging the power of react-hook-form in combination with the latest version 6 of @mui

When using MUI v5 date pickers, I utilized the following method to register the input with react-hook-form: <DatePicker ...date picker props renderInput={(params) => { return ( <TextField {...params} ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Opening a modal in Angular2+ when selecting an item from ngx-chips (tag-input)

I need to implement a functionality where clicking on a tag in a dropdown should trigger the opening of a modal window in my Angular application. Below is the code snippet related to this feature: <div class="force-to-the-bottom"> <tag-input [ ...

What are the steps for creating a TypeScript version of a custom CKEditor5 build?

Currently, I am in the process of creating a personalized version of CKEditor5. By following the guidelines provided in the official documentation, I successfully obtained ckeditor.js. My goal now is to produce a typescript file (ckeditor.ts or ckeditor.d ...

Classify the array types based on their indexes within the map

Is there a way to efficiently access elements in TypeScript using a map with the correct type? When attempting this, an error is thrown due to the type from the map being number | string type Tuple = [number, number, string]; const y: Tuple = [1, 2, &apos ...

Is it possible to utilize the router.query feature in a function within Next.js?

Running into a problem with my Next.js page. I'm attempting to utilize the request params in a function, but it keeps coming up as undefined. I've exhausted all my troubleshooting options. I already know that there's no need to include id i ...