A guide on setting a constant object for template usage

As I delve into constructing elasticsearch queries, I find myself eager to implement object templates to simplify the creation of POST bodies for my queries before they are sent to the data service.

Although the initial query construction goes smoothly, I encounter a challenge when using templates. It seems that the const objects I declare are being altered, causing the template to malfunction thereafter. In the snippet below, not only is the returnQuery value modified, but the INIT_QUERY const also experiences the same issue. Is there a way to utilize this const object as a template without actually changing its value?

const INIT_QUERY = {
    "query": {
        "filtered": {
            "filter": {
                "bool": {
                    "must": <any>[]
                }
            }
        }
    }
}

const MATCH_QUERY = {
    "match": <any>{}
}
...

export class QueryBuilder {

 constructor() {}

 buildQuery() {
   let returnQuery = INIT_QUERY;
   .... loop

     let query = MATCH_QUERY;
     query.match[dbfield].query = 'fieldValueToSearch';

     returnQuery.query.filtered.filter.bool.must.push(query);

   .... end loop

   return returnQuery;
 }

}

Answer №1

By using <code>let returnQuery = INIT_QUERY;
, you are essentially creating a new reference to the existing object INIT_QUERY. Both variables point to the same object.

If you use Object.assign({}, INIT_QUERY);, it will only create a shallow copy which may not be sufficient for your needs.

An alternative approach is to store your template in JSON format and create new objects based on that.

However, keep in mind that this method may impact intellisense functionality. You will need to define an interface and perform a type cast as shown below:

interface Query {
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": any[]
        }
      }
    }
  }
}
const INIT_QUERY = `{
  "query": {
    "filtered": {
        "filter": {
            "bool": {
                "must": []
            }
        }
    }
}`;
let query: Query = <Query>JSON.parse(INIT_QUERY);
   

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

``Engulfed in a sea of NgRx ViewModel

Apologies if this is unclear, there might be a fundamental aspect that I am overlooking, but here is my current issue: I am fetching a list of items from the backend, similar to: interface Item { id: number; userId: number; categoryId: number; } ...

Is it necessary to manually unsubscribe from observables in the main Angular component?

I'm facing a dilemma with my Observable in the root Angular (6.x) component, AppComponent. Typically, I would unsubscribe from any open Subscription when calling destroy() using the lifecycle hook, ngOnDestroy. However, since the AppComponent serv ...

The function signature '() => Element' is incompatible with the type 'string'

Greetings! I have a standard function that returns a span with a prop (if I'm not mistaken). In my TS code, I am encountering this error: Error image Below is the code from the file named qCard.tsx: import { QuestionAnswerTwoTone } from "@material- ...

Determine the route parameter name based on the path string, for example, '/posts/:id'

My Route interface has a params object, and I'm looking to ensure type safety on that params object. For example: If we have a route config like this: { post: { path: 'posts/:id', } } navigate({ name: 'post', params: { wr ...

What is the best way to send an array to the @input() of a separate component in Angular?

Successfully passed my array to the first @Input() and displayed its contents. Now, facing a challenge where I need to pass data from the first @Input() to the second @Input() and display it. Still navigating my way through Angular and learning the ins a ...

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

Differences between Typescript static methods and functions defined outside of classesWhen comparing Types

What distinguishes a static class method from a function defined outside a class in TypeScript, especially when visibility is not a concern? While there are differences in visibility from other classes and files, what factors should be considered when dec ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

TS2304: The build process is unable to locate the name 'iterable' within @types

As an experienced dog attempting to master new tricks like npm and TypeScript, I find myself faced with a challenge in my Visual Studio 2017 project. Despite setting it to "Latest" TypeScript 2.5 and adding @types/jquery (3.2.12), the project keeps throwin ...

Issue with displaying tab icons in Ionic 4

After updating the versions of Angular, Cordova, and Ionic, I started experiencing an issue with the tab icons displaying partially. Specifically, when my app loads with 4 tabs, only the first and third icons are visible. However, upon touching one of the ...

Ways to transfer selected options from a dropdown menu to a higher-level component

I am currently in the process of configuring a modal component that showcases various data from a specific record to the user. The user is provided with a Bulma dropdown component for each field, enabling them to make changes as needed. To streamline the c ...

Placing images inside a div causes them to vanish

I encountered a strange issue where the images I added to a background disappeared. .Background1{ position:relative; top:0%; left:0%; height:100%; width:100%; content:url("/assets/backgroundlayer1.jpg") } .Background2{ posi ...

Tips for obtaining a redirect URL using Angular5

After receiving a temporary URL from a JSON server, I found out that it redirects to a permanent URL. My goal is to capture and store this redirect (permanent) URL in my database. Do you think this can be achieved with Angular 5? ...

Angular seems to be experiencing issues with maintaining context when executing a function reference for a base class method

Imagine we have CtrlOne that extends CtrlTwo, with a componentOne instantiated in the template of CtrlOne. Here is some code to illustrate the issue: class CtrlOne extends CtrlTwo { constructor() { super(); } } class CtrlTwo { sayMyName(name: st ...

What is the best way to change a string into JSON format within Angular?

Embarking on processing the string below: const json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44 ...

Leveraging Angular 2 to retrieve information from mongoDB

I recently finished setting up my nodejs project which includes a database and some data. The database was created using the following URL: mongodb://localhost:27017/ Check out the code snippet below: var MongoClient = require('mongodb').MongoC ...

Utilizing a constant in setting the slotLabelFormat

I am attempting to configure the slotLabelFormat options in a React TypeScript project When I directly set slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }}, TypeScript compile ...

I'm unable to import correctly using the --compiler option

Having an issue here. I'm trying to bring in the typescript compiler. I used this command: bit import bit.envs/compilers/typescript --compiler Unfortunately, it didn't work. This is the error message: bit import [ids...] import components in ...

Exporting a Component from a Lazy Loaded Module in Angular 2: A Step-by-Step Guide

In Module M1, I have a component 'A' that is added and exported for lazy loading. Now in another module M2, there is component 'B' which uses A as its selector. However, since M1 is lazily loaded, I encounter the following error: "Com ...