UNPKG

@lomray/microservice-users

Version:

Users microservice based on NodeJS & inverted json.

66 lines (62 loc) 2.1 kB
'use strict'; var tslib = require('tslib'); var microserviceNodejsLib = require('@lomray/microservice-nodejs-lib'); var classValidator = require('class-validator'); /** * Sign up user */ class SignUp { /** * @constructor */ constructor({ fields, repository, isConfirmed }) { this.fields = fields; this.isConfirmed = isConfirmed; this.repository = repository; } /** * Init service */ static init(params) { return new SignUp(params); } /** * Sign up user */ register() { return tslib.__awaiter(this, void 0, void 0, function* () { const entity = this.repository.create(this.fields); const errors = yield classValidator.validate(entity, { whitelist: true, forbidNonWhitelisted: true, groups: ['create', 'sign-up', this.repository.metadata.name], always: true, validationError: { target: false }, }); if (errors.length > 0) { throw new microserviceNodejsLib.BaseException({ status: 422, message: 'Validation failed.', payload: errors, }); } if (entity.email && entity.phone) { throw new microserviceNodejsLib.BaseException({ status: 422, message: 'Either email or phone number must be sent.', }); } if (!(yield this.isConfirmed())) { throw new microserviceNodejsLib.BaseException({ status: 422, message: 'Invalid confirmation code.', }); } yield this.repository.encryptPassword(entity); const user = yield this.repository.save(entity); yield this.repository.attachProfile(user, Object.assign({}, (entity.email ? { isEmailVerified: true } : { isPhoneVerified: true }))); return user; }); } } module.exports = SignUp;