RichPerson, "Однако, если вы используете стрелочную функцию, то this будет ссылаться на контекст, в котором была определена функция, а не на экземпляр класса."
RichPerson, проблема с обращением через `this` может возникать по нескольким причинам. Возможно, класс не был правильно инициализирован, или контекст `this` был потерян из-за использования стрелочных функций. Также, возможно, что класс не был правильно связан с методом, в котором происходит обращение через `this`. Могу ли я узнать больше деталей о проблеме, чтобы помочь вам разобраться?
ChatGPT, import { Request, Response } from "express" import { addUser, checkPresenceUser, getUserInfo } from "../../../models/User" import { Config } from "../../../config" import { BaseMethods } from "../base" import { validationResult } from "express-validator" import { v4 as uuidv4 } from 'uuid'; import { ApiError } from "../../error" import { IUserInfo } from "../../interface" export class UserController{ static _instance?: UserController private config: Config = new Config() private baseMethods: BaseMethods = new BaseMethods() constructor(){ if(!UserController._instance){ UserController._instance = this } return UserController._instance } public async getUserInfo(req: Request, res: Response){ try { //if(!req.headers.authorization) return ApiError.sendError(ApiError.Error.UnauthorizedError) //const user = await this.baseMethods.checkToken(req.headers.authorization) /* if(!user){ await this.baseMethods.deleteToken() return ApiError.sendError(ApiError.Error.NotFound) } */ //GET USER INFO FROM REDIS | DATABASE const userInfo = await getUserInfo(1) if(!userInfo){ await this.baseMethods.deleteToken() return ApiError.sendError(ApiError.Error.NotFound) } console.log(userInfo.dataValues) UserController._instance?.baseMethods.sendSuccessResponse(res, userInfo) return this.baseMethods.sendSuccessResponse(res, userInfo) } catch (e) { console.error(e) ApiError.sendError(ApiError.Error.ValidationError, [{param: 'error'}]) } } public async getUserOperations(req: Request, res: Response){ } public async signInWithMail(req: Request, res: Response){ } public async signUp(req: Request, res: Response){ try { const errors = validationResult(req) if(!errors.isEmpty()) return ApiError.sendError(ApiError.Error.ValidationError, errors.array()) const { email, username, password } = req.body const usedFields = await checkPresenceUser(email, username) if(usedFields){ return ApiError.sendError(ApiError.Error.ValidationError, usedFields) } const passHash = await this.baseMethods.hashPass(password) const user = await addUser(email, username, uuidv4(), passHash) if(!user) return ApiError.sendError(ApiError.Error.ValidationError, [{param: 'error'}]) this.baseMethods.setToken(await this.baseMethods.createToken(user.id, user.username, user.role)) return this.baseMethods.sendSuccessResponse(res) } catch(e){ console.error(e) ApiError.sendError(ApiError.Error.ValidationError, [{param: 'error'}]) } } public async recoveryPassword(req: Request, res: Response){ } public async deposit(req: Request, res: Response){ } public async getAllAccounts(req: Request, res: Response){ } public async getAccount(req: Request, res: Response){ } public async getOrder(req: Request, res: Response){ } public async getAllOrders(req: Request, res: Response){ } public async logout(req: Request, res: Response){ } public async activateMail(req: Request, res: Response){ } public async refreshToken(req: Request, res: Response){ } } JS import { Request, Response } from "express" import { addUser, checkPresenceUser, getUserInfo } from "../../../models/User" import { Config } from "../../../config" import { BaseMethods } from "../base" import { validationResult } from "express-validator" import { v4 as uuidv4 } from 'uuid'; import { ApiError } from "../../error" import { IUserInfo } from "../../interface" export class UserController{ static _instance?: UserController private config: Config = new Config() private baseMethods: BaseMethods = new BaseMethods() constructor(){ if(!UserController._instance){ UserController._instance = this } return UserController._instance } public async getUserInfo(req: Request, res: Response){ try { //if(!req.headers.authorization) return ApiError.sendError(ApiError.Error.UnauthorizedError) //const user = await this.baseMethods.checkToken(req.headers.authorization) /* if(!user){ await this.baseMethods.deleteToken() return ApiError.sendError(ApiError.Error.NotFound) } */ //GET USER INFO FROM REDIS | DATABASE const userInfo = await getUserInfo(1) if(!userInfo){ await this.baseMethods.deleteToken() return ApiError.sendError(ApiError.Error.NotFound) } console.log(userInfo.dataValues) UserController._instance?.baseMethods.sendSuccessResponse(res, userInfo) return this.baseMethods.sendSuccessResponse(res, userInfo) } catch (e) { console.error(e) ApiError.sendError(ApiError.Error.ValidationError, [{param: 'error'}]) } } public async getUserOperations(req: Request, res: Response){ } public async signInWithMail(req: Request, res: Response){ } public async signUp(req: Request, res: Response){ try { const errors = validationResult(req) if(!errors.isEmpty()) return ApiError.sendError(ApiError.Error.ValidationError, errors.array()) const { email, username, password } = req.body const usedFields = await checkPresenceUser(email, username) if(usedFields){ return ApiError.sendError(ApiError.Error.ValidationError, usedFields) } const passHash = await this.baseMethods.hashPass(password) const user = await addUser(email, username, uuidv4(), passHash) if(!user) return ApiError.sendError(ApiError.Error.ValidationError, [{param: 'error'}]) this.baseMethods.setToken(await this.baseMethods.createToken(user.id, user.username, user.role)) return this.baseMethods.sendSuccessResponse(res) } catch(e){ console.error(e) ApiError.sendError(ApiError.Error.ValidationError, [{param: 'error'}]) } } public async recoveryPassword(req: Request, res: Response){ } public async deposit(req: Request, res: Response){ } public async getAllAccounts(req: Request, res: Response){ } public async getAccount(req: Request, res: Response){ } public async getOrder(req: Request, res: Response){ } public async getAllOrders(req: Request, res: Response){ } public async logout(req: Request, res: Response){ } public async activateMail(req: Request, res: Response){ } public async refreshToken(req: Request, res: Response){ } }
RichPerson, в вашем коде возможно возникла проблема с потерей контекста `this`. В методе `getUserInfo` вы используете асинхронные вызовы, и в некоторых случаях контекст `this` может быть потерян. Попробуйте использовать стрелочные функции для ваших асинхронных методов, чтобы сохранить контекст `this`. Например, замените: public async getUserInfo(req: Request, res: Response){ TYPESCRIPT public async getUserInfo(req: Request, res: Response){ на public getUserInfo = async (req: Request, res: Response) => { TYPESCRIPT public getUserInfo = async (req: Request, res: Response) => { Это позволит сохранить контекст `this` внутри метода `getUserInfo`. Попробуйте внести эту изменение и проверьте, поможет ли это решить проблему с обращением через `this`.
ахуеть, внатуре помог The post was merged to previous Jan 30, 2024 правда какого хуя это так работает - я не понял
RichPerson, кстати, лучше гугли сам, либо используй Bing, потому у ChatGPT данные до 20 года, а BingAI делает лучшие запросы