Skip to content

Commit

Permalink
add auth service register
Browse files Browse the repository at this point in the history
  • Loading branch information
juancwu committed Dec 5, 2024
1 parent 970a130 commit b91b372
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
54 changes: 54 additions & 0 deletions frontend/src/services/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* This file contains business logic regarding authentication.
*/

import { getApiUrl, HttpStatusCode } from '@utils';
import { RegisterError } from './errors';

import type { User, UserRole } from '@t';

export interface RegisterReponse {
accessToken: string;
refreshToken: string;
user: User;
}

/**
* Registers a user if the given email is not already registered.
*/
export async function register(
email: string,
password: string,
role: UserRole = 'startup_owner'
): Promise<RegisterReponse> {
const url = getApiUrl('/auth/signup');
const body = {
email,
password,
role,
};

const res = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
},
});
// the backend should always return json for the api calls
const json = await res.json();

if (res.status !== HttpStatusCode.CREATED) {
throw new RegisterError('Failed to register', res.status, json);
}

return json as RegisterReponse;
}

/**
* Saves the refresh token in localStorage.
*/
export function saveRefreshToken(refreshToken: string) {
// IMPORTANT: The location on where the token is saved must be revisited.
localStorage.setItem('refresh_token', refreshToken);
}
22 changes: 22 additions & 0 deletions frontend/src/services/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export const API_ERROR = 'ApiError';
export const REGISTER_ERROR = 'RegisterError';

export class ApiError extends Error {
// statusCode represents the status of the response
public statusCode: number;
public body: any;

constructor(message: string, statusCode: number, body: any) {
super(message);
this.name = API_ERROR;
this.statusCode = statusCode;
this.body = body;
}
}

export class RegisterError extends ApiError {
constructor(message: string, statusCode: number, body: any) {
super(message, statusCode, body);
this.name = REGISTER_ERROR;
}
}
2 changes: 2 additions & 0 deletions frontend/src/services/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { register, saveRefreshToken } from './auth';
export { RegisterError, ApiError, API_ERROR, REGISTER_ERROR } from './errors';

0 comments on commit b91b372

Please sign in to comment.