Is it possible to utilize a partial entity for saving with TypeORM?

My current table structure looks like this:

--changeset 0004-order:ccushing
create table if not exists "order"."order"
(
    id          uuid primary key                                          not null default uuid_generate_v4(),
    state       uuid references "order".order_status
);

--changeset 0004-h0-table-order_event_type:ccushing
create table if not exists "order".order_event_type
(
    id          uuid primary key                                          not null default uuid_generate_v4(),
    key         text unique                                               not null
);

--changeset 0004-h1-table-order_event:ccushing
create table if not exists "order".order_event
(
    id          uuid primary key                                          not null default uuid_generate_v4(),
    order_id    uuid                                                      not null references "order"."order" (id),
    event_type  uuid                                                      not null references "order".order_event_type (id),
    event       jsonb                                                     not null,
    unique (order_id, event),
    unique (order_id, event_type)
);

I am looking to create a new OrderEventEntity, but I want to avoid loading the Order object since I only need the order_id in the event.

@Entity('order.order_event')
export default class OrderEventEntity implements Identifiable<string> {
  @PrimaryGeneratedColumn({ type: 'uuid' })
  readonly id!: string;

  @ManyToOne(() => OrderEventTypeEntity, ({ event }) => event)
  readonly eventType!: string;

  @ManyToOne(() => OrderEntity, ({ events }) => events)
  readonly order!: OrderEntity;
}

Is it possible for me to achieve this by creating a new OrderEventEntity and saving it without loading the entire Order?

const order = new Order({ id: 1234 })
repo.save( new OrderEventEntity({ order: order, ... })

Or is there another way, maybe with some partial load, that allows me to maintain the OneToMany relationship while only having access to the order id?

Answer №1

Consider the following two options:

  1. Add a order_id column to your OrderEventEntity
@Entity('order.order_event')
export default class OrderEventEntity implements Identifiable<string> {
  @PrimaryGeneratedColumn({ type: 'uuid' })
  readonly id!: string;

  @ManyToOne(() => OrderEventTypeEntity, ({ event }) => event)
  readonly eventType!: string;

  @Column()
  order_id: string;

  @ManyToOne(() => OrderEntity, ({ events }) => events)
  readonly order!: OrderEntity;
}
  1. Alternatively, consider using force cast tricky
const order = { id: 1234 } as Order;
repo.save( new OrderEventEntity({ order: order, ... })

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 best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

Add a class to a button in an Angular btn-group if a specific string is found within an

I am currently working on a project where I have multiple buttons that need to toggle an active class when selected in order to change their color. Below is a snippet of what I have: In the array called 'selected', I have: this.selected = [&ap ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Instructions on how to reset or restore to the initial spawn point

I am currently attempting to simulate a spawn process using the mock-spawn module. However, I am encountering issues with restoring the mock after running subsequent tests. I attempted to use mySpawn.resotre(), but it appears that this function does not e ...

Using next.js with GraphQL resulted in the following error: "Invariant Violation: Unable to locate the "client" in the context or passed in as an option..."

I've searched extensively online, but I can't find a solution to my problem. Here is the error message I'm encountering: Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Craft a unique typings file tailored to your needs

After recently creating my first published npm package named "Foo", I encountered some difficulties while trying to consume it in a TypeScript project. The tutorials on how to declare modules with custom typings were not clear enough for me. Here are the k ...

"Once the queryParams have been updated, the ActivatedRoute.queryParams event is triggered once

Within my Angular component, I am making an API call by passing a hash string extracted from the current query parameters. Upon receiving the API result, a new hash is also obtained and set as the new hash query parameter. Subsequently, the next API call w ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

What is the best way to access a class's private static property in order to utilize it for testing purposes?

Hello, I am currently a beginner in TypeScript and unit testing, so this inquiry may seem elementary to those more experienced. I am attempting to perform unit testing on the code provided below using sinon. Specifically, I am interested in testing whethe ...

Struggling to make type definitions work in react-hook-form 7

Upon defining the types of my form fields, I encountered an issue where each field seems to take on all three different types. This is puzzling as I have specified 3 distinct types for my 3 different fields. What could be causing this confusion? https://i ...

Troubleshooting Vue and Typescript: Understanding why my computed property is not refreshing the view

I'm struggling to understand why my computed property isn't updating the view as expected. The computed property is meant to calculate the total price of my items by combining their individual prices, but it's only showing me the initial pri ...

Error TS2322: The specified type Login cannot be assigned to the given type

I've been facing an issue while working on my app in react native. The error message I keep encountering is as follows: TS2322: Type 'typeof Login' is not assignable to type ScreenComponentType<ParamListBase, "Login"> | undefined Type ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

Deactivate the chosen tab by clicking the Mat-Tab button

I was trying to implement a way to disable the selected mat-tab and its elements when a button is clicked, //HTML <mat-tab-group #tabGroup> <mat-tab *ngFor="let subject of subjects" [label]="subject.name"> {{ subject.name }} ...

Tips for effectively utilizing URLSearchParams in Angular 5 HttpClient's "get" function

When working with Angular 4.2, I used the Http service and made use of the get method by passing in a URLSearchParams object as the search parameter: this.http.get(url, {headers: this.setHeaders(), search: params}) Now I am looking to upgrade to Angular ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Developing a Generic API Invocation Function

I'm currently working on a function that has the capability to call multiple APIs while providing strong typing for each parameter: api - which represents the name of the API, route - the specific route within the 'api', and params - a JSON ...

What are the steps for incorporating the AAD B2C functionality into an Angular2 application with TypeScript?

I recently built a web application using Angular2 and TypeScript, but now one of my clients wants to integrate Azure B2C for customer login instead of OAuth. I followed a simple example on how to implement Azure B2C in a .NET Web app through the link provi ...