@takentrade/takentrade-libs
Version:
TakeNTrade shared libraries
49 lines (48 loc) • 1.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetUser = void 0;
const common_1 = require("@nestjs/common");
/**
* Extracts the user object or a specific property from the request's user payload.
* @param data Optional key of the TokenPayload to extract a specific property.
* @param ctx Execution context to access the request.
* @returns The entire user object or the specified property value.
* @throws UnauthorizedException if user or requested property is not found.
*/
const getUserHelpers = {
getUserFromRequest(request) {
const user = request.user;
if (!user) {
throw new common_1.UnauthorizedException('User not found in request');
}
return user;
},
getUserProperty(user, data) {
if (!data) {
return user;
}
if (data === 'sub') {
const value = user.id || user.sub;
if (!value) {
throw new common_1.UnauthorizedException('User ID not found');
}
return value;
}
const value = user[data];
if (value === undefined) {
throw new common_1.UnauthorizedException(`User ${data} not found`);
}
return value;
},
};
/**
* Custom decorator to extract user data from the request.
* @param data Optional key of the TokenPayload to extract a specific property.
* @param ctx Execution context to access the request.
* @returns The user object or the specified property value.
*/
exports.GetUser = (0, common_1.createParamDecorator)((data, ctx) => {
const request = ctx.switchToHttp().getRequest();
const user = getUserHelpers.getUserFromRequest(request);
return getUserHelpers.getUserProperty(user, data);
});