Creating a TypeORM blog with PostgreSQL-like constraints

For my upcoming blog project, I am implementing a feature where users can like comments or posts using TypeORM with PostgreSQL. Below is the entity structure for likes:

@Entity()
@Unique(["user", "post", "comment"])
export default class Like {
  @PrimaryGeneratedColumn()
  id: number;

  // @Column()
  // likeCount: number;

  @ManyToOne(() => User, (user) => user.likes, { nullable: false })
  user: User;

  @ManyToOne(() => Post, (post) => post.likes)
  post: Post;

  @ManyToOne(() => Comment, (comment) => comment.likes)
  comment: Comment;

I am facing an issue where I need to prevent a user from liking a comment/post more than once. The unique constraints in the code above are not achieving this. Should I consider creating separate tables for liking a post and liking a comment? Also, how can I track the total number of likes for each comment/post?

The current unique constraint setup is ineffective and needs an alternative approach.

Answer №1

To ensure that a user can like multiple posts or comments, you can implement a unique constraint on either the user_id and comment_id columns, or the user_id and post_id columns. This approach will enable users to engage with various posts and comments without restrictions. Additionally, by utilizing foreign keys to establish connections between likes and posts/comments, you can guarantee the existence of relevant data in the database.

Answer №2

Include columns userId, postId, commentId and create a unique index for them.

Example below:

@Entity()
@Unique(["userId", "postId", "commentId"])
export default class Like {
  @PrimaryGeneratedColumn()
  id: number;

  // @Column()
  // likeCount: number;

  @Column()
  userId: number;

  @Column()
  postId: number;

  @Column()
  commentId: number;

  @ManyToOne(() => User, (user) => user.likes, { nullable: false })
  user: User;

  @ManyToOne(() => Post, (post) => post.likes)
  post: Post;

  @ManyToOne(() => Comment, (comment) => comment.likes)
  comment: Comment;

This ensures that one User can only like one Comment per Post.

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 approach to create a regex pattern that will identify variables enclosed in brackets across single and multiple lines?

In my Typescript project, I am working on matching all environment variables that are de-structured from process.env. This includes de-structuring on both single and multiple lines. Consider the following examples in TS code that involve de-structuring fr ...

Injecting a useFactory provider in Angular is a common practice

I manage a factory provider service that selects a service based on a flag. Everything works fine when I need a debug students service, but when I set the flag to false, the application throws an ERROR TypeError: serverService.fetchData is not a function. ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

Having trouble setting the default value of a select element with 'selected' in Angular's bootstrap?

Click here I've been facing some difficulties in making the 'selected' tag work to pre-select my default select value. It seems like it might be related to the unique pipe I'm using and how Angular handles it. I have experimented with ...

Sharing markdown content between two Vue.js components

I have a markdown editor in View A which is displaying the result in the current View. My goal is to share this result with another page, View B. In View A, there is a button that allows the user to share the markdown result with View B. I am using a texta ...

How to enhance an input field: incorporating unique buttons within

Currently, I have an input that is supposed to resemble the following: https://i.sstatic.net/pgPgk.png To achieve this look, I've implemented the code below using Styled-Components and Font-Awesome icons: <Thing> 1 <i className="fa fa ...

Ensuring the proper export of global.d.ts in an npm package

I'm looking to release a typescript npm package with embedded types, and my file structure is set up like so dist/ [...see below] src/ global.d.ts index.ts otherfile.ts test/ examples/ To illustrate, the global.d.ts file contains typings ...

The router smoothly transitions to a new URL without requiring a change in the

One of the components in my project involves using a spreadsheet page with react-spreadsheet npm library: import Link from "next/link" import { useState } from "react" import { Spreadsheet as Sheet } from "react-spreadsheet" ...

The Angular BehaviorSubject observable is returning a null value

I am experiencing an issue where I pass data through components using behavior subject. However, when I try to retrieve it with subscribe, it shows null even though the service returns a real value. To reproduce the issue, you can check out the code here: ...

Form with checkboxes in a Next.js and Typescript application

I am currently working on a project using Next.js and Typescript. I have implemented a form in this project, which is my first experience with Typescript and checkbox types. However, I am encountering difficulties in retrieving all checkbox values, adding ...

Exploring the intricacies of pattern matching with JavaScript visualization

I am currently working on improving my pattern matching function by creating a visualizer for it. To achieve this, I need to slow down the execution of each comparison. My approach involves declaring the i and j variables outside of the function so that I ...

Fastify fails to register middleware when using the decorate method

In the process of crafting middleware for scrutinizing the JWT transmitted during route invocations, I meticulously adhered to the guidelines stipulated in the JWT middleware manual and ported the code to TypeScript from vanilla JS. Regrettably, an anomaly ...

Challenge: Visual Studio 2015 MVC6 and Angular 2 compilation issue - Promise name not found

Initially, I've made sure to review the following sources: Issue 7052 in Angular's GitHub Issue 4902 in Angular's GitHub Typescript: Cannot find 'Promise' using ECMAScript 6 How to utilize ES6 Promises with Typescript? Visual ...

What is the proper way to structure a React component class without any props?

When working with Typescript in a React project, the top level component typically does not receive any props. What is the recommended approach for typing this scenario? I have been using the following coding structure as a template, but I am curious if t ...

Unable to send back transaction response from callback to the user

Our payment processing system utilizes the authorize.net Node SDK. We have implemented a Firebase callable function to manage payment requests but are encountering difficulties in retrieving the transaction response. The issue lies within the following co ...

Create a system for detecting changes in simple input elements and triggering a function to update the final result

There are a maximum of 12 inputs that represent the same entities or objects but with varying integer values. These values directly impact the final result displayed to the user. Whenever any of the input values change, a function needs to be triggered to ...

Deactivate user input depending on a certain requirement

Greetings everyone, I am currently working with the following code snippet: <table class="details-table" *ngIf="peop && peopMetadata"> <tr *ngFor="let attribute of peopMetadata.Attributes"> <td class="details-property"&g ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

The template displays an <object Object>, yet the observable async pipe functions without any errors

I am working with an observable of todos that have properties such as id, title, and completeness. TodosComponent/index.ts import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core'; import {Todo, ITodo} from &a ...

TypeScript was looking for 'never' but found an intersection instead

Can someone help me understand why a conflicting type intersection did not produce a type of never? What am I overlooking? type A = {value: string} type B = {value: number} type D = A & B type E<T> = T extends never ? 'never' : ' ...