Unable to add personalized repository

Looking to implement a request-scoped cache for my repositories, inspired by Hibernate's first-level-cache. I have some ideas on how to achieve this and integrate it with typeorm-transactional-cls-hooked.

For now, I've created a basic provider setup like so:

@Injectable({ scope: Scope.REQUEST })
export class RequestScopedCache extends Object {

  private storage: any = {};

  public set(key: string, value: any) {
    this.storage[key] = value;
  }

  public get(key: string) {
    return this.storage[key];
}

I attempted to inject this provider into a custom repository:

@Injectable()
@EntityRepository(Enqueued)
export class EnqueuedRepository extends Repository<Enqueued> {

  @Inject() readonly cache: RequestScopedCache;

  public async get(id: string) {
    const key = `${this.constructor.name}_${id}`;
    const result = this.cache.get(key);
    if (result) {
      return result;
    }
    const dbResult = await super.findOne(id);
    this.cache.set(key, dbResult);
    return dbResult;
  }

}

Unfortunately, neither constructor injection nor property injection seem to work in the custom repository. It seems that a typeorm-specific constructor (which appears to be private) is being called with the first injected parameter being a connection.

Subsequently, I tried property injection, but that also didn't yield results.

Is there a way to successfully inject custom configuration into a custom repository?

Answer №1

Exploring Composition instead of Inheritance, by encapsulating a repository and utilizing it as a provider, can be beneficial in this scenario:

@Injectable()
export class EnqueuedRepository {
    @Inject() readonly cache: RequestScopedCache;

    constructor(
        @InjectRepository(Enqueued) private readonly enqueuedRepository: Repository<Enqueued>
    ) {
    }
}

Answer №2

While I can't say for certain if this is directly related, one potential method of utilizing custom repositories is outlined below: 1. Begin by crafting a custom repository class in the following manner

@Injectable()
@EntityRepository(UserEntity)
export class UserRepository extends Repository<UserEntity> {
 // Your repository code goes here
 }
  1. Next, inject it into the class where it is needed as shown below
export class UserService {
 constructor(
   @InjectRepository(UserRepository)
   private userRepository: UserRepository,
 ) {}
// Your implementation here
}

This approach allows for the overriding of default TypeORM functionalities and the creation of custom functions tailored to your specific requirements...

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

Exploring Node.js and Express routes

Is it possible to have multiple route files in a nodejs+express application and include them into a single file, like the example below? https://i.sstatic.net/Ex0uN.jpg In hotel.routes.js, there are several routes: const express = require("express") ...

Updating IP addresses in MongoDB

I am dealing with a nested schema in my mongoDB collection. Here's an example of how it looks: { "_id":"61d99bf5544f4822bd963bda0a9c213b", "execution": { "test_split":0, "artifacts&quo ...

How can I retrieve the attributes of multiple identical components within a webpage?

I've recently delved into learning Vue and decided to create a small application for adding fractions together. I have developed two main components: Fraction.vue and App.vue. The App.vue component contains multiple instances of the Fraction component ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

NodeJs Classes TypeError: Unable to access 'name' property as it is undefined

I am currently developing a useful API using Node.js. In order to organize my code effectively, I have created a UserController class where I plan to include all the necessary methods. One thing I am struggling with is how to utilize a variable that I set ...

Error 504: Gateway Timeout - Issue with Node.js + Express + PostgreSQL Server

In my tech stack, I am utilizing node + express for the backend, postgresql for the database, and EJS for the front-end rendering. For managing the server start/stop/logs, I have incorporated the pm2 package. At times, when encountering an API query erro ...

JSON is throwing an error because a semi-colon is missing before a statement

I encountered a perplexing error despite receiving the correct response and being able to view the JSON content: Below is the request: $.ajax({ type: "GET", url: urlTwitter, contentType: "applic ...

Implement a function for templateURL in AngularJS using Typescript programming language

Here is my current setup: export class MyComponent implements ng.IComponentOptions { public static componentName: string = "myViewer"; public bindings: any; public controller: any; public controllerAs: any; public templateUrl: string; ...

Applying a consistent script with varying inputs on the same HTML page

Is it possible to create a JavaScript code that can be used across different sections of an HTML document? The goal is for the script to fetch data such as title, runtime, and plot from a specific URL request and insert this information into the appropriat ...

What's the best way to customize the color of the text "labels" in the Form components of a basic React JS module?

I have a React component named "Login.js" that utilizes forms and renders the following:- return ( <div className="form-container"> <Form onSubmit={onSubmit} noValidate className={loading ? 'loading' : ''}&g ...

I seem to be having trouble with my JavaScript code when attempting to search for items within

I want to implement an onkeyup function for a text input that searches for patient names from column 2 in my table. However, it seems to be not working properly as I don't get any results in return. Below are the snippets of what I have done so far. ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Looking to substitute the <mark> element within a string with the text enclosed in the tag using JavaScript

In need of help with replacing tags inside a string using JavaScript. I want to remove the start and end tags, while keeping the content intact. For example, if my input string is: <div class="active"><mark class="active-search-position">The ...

Dealing with VueJS - Sharing an array of data from a child to a parent component using v-model

I am facing an issue in emitting data (array) from a child component to a parent component using v-model. However, when the parent component is created, my console.log does not work. I am hesitant to work with Vuex as I am still a beginner. Here is my chi ...

Is there a difference in performance between using multiple inline scripts versus one combined inline script?

Comparing Multiple Inline Scripts to a Single Conjoined Inline Script: <script type="text/javascript">/* some codeblock 1 */</script> <script type="text/javascript">/* some codeblock 2 */</script> <script type="text/javascript"& ...

Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...

ExpressJS: Leveraging Dynamic Routing for Post and Put Requests

My tech stack includes Angular on the front end and Express on the back. I am facing a challenge with having two forms on a single page that need to post to the same URL, but trigger different controller methods based on a variable from the request body. ...

How can React.Js and Typescript be used to extract information from JSON files?

Hi there! I've been working with MongoDB, Mongoose, and React.Js for my project. One of the features I have is a page where users can view posts. When making a fetch request to the backend, I receive JSON data in response: { "post" ...