Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this:

async function getApiData() {
  const promises = [];
  for (let i = 0; i < PAGE_COUNT; i++) {
    const apiData = fetch(...);
  }
  const apiData = await Promise.all(promises);
  return apiData;
}

The result of this function is a promise that resolves to an array containing objects. Each object represents data retrieved from the API and follows a specific pattern, for example:

const exampleData = { name: 'john', lastName: 'doe' };

To define a type for this in Typescript, I can specify it within my getApiData function.

In addition, I am using Prisma with a schema structured as follows:

model Person {
  id  Int  @id @default(autoincrement())
  name String
  lastName String
}

While I can import typings specific to Prisma such as Person, there are variations in typing between this and what I use inside getApiData. This inconsistency generates an error when attempting to import and apply the Prisma typing:

Property 'id' is missing in type  but required in type `{name, lastName} but required in type 'Repository'

This situation prompts two main questions:

  1. How can I utilize the Prisma typing for shaping my API data? Creating a separate interface solely for accommodating one field difference feels cumbersome.
  2. From a typescript perspective, how can I insert any form of data into the Prisma database? Given that the id field is autogenerated upon insertion, does Prisma necessitate a specific typing for data insertion or can a more general approach be employed?

Answer №1

When facing this kind of issue, I usually rely on the typescript utility types like Partial or Omit.

import { Person } from '@prisma/client'

async function getApiData(): PartialPersonData[] | undefined {
  const promises = [];
  for (let i = 0; i < PAGE_COUNT; i++) {
    const apiData = fetch(...);
  }
  const apiData = await Promise.all(promises);
  return apiData;
}

// The choice between these two options depends on your specific goals and needs
type PartialPersonData = Partial<Person> // partial === any of Person fields are valid
type OmitIdPersonData = Omit<Person, 'id'> // omit === all Person fields as is omitting id

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

What is the proper way to access the global `angular` variable in Angular and TypeScript when using AngularJS?

I'm currently integrating an Angular 4 component into a large monolithic AngularJS application. The challenge I face lies in the restrictions of the AngularJS project's build system, which limits me to only modifying the project's index.html ...

Having trouble importing XML data from an external file with jQuery

Attempting to import external XML with the code below is proving unsuccessful $( document ).load( "data.xml", function( response, status, xhr ) { console.log( xhr.status + " " + xhr.statusText ); }); Both data.xml and js files are in the ...

Express server encountering difficulties locating requested file for download

I encountered a curious issue while working with my express server: I am attempting to download a file from a dynamically created folder. Below is the code snippet: var folder = id.toString() var file = [projectRoot,"/app/temp/",folder, "/regist ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

Turning my dual button navigation into tabs to display distinct HTML pages beneath a designated header

body{ background:url(background.jpg); background-size: cover; } h1{ font-family: 'Dancing Script', cursive; font-size: 5em; color: white; text-align: center; margin-top: 25px; margin-bottom: 20px; } h2{ font-size: 18px; color: white; text-align ...

Can JSON.parse be used on only a portion of an object in JavaScript?

Currently, I am facing an issue with a lengthy JSON file that I am fetching from a URL using https.request. Upon attempting to parse the string with JSON.parse, I encounter an "Unexpected end of JSON input" error. It appears that there is a limit to the ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Begin the React counter with a starting value of two

Recently, I set up a new React application using the create-react-app command and ran a test with a render counter. Here is the code snippet: import React, { useState } from "react"; let render = 0; export default function App() { const [cou ...

Vue.js encountered an uncaught TypeError while trying to execute the 'drawImage' function

I am facing an issue with my vue.js application where I can successfully apply a filter to a photo, but I am unable to post it. The error message I am encountering is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingCon ...

Submit a form utilizing jQuery's ajax function

I am currently facing an issue with my use of the $.ajax post method. My intention is to submit form data on the current page itself, but somehow the script is redirecting to the action page. If anyone could pinpoint what's causing this redirection ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

Troubleshoot the Error: EEXIST - Directory already exists at 'C:UsersPhantom' while setting up a React application[RESOLVE]

I'm trying to set up react and start my first project, but I encountered an issue during the installation process. How can I resolve this? Error: EEXIST: file already exists, mkdir 'C:\Users\Phantom' TypeError: Cannot read propert ...

Operations such as OR and AND can be used within a JSONB array to filter

Imagine having a table named temp (jsondata jsonb) In Postgres, there is a method to query a jsonb array object for containment check using SELECT jsondata FROM temp WHERE (jsondata->'properties'->'home') ? 'football&apo ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...

What is the best way to integrate a loop in JavaScript to retrieve values?

<script> var data={ Data: { name: 'aaaa', number: '0003' }, values: { val: '-20.00', rate: '22047' }, user: [ '6|1|5', '10|1|15' ] }; ...

How to Eliminate Image Flickering While Loading in a React Component

Currently, I am developing a React component that takes an imageUrl and displays it on a canvas with a deliberate 2-second delay to mimic loading time for larger images. However, I have encountered a problem: when the imageUrl changes in the parent compone ...

React Three Fiber encountered an unexpected JSON token 'c' at position 3

I am encountering an issue while trying to load a .glb file using react-three-fiber. The error I'm receiving is as follows: Error Unexpected token c in JSON at position 3 I can't seem to figure out what mistake I am making - it seems that the co ...

What is the reason behind Ember choosing to install everything as devDependencies rather than regular dependencies?

Ember CLI applications have a package.json file that lists everything as dev dependencies, including packages needed in the app's production version such as ember and ember-data. If you would like to see an example, check out this sample: https://git ...