import { ModelClient, isAPIError, getErrorMessage, isValidationError, getValidationErrorMessage } from '../client/model-client'; import { User, PatchedUser } from './user'; export interface Credentials { access: string; refresh: string | undefined; } export function isCredentials(data: any): data is Credentials { return data && data.access; } export interface PAT { pat: string; } export function isPAT(data: any): data is PAT { return data && data.pat; } export class UserClient extends ModelClient { pluralName = 'users'; async logout() { const url = '/v1/tokens'; return this.client.delete(url); } async login( email: string, password: string, rememberMe = false ): Promise { if (rememberMe) { return await this.generatePAT(email, password); } const url = `/${this.version}/tokens`; const response = await this.client.post(url, { email, password }); if (isValidationError(response.data)) { throw new Error(getValidationErrorMessage(response.data)); } if (isAPIError(response.data)) { throw new Error(getErrorMessage(response.data)); } if (!isCredentials(response.data)) { throw new Error('Unexpected response for tokens!'); } return response.data; } async generatePAT(email: string, password: string): Promise { const url = `/${this.version}/tokens/pat`; const response = await this.client.post(url, { email, password }); if (isAPIError(response.data)) { throw new Error(getErrorMessage(response.data)); } if (!isPAT(response.data)) { throw new Error('Unexpected response for tokens!'); } return response.data; } }