Is it considered a poor practice to self-instantiate within a static method of a JavaScript class

Do you think this object-oriented JavaScript (TypeScript) code is not well-written?

class KYC {
 public reference;
 public data = null;

 constructor(id: string) {
   this.reference = id ? firestoreAdmin.collection('kyc').doc(id) :
           firestoreAdmin.collection('kyc').doc() :
 }

 async get() {
  const result = await this.reference.get();

  if(!result.exist) throw new Error('not found');

  this.data = result.data;

  return this;
 }

 static async getById(id: string) {
  return await new this(id: string).get();
 }
}

I structured it in this way because I feel that using new Kyc(id).get(); can be hard to read, particularly within an Express framework.

Is this approach considered bad practice or potentially an anti-pattern? Your thoughts are greatly appreciated!

Answer №1

Is it considered a bad practice to perform self-instantiation within a static class method?

No, it is not inherently bad practice. Using a static method as a factory is a common approach.

However, the unconventional aspect of your code lies in the asynchronous initialization of the data. While this may serve a particular purpose, it could be argued that the class lacks utility without the data immediately available. Consider initializing the data upfront, within the static method:

class KYC {
  constructor(
    public reference,
    public data,
  ) {}

  static async getFromReference(reference) {
    const result = await reference.get();
    if (!result.exist) throw new Error('not found');
    return result.data;
  }
  static async getById(id: string) {
    const reference = firestoreAdmin.collection('kyc').doc(id);
    return new this(reference, await this.getFromReference(reference));
  }

  … // additional methods utilizing this.data
}

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

JavaScript - Getting the name of a sub-class when extending the Error class

In my application, I have custom Errors that I wanted to check for later using the constructor name. However, when I extend Error in my classes, the constructor name always displays as "Error" instead of the actual name I assigned to it. I conducted some ...

Ways to showcase hierarchical list information in tabulator

I have set up a search and listing panel on my screen. To display nested data on the listing page, I decided to use tabulator. Here is the code in my js file : function onCheckClick() { var url = "/SomeController/SomeAction/"; $.ajax({ url: ...

Utilize Require.js to Load Dropzone.js Library

I am interested in integrating Dropzone.js into an application that is built using Backbone and Require.JS. However, I am unsure of the correct implementation process. Should I utilize require()? What is the most effective way to handle this integration? ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Request failed: The ajax call did not trigger the error function or timeout

Displayed below is the Ajax call that I have created var configuration = { "asynchronous": true, "crossOrigin": true, "url": "http://sample.com/customer/api/v1/meetings/meeting", "methodType": "POST", "headers": { ...

Does the onAuthStateChanged listener in firebase trigger immediately upon user login or logout?

//initialize auth change listener useEffect(() => { auth.onAuthStateChanged((user) => { if (user) { router.replace('/') } }) setInitializing(false) }, []) //*handled by login button const login = asy ...

How can I retrieve the outcomes of the Request.js request method?

var request = require('request'); var cheerio = require('cheerio'); request(url, function (error, response, html) { if (!error && response.statusCode == 200) { var $ = cheerio.load(html); var link = $(&apos ...

How can I make TypeScript's http.get Observable wait for the inline parameter to be returned?

I'm currently facing an issue with my http.get call in which I need one of the parameters (getUserToken) to be returned before the function is executed. However, I don't want to chain them together since the calling function getSomeData returns a ...

Retrieving the ID and value of a specific dropdown list using jQuery from an array of dropdown lists

My HTML structure looks like this: <?php foreach($active_brand as $brand) { ?> <select name="selector" id="selector"> <?php foreach($options as $option) { ?> <option <?php if($brand['State'] == $option) { ?& ...

Implementing dynamic dropdown population in Angular 2 based on selection from another dropdown

I am relatively new to Angular 2 and currently facing a challenge in populating a dropdown menu based on the selection from another dropdown menu from MongoDB. The Issue: While I can successfully load the rooms, I encounter a problem when trying to load t ...

Successfully Passing GET Parameters to ngResource in AngularJS

I'm struggling to figure out how to pass a simple id parameter to my created resource. The service in question is: angular. module('shared.testUser'). factory('TestUser', ['$resource', function($resource) { ...

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

Set the height of the vertical scroll at a fixed 100% floatValue

Check out my creation at http://jsfiddle.net/ZygnV/ html, body { margin: 0; padding: 0; height: 100%; } .main-content-wrapper { height: 100%; overflow-y: hidden; white-space: nowrap; } .main-sidebar { display: inline-block; height: 1 ...

Angular user profile update button not functioning as expected

We are currently implementing Angular alongside Node.js Express. Our issue arises when attempting to update user details from the settings page, as clicking the update button triggers the following error: Failed to load resource: net::ERR_CONNECTION_RESET ...

The functionality of CSSTransition seems to be malfunctioning. Perhaps switching to V2 of react

Can anyone help me troubleshoot my code snippet where I'm attempting to incorporate an animation for Tooltip Nodes? Despite my efforts, the animation does not show up on the screen after mounting. Additionally, the console.log is not triggered on the ...

The issue of v-bind:checked not functioning properly across all component instances

Presenting a unique radio list component: <template> <div class="list"> <div class="radio"> <input type="radio" name="custom-radio-list" :id="'custom-radio-full-' + cid" value="" @change="updateCustomRadio" ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...

Utilizing IndexedDB for data storage

Hey there! I am currently working on storing three fields in an IndexedDB. When I view them in the browser, I see the names of each index - content, content2, and content3. However, only data is being saved into content3. Can you help me figure out why? B ...