import { BaseModel } from './base'; import { RequestApi, User as UserRequestModel, FormInitOptions, } from '../requests'; import { Store } from './store'; import { ApiKeys, UserData, Id, CredentialsData, PersonData, AddressData, LoanPartData, CreditData, KycData, TinkLoanData, TinkAccountData, } from '../types'; import { Keys, USER_LITERAL } from './entities'; import { hasMany, HasMany } from './has-many'; @hasMany({ relationKey: 'forms', foreignKey: 'userId', storeKey: Keys.forms, }) @hasMany({ relationKey: 'persons', foreignKey: 'userId', storeKey: Keys.persons, }) @hasMany({ relationKey: 'addresses', foreignKey: 'userId', storeKey: Keys.addresses, }) @hasMany({ relationKey: 'loanParts', foreignKey: 'userId', storeKey: Keys.loanParts, }) @hasMany({ relationKey: 'credits', foreignKey: 'userId', storeKey: Keys.credits, }) @hasMany({ relationKey: 'kycs', foreignKey: 'userId', storeKey: Keys.kycs, }) @hasMany({ relationKey: 'tinkLoans', foreignKey: 'userId', storeKey: Keys.tinkLoans, }) @hasMany({ relationKey: 'tinkAccounts', foreignKey: 'userId', storeKey: Keys.tinkAccounts, }) export class UserModel extends BaseModel { constructor(requestApi: RequestApi, store: Store) { super(requestApi[ApiKeys.USERS], Keys.users, store); } async login(credentials: CredentialsData) { const { login } = this._requestModel; const data = await login(credentials); if (data && data.user && data.user.id) { this._store.set(Keys.userLiteral, { [USER_LITERAL]: data.user.id }); } return data; } async anonymousLogin() { const { anonymousLogin } = this._requestModel; return anonymousLogin(); } private _getId(potentialId: Id) { if (potentialId === USER_LITERAL) { const me = this._store.get(Keys.userLiteral, USER_LITERAL); if (me && me[USER_LITERAL]) { return me[USER_LITERAL]; } } return potentialId; } async formInit(id: Id, opts?: FormInitOptions) { const userId = this._getId(id); const { formInit } = this._requestModel; const form = await formInit(userId, opts); this._store.set(Keys.forms, form, {deep: false}); return form; } async lookUpPerson(id: Id, ssn: string) { const { lookUpPerson } = this._requestModel; const userId = this._getId(id); const person = await lookUpPerson(userId, ssn); this._store.set(Keys.persons, person, { deep: false }); return person; } } type UserRelations = { forms: HasMany; persons: HasMany; addresses: HasMany; loanParts: HasMany; credits: HasMany; kycs: HasMany; tinkLoans: HasMany; tinkAccounts: HasMany; }; export type UserType = UserModel & UserRelations;