Developing a foundational Repository class in TypeORM

Are you looking to create a custom baseRepository class that extends TypeORM's Repository?


        import { Repository } from 'typeorm';

        export abstract class BaseRepo extends Repository<T> {

            public getAll () { ... }

            public getOneById (id: number) { ... }

            public deleteById (id: number) { ... }

        }
    

Once you have created your base repository, you can inherit those methods like this:


        @EntityRepository(User)
        export class UserRepo extends BaseRepo<User> {

            constructor (baseRepo: BaseRepo) {
                super();
                this.__baseRepo = baseRepo;
            }

            public getOne (id: number) {
                return __baseRepo.getOneById(id);
            }
        }
    

Answer №1

This solution does not require the use of a constructor

import { Repository } from "typeorm";

export class BaseRepo<T> extends Repository<T> {

   getOneById(id: string) { ... }

}

You can implement it in your code like this:

import { EntityRepository } from "typeorm";
import { BaseRepo } from "../shared/BaseRepo";
import { User } from "../entities/User";

@EntityRepository(User)
export class MyEntityRepository extends BaseRepo<User> { }

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

The combination of Autodesk Forge Viewer and React with TypeScript provides a powerful platform for developing

I'm brand new to React and Typescript, and I have a very basic question. In the viewer documentation, extensions are defined as classes. Is it possible to transform that class into a typescript function? Does that even make sense? For example, take th ...

Error encountered with default theme styling in Material-UI React TypeScript components

Currently, I am working on integrating Material-UI (v4.4.3) with a React (v16.9.2) TypeScript (v3.6.3) website. Following the example of the AppBar component from https://material-ui.com/components/app-bar/ and the TypeScript Guide https://material-ui.com/ ...

Error in Firebase Emulator: The refFromUrl() function requires a complete and valid URL to run properly

Could it be that refFromURL() is not functioning properly when used locally? function deleteImage(imageUrl: string) { let urlRef = firebase.storage().refFromURL(imageUrl) return urlRef.delete().catch((error) => console.error(error)) } Upon ...

Using TypeScript arrow functions to define parameters

When setting "noImplicitAny": true in TypeScript, you may encounter the following errors: Parameter 'x' implicitly has an 'any' type This error can occur with the code snippet: .do(x => console.log(x)); Another error you might s ...

Inputting data types as arguments into a personalized hook

I am currently developing a Next.js application and have created a custom hook called useAxios. I am looking to implement a type assertion similar to what can be done with useState. For example: const [foo, setFoo] = useState<string>(''); ...

What is the process for retrieving information from a retail outlet?

How can I retrieve data from the Vuex store using Vue.js? Below is my code: Vue.use(Vuex); export default new Vuex.Store({ modules: { data } }) data.js import axios from 'axios'; const state = { data: '' }; cons ...

Having trouble compiling Typescript code when attempting to apply material-ui withStyles function

I have the following dependencies: "@material-ui/core": "3.5.1", "react": "16.4.0", "typescript": "2.6.1" Currently, I am attempting to recreate the material-ui demo for SimpleListMenu. However, I am encountering one final compile error that is proving ...

The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario: selectOrder(orderId): void { this.store$.dispatch( selectOrder({orderId}) ); } The order UI component triggers an action to load all associated data: private fetchOrderOnSelectOrder(): void { this.sto ...

How can elements be collapsed into an array using the Reactive approach?

Consider this TypeScript/Angular 2 code snippet: query(): Rx.Observable<any> { return Observable.create((o) => { var refinedPosts = new Array<RefinedPost>(); const observable = this.server.get('http://localhost/ra ...

Creating multiple relationships in TypeORM for entities with private properties

In my node application, I am utilizing the typeorm library for entity mapping. My goal is to establish multiple type relations between entities. While following the documentation, I noticed that the entity properties are marked as public, allowing access f ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

A class in Typescript containing static methods that adhere to an interface with a string index

Take a look at this code snippet: interface StringDoers { [key: string]: (s: string) => void; } class MyStringDoers implements StringDoers { public static print(s: string) { console.log(s); } public static printTwice(s: string) { conso ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

Enhancing a prototype instance in TypeScript while activating strict mode

When working with an instance named remote from a factory in a vendor script, I encountered the need to add my own methods and members to that instance. While seeking a solution, I came across an insightful response on extending this in a Typescript class ...

Interacting with User Input in React and TypeScript: Utilizing onKeyDown and onChange

Trying to assign both an onChange and onKeyDown event handler to an Input component with TypeScript has become overwhelming. This is the current structure of the Input component: import React, { ChangeEvent, KeyboardEvent } from 'react' import ...

The error message "Type 'null' cannot be assigned to type 'Element | DocumentFragment'" occurs when using Nextjs/React createPortal

I am completely new to typescript. Currently, I'm working on a project that has a lot of pre-configured react components in JavaScript files (.js). My task now is to convert everything to TypeScript (.tsx) without triggering any ESLint errors. Unfort ...

Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

Is there a way to ensure my custom tslint rule is compatible with the exact version of the TypeScript module being used by tslint?

I seem to be missing something crucial, but I can't pinpoint the issue. Within my custom rule, I am utilizing the SyntaxKind of a Node for controlling my flow, as shown below: import * as ts from "typescript" function processPropertyName(pn: ts.Pro ...

What methods can I employ to trace anonymous functions within the Angular framework?

I'm curious about how to keep track of anonymous functions for performance purposes. Is there a way to determine which piece of code an anonymous function is associated with? Here's an example of my code: <button (click)="startTimeout()&q ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...