import { IUserDoc , userSchema } from './users.model' ; import { Mongoose , Model } from 'mongoose' ; import * as bcrypt from 'bcryptjs' ; import * as jwt from 'jsonwebtoken' ; import * as mongoose from 'mongoose' ; param _id return export const toObjectId = ( _id ) : mongoose . Types . ObjectId | null => { return ( mongoose . Types . ObjectId . isValid ( _id ) ) ? ( typeof _id === 'string' ) ? mongoose . Types . ObjectId . createFromHexString ( _id ) : _id : null ; } ; param secretToken param expire param doc export const getToken = ( secretToken = null , expire = null , doc = { } ) : string => { if ( ! doc . _id || ! doc . email ) return '' ; const payload = { _id : doc . _id , email : doc . email } ; return jwt . sign ( payload , secretToken , { expiresIn : + expire } ) ; } ; export class UsersRepo { private _model : Model < IUserDoc > ; private _connected = true ; private _db : Mongoose ; private _serverConfig ; public get model ( ) { return this . _model ; } public get serverConfig ( ) { return this . _serverConfig ; } init ( db , serverConfig ) { if ( ! db ) return Promise . reject ( '{UserRepo} DB not available!' ) ; if ( db . connection . readyState !== 1 ) return Promise . reject ( '{UserRepo} DB not connected!' ) ; if ( ! serverConfig ) return Promise . reject ( '{UserRepo} Auth repository must be started with server configuration' ) ; this . _serverConfig = serverConfig ; db . connection . once ( 'disconnect' , ( ) => { this . _connected = false ; } ) ; this . _db = db ; this . _model = this . _db . model < IUserDoc > ( 'users' , userSchema ) ; return Promise . resolve ( this ) ; } public getToken ( doc ) { return getToken ( this . _serverConfig . secretTokent , + this . _serverConfig . jwtExpire , doc ) ; } async getById ( id ) { if ( ! this . _connected ) { return Promise . reject ( '{UserRepo} DB not connected' ) ; } const user = await this . _model . findOne ( { uid : toObjectId ( id ) } ) ; if ( ! user || user instanceof Error ) return Promise . reject ( `{UserRepo} getById failed. User don't exist.` ) ; return { user } ; } public async create ( data ) { let user = await this . _model . findOne ( { email : data . email } ) ; if ( user instanceof Error ) return Promise . reject ( { code : 400 , message : `{UserRepo} An error occured fetching a data with email: ${ data . email }` , stack : user } ) ; if ( user ) return Promise . reject ( { code : 400 , message : '{UserRepo} User already exists' } ) ; if ( ! data . _id || data . _id === 'new' ) delete data . _id ; data . created = new Date ( ) ; user = await new this . _model ( data ) . save ( ) ; if ( user instanceof Error ) return Promise . reject ( { code : 400 , message : '{UserRepo} Error with save newUser into Users._model' , stack : user } ) ; return { user } ; } }