initial commit
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
User,
|
||||
LoginResponse,
|
||||
RegisterResponse,
|
||||
SendMessageResponse,
|
||||
} from "./types.js";
|
||||
|
||||
export class APIService {
|
||||
private static readonly baseUrl = "http://webp-ilv-backend.cs.technikum-wien.at/messenger";
|
||||
|
||||
async register ( name: string, email: string, password: string, groupId: string): Promise<RegisterResponse> {
|
||||
const formData = new FormData();
|
||||
formData.append( "name", name );
|
||||
formData.append( "email", email );
|
||||
formData.append( "password", password );
|
||||
formData.append( "group_id", groupId );
|
||||
|
||||
const response = await fetch( `${APIService.baseUrl}/registrieren.php`, {method: "POST", body: formData} );
|
||||
if ( !response.ok ) {
|
||||
throw new Error ( 'Registration failed: ' + response.statusText );
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
let data: RegisterResponse;
|
||||
try {
|
||||
data = JSON.parse( text );
|
||||
} catch {
|
||||
console.error( "Non-JSON response from registrieren.php:", text );
|
||||
throw new Error( "Registration failed: unexpected server response." );
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
async login ( usernameOrEmail: string, password: string): Promise <LoginResponse> {
|
||||
const formData = new FormData();
|
||||
formData.append( "username_or_email", usernameOrEmail );
|
||||
formData.append( "password", password );
|
||||
|
||||
const response = await fetch( `${APIService.baseUrl}/login.php`, {method: "POST", body: formData} );
|
||||
|
||||
if ( !response.ok ) {
|
||||
throw new Error ( 'Login failed: ' + response.statusText );
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
async getUsers ( token: string, userId: string): Promise<User[]> {
|
||||
const url = new URL( `${APIService.baseUrl}/get_users.php` );
|
||||
url.searchParams.set( "token", token );
|
||||
url.searchParams.set( "id", userId );
|
||||
|
||||
const response = await fetch ( url, {method: "GET"} );
|
||||
|
||||
if ( !response.ok ) {
|
||||
throw new Error ( 'Failed to fetch users: ' + response.statusText );
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
async sendMessage ( token: string, senderId: string, receiverId: string, message: string ): Promise <SendMessageResponse> {
|
||||
const formData = new FormData();
|
||||
formData.append( "token", token );
|
||||
formData.append( "sender_id", senderId );
|
||||
formData.append( "receiver_id", receiverId );
|
||||
formData.append( "message", message );
|
||||
|
||||
const response = await fetch( `${APIService.baseUrl}/send_message.php`, {method: "POST", body: formData} );
|
||||
|
||||
if ( !response.ok ) {
|
||||
throw new Error ( 'Failed to send message: ' + response.statusText );
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user