Definition of data types from the result of a PostgreSQL query in Typescript

Imagine you're dealing with a intricate query that outputs hierarchical JSON data. What's the best way to create Typescript definitions for this query result?

Answer №1

In accordance with Martin Vseticka's suggestion, it would be beneficial to have a look at the actual JSON data you are dealing with. Below is a somewhat intricate example that I recently worked on:

https://i.sstatic.net/WyPjT.png

My approach involves identifying the most basic elements of each tier and then progressively building them under a common parent structure until reaching the top level.

The TypeScript interface used to define this scenario (along with explanatory comments) is as follows:

module RL.SS.Portal.RLToday.Interfaces {

    // The complexity presented here stems from the convoluted nature of the MMS ASMX service.
    /*
        data
            TermStore
                T: [] of
                    DS: string or object, --> this is where the description would go if there is one. blank string if no desciption, otherwise object ->
                        TD: object ->
                            a11: string (the description;  you can see and edit this description in the UI)
                    LS: object ->
                        TL: object -> **NOTE: this will be an array if there are multiple labels.
                            a31: boolean (seems to be if it's the default value when there are multiple labels)
                            a32: string (seems to be the value of the term as a string)
                    TMS: object ->
                        TM: object ->
                            a12: "Locations" (prob term set name)
                            a17: boolean (seems to indicate whether end users can use this for tagging. visible in the term set UI via site collection admin)
                            a24: string (guid, parent ID if any)
                            a40: string, blank in the sample I have
                            a45: string (guid, not sure what)
                            a67: string, blank in my sample
                    a9: guid of the term
                    a21: boolean, true if there are children
                    a61: "0" in my sample

      This modeling task is highly challenging due to the variable rules applied based on alternative keywords.

      The current definition assumes a consistent set of keywords without variations.

      Note that the GUIDs do not contain parentheses in their raw form.
    */
    export interface MmsAsmxTL {
        _a31: boolean, // Indicates if it's the default term label (mainly useful if there are multiple labels for this term)
        _a32: string // Value of the term
    }

    export interface MmsAsmxLS {
        TL: MmsAsmxTL
    }

    export interface MmsAsmxTM {
        _a12: string, // name of the term set
        _a17: boolean, // whether it's available for tagging or not
        _a24: string, // some kind of guid,
        _a40: string, // Not sure,
        _a45: string, // guid, not sure for what,
        _a67: string // another blank string as per the sample data
    }

    export interface MmsAsmxTMS {
        TM: MmsAsmxTM;
    }

    export interface MmsAsmxTD {
        _a11: string; // Description of the term. Not mandatory.
    }

    export interface MmsAsmxDS {
        TD ?: MmsAsmxTD // optional, will not exist if there's not description
    }

    export interface MmsAsmxT {
        DS: MmsAsmxDS,
        LS: MmsAsmxLS,
        TMS: MmsAsmxTMS,
        _a9: string, // guid of the term
        _a21: boolean, // whether there are children
        _a61: string
    }

    export interface MmsAsmxTermStore {
        T: MmsAsmxT[]
    }

    export interface MmsAsmxData {
        TermStore: MmsAsmxTermStore;
    }
    export interface MmsAsmxSuccessResult {
        data: MmsAsmxData;
    }
}

Hope this helps clarify things for you.

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

How can I iterate through a string array using RapidJSON?

I am struggling to figure out how to iterate through the members of a JSON object using RapidJSON. Here is an example of the JSON data structure: { "members":{ "0":{ "template":"this is member 1" }, "1":{ "template":"this is m ...

Serving both HTML and JSON responses concurrently using PHP

Consider a scenario where a webpage contains elements generated in HTML directly from the server backend and others generated through JavaScript with data sourced from JSON. Upon initially loading the page, the HTML layout and its elements are delivered in ...

Obtaining a JSON string from a URL in Xamarin.Forms PCL

For instance, I encountered an issue with retrieving a JSON string from the following URL: . Since WebClient is not supported in Xamarin.forms PCL, I turned to Xamarin's documentation on utilizing web services in forms and followed their example. Li ...

Setting a predefined value in a dropdown menu can be a challenge, especially when the default value is hardcoded in

I am working with a dropdown and I want to make All Patients the default value. <select [(ngModel)]="searchModel.careprovider"> <option [value]="0">All Pateints</option> <option *ngFor="let user of practiceUsers" [valu ...

What is the proper way to include non-string values in a TJSONObject?

When using a TJSONObject, I have observed that the AddPair function has several different overloads: function AddPair(const Pair: TJSONPair): TJSONObject; overload; function AddPair(const Str: TJSONString, const Val: TJSONValue): TJSONObject; overload; fu ...

What is the best way to generate a POJO class in Java that can handle JSON with dynamic keys when using

{ "batchcomplete": "", "warnings": { "main": { "*": "Unrecognized parameter: rvprop." }, "extracts": { "*": "\"exlimit\" was too large for a whole article extracts request, lowered to 1." } }, "query": { "n ...

Exploring the Functionality of Backend Objects in Frontend TypeScript within the MEAN Stack Environment

Utilizing MongoDB, express.js, angular4, node.js Although a string I retrieve is successful, it's not the same as retrieving the full object... account.service.ts (full, ) import { Injectable } from '@angular/core'; import { Http, Headers ...

Discover the power of Angular2 by utilizing local template variables for efficient element management within a list

Here is a simple code snippet: <ul> <li *ngFor="let item of list"> <div class="button">Click to show text</div> <div class="text">hello</div </li> </ul> The goal is to create and assign a local var ...

Unable to convert information into a Dictionary

I am facing the challenge of casting a JSONObject to its class. My attempt at using JSONSerialization.data(withJSONObject: data, options: []) and encoding it as a .utf8 String has not been successful.... socket.on("privateMessage") {data, ack in ...

What could be causing TypeScript to struggle with verifying the return type of a function?

I am facing an issue with a function that is supposed to return NetworkState. However, despite the code clearly showing that the function does not return the correct type in most cases, TypeScript does not flag any errors. Can someone point out what I migh ...

Adjust the color of the IText element on a Fabric.JS canvas (utilizing React and typescript)

I have an input with the type=color attribute positioned outside of a Canvas. Inside the canvas, there are one or more IText objects along with other elements. My goal is to "change the color of selected text objects when the input value changes". Incorpo ...

The NgRx Effect causing an endless cycle of HTTP requests

I am currently experiencing the following effect: initCompaniesAndSetCompanyEffect$: Observable<Action> = createEffect( (): Observable<Action> => this.actions$.pipe( ofType<changeCompanyActions.InitCompaniesAction>( ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Understanding the difference between read and write operations in an array versus multiple rows in Postgres

When dealing with storing 10k (varying at times) string values under the same ID multiple times, is it advisable to utilize an array for storage or should the string values be inserted individually under the same ID? ...

Using Angular to dynamically set data and labels for a bar chart

My issue is with dynamically adding data to my bar chart dataset as it keeps returning undefined. Here's the current working version: public barChartData: ChartDataSets[] = [ { data: [], label: 'High' }, { data: [], label: 'Medium' ...

module 'next/router' cannot be located or its associated type declarations are missing

Running into some issues with my NextJS application. An unusual error message is appearing, even though my code is functioning smoothly without any errors. import { useRouter } from 'next/router'; // Cannot find module 'next/router' or ...

An abstract class featuring a nested generic function that is also abstract

I am working on creating a dynamic table that can change its content and position based on a special row unique to each page. Currently, I'm encountering an error The generic type 'Table<SpecialFunctions>' requires 1 type argument(s). ...

Enhance your text in TextInput by incorporating newline characters with advanced editing features

I'm encountering an issue with my Textarea component that handles Markdown headers: type TextareaProps = { initValue: string; style?: StyleProp<TextStyle>; onChange?: (value: string) => void; }; type OnChangeFun = NativeSynthetic ...

Utilizing a where clause within a relation table in a NestJS application with PostgreSQL database using Type

I have come across a query that looks like this async findAllEnquiries(filter: DataFilterDto): Promise<ApiResponseDto<EnquiryEntity[]>> { const take = filter.count || 10; const page = filter.pageNo > 0 ? filter.pageNo - 1 : 0; co ...

What is the best way to assign a type based on a variadic type in TypeScript?

TypeScript playground link For my current project, I am designing a custom route handler creator for Express. The goal is to allow passing arbitrary assertions as initial arguments before invoking the route handler callback. Here's an example of how ...