UNPKG

dbl-coins-invest

Version:

Sharade DBL package over other coins invest services

159 lines (147 loc) 4.75 kB
import { Investment, Portfolio, User, Account } from "./models"; import Rx from 'rxjs'; import DBL from "./dbl"; import AccountService from "./account"; import InvestmentService from "./investments"; import * as Sequelize from "sequelize"; const Op = Sequelize.Op; export default class PortfolioService extends DBL { constructor(userSub) { if (!userSub) throw new Error('userSub have to be provided!!!!'); super(); this.userSub = userSub; this.model = Portfolio; this.investmentService = new InvestmentService(userSub); this.accountServise = new AccountService(userSub); } addInvestment(portfolioId, investment) { return Rx.Observable.forkJoin( this.investmentService.create(investment), this.getById(portfolioId) ) .mergeMap(([investModel, portfolioModel]) => { return Rx.Observable.fromPromise(portfolioModel.addInvestments(investModel)) }) } getAll() { return Rx.Observable.fromPromise(Account.findOne({ where: { userSub: { [Op.eq]: this.userSub } }, include: [ { model: Portfolio, as: 'Portfolios', } ] })).map((account) => { if (!account) { return Rx.Observable.throw('noAccountFound'); } return account.get('Portfolios'); }); } createPortfolio(portfolio) { return Rx.Observable.forkJoin( this.accountServise.getUserAccount(), this.model.create(portfolio) ) .mergeMap((response) => { let [_account, _portfolio] = response; return Rx.Observable.fromPromise(_account.addPortfolios(_portfolio)) .map((account) => { return _portfolio; }); }); } getById(portfolioId) { return Rx.Observable.fromPromise(Account.findOne({ where: { userSub: { [Op.eq]: this.userSub } }, include: [ { model: Portfolio, as: 'Portfolios', where: { id: { [Op.eq]: portfolioId }, } } ] })).map((account) => { return account.get('Portfolios')[0]; }); } delete(portfolioId) { return this.getById(portfolioId) .mergeMap((portfolioModel) => { return Rx.Observable.fromPromise( portfolioModel.destroy() ); }) } //TODO should return investments!!! getInvestments(portfolioId) { return Rx.Observable.fromPromise(Account.findOne({ where: { userSub: {[Op.eq]: this.userSub} }, include: [ { model: Portfolio, as: 'Portfolios', where: { id: { [Op.eq]: portfolioId }, }, include: [{model: Investment, as: 'Investments'}] } ] })).map((account) => { return account.get('Portfolios')[0].get('Investments') }); } removeInvestment(portfolioId, investId) { return Rx.Observable.fromPromise(Account.findOne({ where: { userSub: {[Op.eq]: this.userSub} }, include: [ { model: Portfolio, as: 'Portfolios', where: { id: { [Op.eq]: portfolioId }, }, include: [{ model: Investment, as: 'Investments', where: { id: { [Op.eq]: investId }, }, }] } ] })) .mergeMap((account) => { return Rx.Observable.fromPromise( account.get('Portfolios')[0].get('Investments')[0].destroy() ); }) .mergeMap((resp) => { return this.getInvestments(portfolioId); }); } }