What steps can be taken to optimize and streamline this update API, eliminating redundancy and improving efficiency?

Is there a way to simplify the code in this service method for updating an account on an API? I want to reduce the number of objects within the if conditions.




async updateAccount(uuid: string, body: IUpdateAccountDto) {
    const found = await this.getAccountById(uuid);
    const update = (resolve, reject) => {
      if (
        found.username ||
        found.password ||
        found.email ||
        found.phone ||
        found.product
      ) {
        resolve(
          'account updated',
          ((found.username = body.username),
          (found.password = body.password),
          (found.email = body.email),
          (found.phone = body.phone),
          (found.product = body.product)),
        );
      } else {
        reject('cannot update username');
      }
    };

    const updateAccount = new Promise(update);
    return updateAccount;
  }

Answer №1

To achieve this, you can utilize the functions Object.values(obj) and Array.some(fn). Keep in mind that using Array.every(fn) will only fulfill the && condition.

var invalidData = {
  username: "",
  password: undefined,
  email: "",
  phone: null,
  product: ""
};

var hasInvalidValue = Object.values(invalidData).some(o => o);

console.log(hasInvalidValue);

var validData = {
  username: "some_username",
  password: undefined,
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2544654447460b464a48">[email protected]</a>",
  phone: null,
  product: ""
};

var hasValidValue = Object.values(validData).some(o => o);

console.log(hasValidValue);

For more information on how to use Object.values(obj) and Array.prototype.some(fn), you can visit the respective Mozilla Developer Network pages.

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

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Organizing Object Array by Key in Typescript: A Step-by-Step Guide

How can I sort an array of candidate objects in TypeScript within Angular 2 by the name property? candidateid:number; name:string; ...

Guide to personalizing the ngxDaterangepickerMd calendaring component

I need to customize the daterangepicker library using ngxDaterangepickerMd in order to separate the start date into its own input field from the end date. This way, I can make individual modifications to either the start date or end date without affectin ...

What is the best method for creating a zod schema for an intricately nested object?

Here is the data I am working with: { "2022-06-01": { "09:00am": { "time_table_id": 1, "job_id": 4, "start_working_time": "09:00am", "end_working_time": &qu ...

Ignoring lines in code coverage using Istanbul is not an option that can be overlooked

I have come across many examples of code that utilize /* istanbul ignore next / / istanbul ignore start / / istanbul ignore end */ There are certain parts in the codebase that cannot be covered by unit tests, and it would be beneficial to employ these Is ...

When attempting to parse JSON using Json.parse, it throws an error saying: "SyntaxError: Unexpected end of JSON input

Hello everyone on stackoverflow, The Issue I am currently facing an problem when trying to parse a string into JSON. The string that needs to be parsed is sent from the client to the server using a POST method. The server handles this request with the fo ...

What is the best approach to handling an undefined quantity of input FormControls within Angular?

I have a unique task in my Angular application where I need to collect an unspecified number of entries, such as names, into a list. My goal is to convert this list of names into an array. To facilitate this process, I would like to offer users the abilit ...

Every time I clear the information, it seems to be instantly replaced with new data. How can I prevent it from constantly refilling?

When I press the remove button on my application, it successfully deletes the data in a field. However, it also automatically adds new data to the field which was not intended. I am seeking assistance on how to keep those fields empty after removing the ...

What is the best method for storing a third-party image in cache?

Running my website, I aim to achieve top-notch performance scores using LightHouse. I have successfully cached all the images I created (Cache-Control: public, max-age=31536000). Unfortunately, third-party website images are not cached. How can I cache t ...

Develop the data structure according to the function signature specified in Typescript

I am trying to create a function that will take another function as input and return a new function with the same parameters list. const fn1 = (id: string) => {}; const fn2 = (key: string; value: string) => {}; const caller = <F = ??, A = ??>( ...

Is it possible to run TypeScript-transpiled code in a browser directly with es6-style classes and import statements without the need for an extra transpilation

When I transpile TypeScript code using target:"es5" for es6-style classes and React, the resulting transpiled code in my intended entry point (in this case a file named App.ts) looks something like this: Object.defineProperty(exports, "__esM ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

There is an issue with accessing functions from classes in Angular 2

When attempting to use the checkRev function from the Known class in the onNgInit method, I am receiving an error message stating "this.known.checkRev is not a function." Here is my Known class: export class Known { constructor(args...){} public ch ...

State remains unchanged despite calling setState

When working with React, I encountered an issue in my function called setTitleAndBody. Even though the object result is being logged correctly and displaying the title and body information in the developer console, the setState method is not updating the ...

Every time I attempt to use the reset() function in typescript, I encounter a type error that prevents its

I am encountering a type error message that reads: 9: Property 'reset' does not exist on type 'EventTarget'. 18 | }); 19 | 20 | e.target.reset() | ^^^^^ 21 | } Below is the relevant code snippet: const hand ...

Using a Component as a Property in Angular

There is a small gridComponent: @Component({ selector: 'moving-grid', templateUrl: './grid.component.html', styleUrls: ['./grid.component.css'] }) export class GridComponent { @Input('widgets') ext ...

What is the process for extracting the "path expression" from an interface in TypeScript?

My goal is to achieve the following structure: type Post = { id: number title: string author: { name: string } comments: { text: string }[] } type ExtractPathExpressions<T> = ??? type Paths = ExtractPathExpressions<Post> / ...

Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship: Departament: @Entity('Departament') export default class Departament { @PrimaryGeneratedColumn() id: string; @Column() departament_name: string; @OneToOne(type ...

Implement Angular backend API on Azure Cloud Platform

I successfully created a backend API that connects to SQL and is hosted on my Azure account. However, I am unsure of the steps needed to deploy this API on Azure and make it accessible so that I can connect my Angular app to its URL instead of using loca ...

Filtering an array of objects with another array of objects in a React Typescript application

Currently, I am receiving data from the server and storing it in 2 separate states. One state displays all the data received, while the other state presents the data in a paginated format. The data structure is defined as follows: type ArrayType = { nam ...