Guide for retrieving a user object from an HTTP request

I am looking to retrieve only the user object from the request.

public async getUserByHash(hash: IHash) {
    this.logger.log('Hash for check email accessed');
    const user = await this.hashRepository.findOne({
        select: ['id', 'user'],
        relations: ['user'],
        where: hash,
    });
    return user;
}

The user variable now holds the following information.

{
    id:2
    user: {
        id: 3, 
        email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f6a626e66634f7b6a7c7b216c6062">[email protected]</a>",
        password:"12345678"
    }
}

I specifically want to retrieve only the user fields, which are the identifier and email.

I attempted to modify it like so but encountered an error.

public async getUserByHash(hash: IHash) {
    this.logger.log('Hash for check email accessed');
    const user = await this.hashRepository.findOne({
        select: ['user.id', 'user.email'],
        relations: ['user'],
        where: hash,
    });
    return user;
}

However, I encountered an error message:

QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'distinctAlias.Hash_id' in 'field list'

Is there a better way to retrieve only the user fields, such as ID and email?

Answer №1

If you're looking for a solution, consider using the lodash library.

import { pick as _pick } from 'lodash'; 

public async retrieveUserByEmailHash(hash: IHash) {
    this.logger.log('Retrieving user by email hash');

    const retrievedUser = await this.hashRepository.findOne({
        select: ['id', 'user'],
        relations: ['user'],
        where: hash,
    });

    return _pick(retrievedUser.user, ['id', 'email']);
}

Answer №2

Perhaps giving this a shot could be beneficial.

retrieve user's username

Fingers crossed that it helps!

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

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

How is it possible to utilize type assertions with literals like `false`?

When working in TypeScript, I came across an interesting observation when compiling the following code: const x = true as false; Surprisingly, this direct assertion is valid, creating a constant x with the value true and type false. This differs from the ...

Disallow the use of properties in a nested interface

Is there a way to define an interface or type that restricts a specific key in a child of the interface when used in union types? I am looking for the correct definition for Abc: type Abc = { someField: { prohibited?: never, }, }; type Use ...

pnpm, vue, and vite monorepo: tackling alias path imports within a workspace package

I am in the process of creating a monorepo for UI applications that utilize shared components and styles with pnpm, typescript, vue, and vite. While attempting to streamline development and deployment using pnpm's workspace feature, I am encountering ...

Opt for Observable over Promise in your applications

I have implemented this function in one of my servlets: private setValues() { this.config.socket.on('config.weather', (values:any) => { console.log(values); } However, I would like to refactor it to something like this: private se ...

@ngrx effects ensure switchmap does not stop on error

Throughout the sign up process, I make 3 http calls: signing up with an auth provider, creating an account within the API, and then logging in. If the signup with the auth provider fails (e.g. due to an existing account), the process still tries to create ...

Ensuring the correct type for an object's interface property value

I am currently working on defining a new interface interface SUser { ID: number; NAME: string; MAIL: string; PASSWORD: string; GENDER: number; BIRTHDATE: string; ID_FB: string; CREDIT: number; ID_REFERRAL: number; } My objective is to c ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

What is the best way to pass down SectionList prop types in TypeScript when using React?

I am working on creating a wrapper for SectionList in React Native that needs to accept all the standard props of SectionList along with some custom ones. How can I set up typescript to accommodate this? Here is what I have tried: import React from &apos ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

Using PersistedModel.create(Array) will generate an object containing properties that are numbered sequentially

Here is a piece of code that makes a call to a Loopback API method with an array of values. The input data is correct, no errors are thrown by the API, and the subscribe block executes as expected. const newStudentGroups = selectedStudentI ...

Dynamic Material UI Timeline

I am facing a challenge with making the Timeline in Material UI responsive for the first time. Currently, I have it set to align 'alternate', but I want it to switch to align 'left' when viewed on mobile or certain screen widths. I have ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

What is the best way to initialize a discriminated union in TypeScript using a given type?

Looking at the discriminated union named MyUnion, the aim is to invoke a function called createMyUnionObject using one of the specified types within MyUnion. Additionally, a suitable value for the value must be provided with the correct type. type MyUnion ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

What is the process for creating a node module with TypeScript?

So, with regards to the previous question about importing a module using typescript, here is a general answer: 1) Start by creating a blah.d.ts definition file. 2) Use the following code snippet: /// <reference path="./defs/foo/foo.d.ts"/> import ...

Remove the color options from the Material UI theme

Can certain color types be excluded from the MUI palette in MUI v5? For example, can background and error colors be removed, allowing only colors defined in a custom theme file to be used? I attempted using 'never' but it did not provide a solut ...