Receive a list of articles based on your subscription status

I am looking to create a filter that can retrieve subscription records

Entity 'Subscription'

export class Subscription {
  @PrimaryColumn()
  id: string;
  @Column('uuid')
  userId: string;
  @Column('uuid')
  targetUserId: string;
  @CreateDateColumn()
  createdAt: Date;
}

Filter

applyFilter(query: QueryArticle, qb: SelectQueryBuilder<Article>, userId?: string) {
    if (query.filter) {
      switch (query.filter) {
        ....
        case 'subscriptions':
          qb.select(
            `article.authorId WHERE targetUserId IN (SELECT targetUserId FROM Subscription WHERE userId=${userId})`,
          );
          break;
      }
    }
    return qb;
  }

SQL code

Select * FROM article WHERE authorId=targetUserId IN (SELECT targetUserId FROM Subscription WHERE userId=userId)

Error

syntax error at or near "f5779e5" +3974ms
QueryFailedError: syntax error at or near "f5779e5"

Is there a way to fetch all posts from users followed by another user using TypeORM?

Thank you in advance for your help!

Answer №1

STOP WHAT YOU'RE DOING IMMEDIATELY. Engaging in this behavior could result in a critical SQL Injection vulnerability. Instead of manually executing queries, consider using the secure method manager.query:

const output = manager.query('article."authorId" WHERE "targetUserId" IN (SELECT "targetUserId" FROM Subscription WHERE "userId" = :userId)',
  { userId: userId }
);

Take note of the parameter object passed as the second argument containing parameters referenced by keys like :userId. Avoid using template strings for SQL queries to prevent vulnerabilities.

If you prefer to utilize QueryBuilder, your code will have a slightly different structure (more details available here)

const output = articleRepo.createQueryBuilder('article')
  .select('article.authorId')
  .where('article."authorId" IN (SELECT "targetUserId" FROM subscription WHERE "userId" = :userId)',
    { userId: userId }
  )
  .getRawMany(); // To retrieve entities instead of raw results, use .getMany()

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

A tip for transferring the value of a binding variable to a method within the template when the button is clicked

I am currently exploring the concept of binding between parent and child components using @Input, @Output, and EventEmitter decorators. This is demonstrated in the HTML snippet below: <h1 appItemDetails [item]="currentItem">{{currentItem}}& ...

ngif directive does not function properly when subscribe is utilized in ngOnInit

this is the unique component code import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; //import { Item } from '../item/item.model'; import { CartItem } from './cart-item.model'; imp ...

Capture all HTTP requests made by Angular2

I'm trying to find a way to intercept and modify all HTTP requests made by Angular by adding custom headers. In previous releases prior to angular2 RC5, this was achieved by extending the BaseRequestOptions like this: class MyOptions extends BaseRequ ...

Filtering an array of objects based on another array of objects in Angular2 through the use of pipes

I'm having trouble understanding how to use the angular pipe to filter an array of objects based on another array of objects. Currently, I have a pipe that filters based on a single argument. I am working with two arrays, array1 and array2, both cont ...

What is the best way to create props that can accommodate three distinct types of functions in TypeScript?

I have been encountering a problem with the last function in my props interface that is supposed to support 3 different types of functions throughout the application. Despite adding parentheses as requested, I am still facing errors. // In Parent compon ...

Passing variables from a template to TypeScript using ngFor

Need help passing a variable from a template to typescript using *ngFor loop. Currently, my code looks like this: <select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple> <opt ...

operating efficiently even when producing an incorrect output type

Exploring Typescript for the first time on Codepen.io has left me puzzled. I'm unsure why, despite defining the function signature and return type with an interface, I am able to return a different type without encountering any errors. Is there somet ...

Ways to display the access path of a SQL query

Are there any methods in MySQL to display the access path of a query? I have been searching online for a while now with no luck...any suggestions? ...

The element does not have a property named 'className' in the object type '{ props: ReactNode; }'

I am currently in the process of converting a Next.js project from JavaScript to TypeScript, and I encountered an issue: Property 'className' does not exist on type '{ props: ReactNode; }'. In JavaScript, I could access className from p ...

Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code: res= this.CS.postcompetenze(this.comp) Th ...

Module 'xlsx' cannot be located

I encountered this issue while building with Jenkins on the server, but it works fine on my local machine without any errors: 15:07:39 "", 15:07:39 "", 15:07:39 "ERROR in src/services/excel.service.ts:2:23 - error TS2307: Cannot find module 'xlsx&apos ...

Extract the varchar column based on the values from another column in a pivot operation

I need help with transforming the data from the table below: object_key created_by updated_on updated_by attr_type value_name value_num 1 user1 3/21/2021 user1 name John 1 user4 4/15/2021 user3 mobile_number 4567865 1 user3 4/21/2021 user2 of ...

The ListBuckets command in AWS S3 provides a comprehensive list of all available

I'm currently working on a TypeScript application that interacts with an AWS S3 bucket. The issue I'm facing is that my current credentials only allow me to read and write data to specific buckets, not all of them. For example: ListBuckets retu ...

Receiving an error when attempting to inject the Router in a component constructor without using the elvis operator

Upon launching my app, I desire the route /home to be automatically displayed. Unfortunately, the Angular 2 version I am utilizing does not support the "useAsDefault: true" property in route definitions. To address this issue, I considered implementing th ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

Extracting data based on date ranges from Various Tables in MySQL

My query is to retrieve users who have not performed action_id 110 within a specific date range Date Range From - 2014-04-01 To - 2014-08-08 tbl_user userid name email db_add_date 1 steve <a href="/cdn-cgi/l/email-p ...

Are Snowflake's `not in` and `in` clauses yielding identical outcomes?

I currently have a dilemma with my order ids table. I am extracting data from a source system containing order ids and need to pinpoint which ones are absent from my table. To address this issue, I have devised two separate queries. Exclusion Query Identi ...

Remove a particular row from a table with PHP

I have created a visually appealing table to showcase data in the following manner: ID name Delete 1 abc Delete 2 def Delete The coding snippet used for the aforementioned display is as follows: <?php $con=mysqli_connect("abc" ...

What is the best way to modify the underline style of a tab in Material UI?

I'm trying to customize the underline of: https://i.stack.imgur.com/J2R1z.png Currently, I am using material ui version 4.12.3 The code snippet for generating my tabs is below: function renderTabs(): JSX.Element { return ( <Tabs className={cla ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...