import Axios, { AxiosInstance } from 'axios' import { Account, Password, Stack, Transaction, User, uuid } from '../types' import { JWT, setJWT, wipeJWT } from '../utils/jwt' import { DataBuddy } from '@dank-inc/data-buddy' import { users, accounts, stacks, transactions } from './data' export type ApiParams = { baseURL?: string mock?: boolean } export interface Api { mock?: boolean users: DataBuddy accounts: DataBuddy stacks: DataBuddy transactions: DataBuddy axios: AxiosInstance } export class Api { constructor({ mock, baseURL }: ApiParams) { this.mock = mock this.users = users this.accounts = accounts this.stacks = stacks this.transactions = transactions this.axios = Axios.create({ baseURL }) } login = async (name: string, password: string): Promise => { if (this.mock) { const jwt = { id: 'mock-user', token: 'token-token-token', exp: +new Date(), } setJWT(jwt) return jwt } const { data } = await this.axios.post(`/dj-rest-auth/login/`, { name, password, }) setJWT(data) return data } logout = () => { if (this.mock) return true wipeJWT() } getUser = async (id: uuid) => { if (this.mock) return this.users.getOne(id) const { data } = await this.axios.get(`users/${id}`) return data } updateUser = async (id: uuid, body: Partial) => { if (this.mock) return this.users.update(id, body) const { data } = await this.axios.patch(`users/${id}`, body) return data } createUser = async (body: Omit & Password) => { const { data } = await this.axios.post(`users`, body) return data } getAccounts = async () => { if (this.mock) return this.accounts.get() const { data } = await this.axios.get('accounts') return data } getAccount = async (id: uuid) => { if (this.mock) return this.accounts.getOne(id) const data = await this.axios.get(`accounts/${id}`) return data } updateAccount = async (id: uuid, body: Partial) => { const { data } = await this.axios.patch(`accounts/${id}`, body) return data } createAccount = async (body: Omit) => { const { data } = await this.axios.post('accounts', body) return data } deleteAccount = async () => {} getStacks = async (): Promise => { if (this.mock) return this.stacks.get() const { data } = await this.axios.get('stacks') return data } updateStack = async (id: uuid, body: Partial) => { const { data } = await this.axios.patch(`stacks/${id}`, body) return data } createStack = async () => {} deleteStack = async () => {} getTransactions = async () => { if (this.mock) return this.transactions.get() const { data } = await this.axios.get('transactions') return data } updateTransaction = async (id: uuid, body: Partial) => { const { data } = await this.axios.patch( `transactions/${id}`, body, ) return data } createTransaction = async (body: Omit) => { const { data } = await this.axios.post('transactions', body) return data } deleteTransaction = async () => {} } export const logOut = async () => { wipeJWT() }