Obtain a compilation of responses to comments

I have some thoughts on the article. However, I decided to enhance the commenting feature by allowing replies to comments.

Comment entity:

@Entity()
export class Comment {
  @PrimaryColumn()
  id: string;

  @Column({ type: 'varchar', length: 50 })
  content: string;

  @Column()
  authorId: string;

  @Column()
  entityId: string;

  @CreateDateColumn()
  createdAt: Date;

  @Column('text', { nullable: true })
  replyId?: string;

  @Column({ type: 'enum', enum: CommentTypeEnum })
  type: CommentTypeEnum;
}

Here are some specifics: When creating a reply to a comment, I capture the parent comment's id (the one being replied to) and store it in the replyId field. The parent comment can have NULL or another id as well; essentially, a new comment contains its parent's id.

[
  {
    "id": "dee96b97-cd45-4a09-a27d-985617cc5a16",
    "content": "comment",
    "authorId": "a30bfd0b-0519-4b4f-bbc5-04178f8af782",
    "entityId": "91e22cb7-cb42-49a3-a5e7-8d111111",
    "createdAt": "2021-10-04T08:43:35.204Z",
    "replyId": "cab2d3fd-7fba-4d02-a911-538246d92cfd",
    "type": "COMMENT_TYPE"
  },
  ...
]

Method used to fetch all records for a specific entity:

@Get('/:entityId/comments')
  async getAll(@Param('entityId') entityId: string): Promise<CommentDto[]> {
    const comments = await this.commentRepository.find({ where: { entityId: entityId }, order: { id: 'DESC' } });
    return comments.map(it => ({
      id: it.id,
      content: it.content,
      authorId: it.authorId,
      entityId: it.entityId,
      createdAt: it.createdAt,
      replyId: it.replyId || null,
      type: it.type,
    }));
  }

DTO:

export class CommentDto {
  id: string;
  content: string;
  authorId: string;
  entityId: string;
  createdAt: Date;
  replyId?: string;
  type: CommentTypeEnum;
}

To retrieve records like the example below:

[
  {
    "id": "4f7b2bb3-b224-45d9-8093-9c0de7514bd4",
    "content": "comment",
    "authorId": "a30bfd0b-0519-4b4f-bbc5-04178f8af782",
    "entityId": "91e22cb7-cb42-49a3-a5e7-8d111111",
    "createdAt": "2021-10-04T08:43:04.391Z",
    "replyId": [
        {
          "id": "cab2d3fd-7fba-4d02-a911-538246d92cfd",
          "content": "comment",
          "authorId": "a30bfd0b-0519-4b4f-bbc5-04178f8af782",
          "entityId": "91e22cb7-cb42-49a3-a5e7-8d111111",
          "createdAt": "2021-10-04T08:43:22.663Z",
          "replyId": [...],
          "type": "COMMENT_TYPE"
        },
        ...
      ],
    "type": "COMMENT_TYPE"
  }
]

Thank you in advance for your response

Answer №1

Explore the concept of "many to one" relationships in TypeOrm by referring to this resource: ().

Essentially, you should implement the following:

@ManyToOne(type => Comment)
@JoinColumn({ name: 'replyId' })
reply?: Comment | null;

@Column({ nullable: true })
@Index()
replyId: string | null;

Subsequently, utilize the following code snippet:

await this.commentRepository.find({
    where: { entityId: entityId },
    relations: ['reply'],
    order: { id: 'DESC' }
});

A word of caution, typeorm does not automatically retrieve all related data to an unlimited depth. relations: ['reply'] will provide information up to one level. If you need more depth, increase the nesting with additional relation keys like

['reply', 'reply.reply', 'reply.reply.reply']
, however, performance may decrease as the depth increases.

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

Inquiring about the specifics of pointer behavior

Consider having an array int b[] = {2, 3, 4}; What allows a pointer to the first element &b[0] to point to elements of the array or values in general, while the pointer &b itself cannot? cout << (&b[0])[1]; // 3 cout << (&b)[0 ...

challenging analysis using PHP

I've been working on analyzing the distribution of items in a game on a monthly basis. Here is an example table: Date itemname quantity avg. price Mar-2012 x 10 3.45 Mar-2012 y 12 4.66 Apr-2012 x 23 4.56 ...

Attempting to intercept a 401 error in an HTTP interceptor, I aim to refresh my session and then retry the initial request

My goal is to intercept responses returning from the /api, catching them if they are a 401 error, executing a refresh session action, and then retrying the original HTTP call again (while also preventing it from infinitely looping if another 401 error occu ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

Customizing form validation in React using Zod resolver for optional fields

I am currently working on creating a form using React-hook-form and zod resolver. My goal is to have all fields be optional, yet still required despite being marked as optional in the zod schema: const schema = z.object({ name: z.string().min(3).max(50 ...

Exploring the Array: Evaluating Zero in Every Position

I'm currently developing a Java game using Swing. In order to manage the game world, I am utilizing a 2D Array. However, I have encountered an issue with my text command system. Whenever it attempts to access a variable from the array, it consistently ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Retrieve the list of users playing certain games using the start.gg API

Is there a way to retrieve all users from Smash Ultimate using the start.gg API? I couldn't find any information about fetching all users, only details about tournaments or specific player sets. You can access the API here: Thank you in advance for ...

What is the best way to transform a Python list containing string elements without quotes into a formatted list?

Let's take a look at this list: list1 = [home , school, ground, field] The elements of the list are strings without quotes, making it an invalid list. Is there a way to convert this into a proper list using Python? The corrected version should be ...

Error: Attempting to delete a dynamically allocated array with an invalid pointer is causing a

Currently experimenting with pointers arithmetics and puzzled by the "free(): invalid pointer" error that arises when executing the final line containing delete [] arr;. I've noticed that this code runs smoothly when using C4Droid on my Android phone ...

Safe way to implement map and spread operator in your codebase

Is there a workaround for this issue? I am working with an interface, IFoo, and an array of data IFoo[]. My goal is to map this data and modify a single property. It should look something like this const mapper = (foos: IFoo[]): IFoo[] => { return foo ...

Generating dynamic menu options for a <select> element from an array using React's createElement() method

I have a question about dynamically populating options from an array or JSON. Currently, I am generating the options manually with the following code: return React.createElement("select", {}, React.createElement("option", {value: "A"}, "Option ...

Show information from a chart depending on the data retrieved from an API request

I am currently learning how to use React and incorporating a store into my application. My goal is to have 2 components, one main component and a child component. The main component will make an API call to retrieve data, which will then be passed to the c ...

Tips for identifying functions that return objects

I'm trying to figure out how to extract the type from the object returned by a specific function. The function returns an object with two keys: X and Y. In my getItem function, I only need the type of X. I don't want to use the interface Selecte ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

Add a new class to the Custom Repository

In my project, I have developed a class called S3Service that handles the task of uploading and deleting objects (such as images) from S3. Since I intend to utilize this "service" in various modules, I decided to create a custom module named UtilsModule wh ...

Creating a nested array from an object array using PHP

I am trying to reformat an array that looks like this: array(4) { [0]=> object(stdClass)#19 (3) { ["column_name"]=> "article_id" ["caption"]=> "Article Id" ["input_type"]=> "Number" } [1]=> object(stdClass)#21 (3) { ["column_ ...

Angular 2: Issue with Observable subscription not correctly retrieving data

When attempting to retrieve an array of objects from the ngrx Store and assign it to an array using the subscribe option provided by Observables in Angular 2, an issue arises when trying to access the contents of the array. Below is a snippet of the code: ...

Exploring the differences between Angular's @Input and @Output directives and utilizing Injectable Services

When considering the differences between @Input/@Output in parent and child components versus using services that are instantiated only once with dependency injection (@Injectable()), I find myself questioning whether there are any distinctions beyond the ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...