Tips for developing a universal function using TypeScript and TypeORM

Seeking advice on creating a versatile function in TypeScript and TypeORM

I currently have numerous functions structured like this:

    async getOrderName(id: number): Promise<string> {
        const order = await this.conn.getRepository(Order).findOne(id);
        return `${order.name}`;
    }
    async getServiceName(id: number): Promise<string> {
        const service = await this.conn.getRepository(Service).findOne(id);
        return `${service.name}`;
    }

and the list goes on... I am looking to develop a single generic function that can be utilized across multiple entities

If anyone has insight on how to go about creating such a function, please share!

Answer №1

Utilizing duck typing to generalize functionality across different types of EntityTargets can be quite powerful:

interface NamedThing {
    name: string
}
async extractName<Entity extends NamedThing>(id: number, target: EntityTarget<Entity>): Promise<string> {
    const namedEntity = await this.conn.getRepository<Entity>(target).findOne(id);
    return `${namedEntity && namedEntity.name}`;
}

// Now you can call the function with `extractName(id, Order)`, `extractName(id, Service)`, and so on.

Answer №2

If you're interested in diving deeper into TypeScript generics, I urge you to explore this link.

With generics, you have the flexibility to pass in type T and return type T as needed.

async fetchEntityName<T>(id: T): Promise<string> {
        const entity = await this.connection.getRepository(Entity).findOne(id);
        return `${entity.name}`;
    }

To handle different types of inputs, you may need to extend the functionality of the findOne method or resort to using the any keyword for simplicity.

Answer №3

One method is to utilize

const variable = MyRepositoryName

then provide variable as a parameter for the function

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

Separate and add on the change validity status of an AngularJS form

If you want to test it out, check this jsFiddle link: HERE (it's recommended to view on a new jsFiddle, refer to the EDIT section of this post) I've noticed what seems like a bug in AngularJS or at least an unexpected behavior. When I detach a f ...

Is there a way to verify that a form field has been completed?

Currently, I am grappling with a method to clear a field if a specific field is filled in and vice versa. This form identifies urgent care locations based on the information provided by users. The required entries include the name of the urgent care facil ...

Icon for local system displayed on browser tab

I am currently trying to set a Browser Tab icon for the local system, but it is not working. However, when using an HTTP static icon, it works perfectly. Can someone please help me understand what the issue might be? PAGE 1 : Icon Not Showing <link re ...

Experience the combined power of addthis, isotope, and nicescroll - all in a single

I am utilizing a WordPress template that includes a set of share buttons from AddThis. <ul class="addthis extra"> <li class="addthis-hold"> <div class="addthis_toolbox" addthis:url="<?php the_permalink( ...

Cross domain Ajax POST requests using CodeIgniter and AjaxBy utilizing CodeIgn

Initially, I would like to clarify ... I own two domains: www.one.com and www.two.com The first domain www.one.com has a form input below <div class="hidden cswrap2"> <h3>Edit Data Mustahik</h3> <div class="cscontent"> ...

Attempting to create a button cluster using Bootstrap and AngularJS for the purpose of navigating to various URLs

Looking to create a pair of buttons using bootstrap and angularjs that will redirect to different URLs when clicked. Here is the relevant code snippet: app.controller('LinkController',function(link, $scope, $location){ $scope.go = function() ...

Is it possible to display two separate pieces of content in two separate divs simultaneously?

import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <span>Is React a JavaScript library for creating user interfaces?</span>, document.getElementById("question1") ) ReactDOM.render( <form class="options"> ...

Issue: The component series.line does not exist. Please ensure it is loaded before using it in Vue Echarts

I added the line component, but I'm still encountering issues. I set up my project using vue cli 3 and referred to this guide, but I can't locate the vue.config.js file in my project. Therefore, I manually created a vue.config.js and placed it in ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

Ways to conceal elements when a router link is clicked

Within my app.js, I have the App.js where I aim to display certain components upon clicking on the router. Below is the code snippet from my App.js: import React from 'react'; import {BrowserRouter, Route} from 'react-router-dom'; impo ...

Creating stylish elements for dynamically inserted content

After searching online, I am still unable to find a solution to my issue. Let me provide a detailed explanation of the problem. I am attempting to dynamically insert content into an unordered list (<ul>) and ensure that it is formatted correctly. Th ...

I am struggling with grasping the concept of the event system

I'm encountering an issue with the following code snippet: <template> <div class="chart" v-bind:style="chartStyleObject" v-on:mousedown.left="initHandleMousedown($event)" v-on:mouseup.left="initHandleMouseu ...

Hover-over functionality not functioning properly on select images

My website, located at , is fully functional. When you visit the homepage, you will see some words that turn black when you hover over them. I recently switched this site, which was originally created in Dreamweaver, to Umbraco, a .net based CMS. My site ...

Is it appropriate to utilize response headers (specifically 400 error codes) to communicate errors, especially when working with x-editable?

Exploring the capabilities of the plugin reveals that it offers two distinct callbacks upon posting a result: error and success. The error callback is triggered in cases where the server does not respond with a 200 header. This means that if the server d ...

React Image Error Handling: How to deal with broken images in

I am currently working on a project where I need to retrieve the maxresdefault of various YouTube thumbnails. However, some YouTube videos do not have high-resolution thumbnail images available. To handle this scenario, I added an onError prop to the img ...

Incorporating outside content into HTML

Currently, I am working on a project at my job which requires me to create a comprehensive help file with multiple chapters and extensive text all within one large HTML file. However, as the text will need to be translated into different languages, I am lo ...

During bundling, utilize an npm script to copy the package.json file to the dist directory

Currently, I am facing a challenge while trying to enhance my npm bundle script. Although the initial part is functioning smoothly, I am encountering difficulties in including three additional files along with the bundle. At present, my script looks like ...

Determine the output based on the data received from the ajax post request

I am seeking a way to validate my form based on the data returned. Currently, the validation only returns false if the entire post function is false. Is there a solution to differentiate how it is returned depending on which condition is met? This is my ...

Discover the elements that are currently utilizing jQuery widgets

I currently utilize the jQuery-File-Upload plugin in my project, but I believe my query can apply to any jQuery plugin. The API documentation suggests initiating the plugin using the fileupload method, like so: $('#fileupload').fileupload(); My ...