Skip to content
Snippets Groups Projects
Commit 93892139 authored by Jonny Ngo Luong's avatar Jonny Ngo Luong
Browse files

feat: add user registration form and request (#8)

parent 69d582ec
No related branches found
No related tags found
No related merge requests found
......@@ -4,6 +4,9 @@
<a href="/">/</a>
<a href="/annonse">/annonse</a>
<a href="/annonse/ny">/annonse/ny</a>
<a href="/register">/register</a>
<a href="/login">/login</a>
<a href="/profile">/profile</a>
</nav>
</div>
......
......@@ -2,7 +2,7 @@ import { Deserializable } from "./deserializable.model";
import { Serializable } from "./serializable.model";
export class User implements Deserializable, Serializable {
private userid: number;
private userId: number;
private username: string;
private email: string;
private password: string;
......@@ -12,7 +12,7 @@ export class User implements Deserializable, Serializable {
if (input) {
this.deserialize(input);
} else {
this.userid = 0;
this.userId = 0;
this.username = null;
this.email = null;
this.password = null;
......@@ -22,12 +22,13 @@ export class User implements Deserializable, Serializable {
deserialize(input: Object): this {
Object.assign(this, input);
console.log(this);
return this;
}
serialize(): Object {
return {
userid: this.userid,
userId: this.userId,
username: this.username,
email: this.email,
password: this.password,
......@@ -36,11 +37,11 @@ export class User implements Deserializable, Serializable {
}
get getUserId() {
return this.userid;
return this.userId;
}
set setUserId(userid: number) {
this.userid = userid;
set setUserId(userId: number) {
this.userId = userId;
}
get getUsername() {
......
<p>user-registration-form works!</p>
<div class="registrationForm">
<h3>Register en bruker</h3>
<app-text-input [(inputModel)]="username" label="Brukernavn" (blur)="checkForm()"></app-text-input>
<app-text-input [(inputModel)]="email" label="Epost" (blur)="checkForm()"></app-text-input>
<app-text-input [(inputModel)]="password" label="Passord" (blur)="checkForm()"></app-text-input>
<p>{{statusMessage}}</p>
<app-button (click)="registerUser()" text="Register"></app-button>
</div>
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from 'src/app/models/user.model';
import { UserService } from '../user.service';
@Component({
selector: 'app-user-registration-form',
......@@ -6,10 +9,63 @@ import { Component, OnInit } from '@angular/core';
styleUrls: ['./user-registration-form.component.scss']
})
export class UserRegistrationFormComponent implements OnInit {
username: string = "";
email: string = "";
password: string = "";
constructor() { }
statusMessage: string = "";
constructor(private userService: UserService, private router: Router) { }
ngOnInit(): void {
}
/**
* Validates form.
*/
checkForm(): boolean {
if (this.username == "") {
this.setStatusMessage("Brukernavn kan ikke være tom");
return false;
}
else if (this.email == "") {
this.setStatusMessage("Eposten kan ikke være tom");
return false;
}
else if (this.password == "") {
this.setStatusMessage("Passordet kan ikke være tom");
return false;
}
this.setStatusMessage("");
return true;
}
/**
* Publishes user if it is valid.
*/
registerUser() {
if (this.checkForm()) {
const newUser = new User({
username: this.username,
email: this.email,
password: this.password,
});
// Adds user to database and changes page afterwards
this.userService.addUser(newUser).then(status => {
console.log("User was added: " + status);
this.router.navigateByUrl("/");
}).catch(error => {
console.log("Error adding user: " + error);
});
}
}
/**
* Sets a status message.
*/
setStatusMessage(message: string) {
this.statusMessage = message;
}
}
......@@ -5,6 +5,126 @@ import { User } from '../models/user.model';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
service = TestBed.inject(UserService);
httpMock = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('getUser', () => {
it('should get an user', () => {
// Gets post and checks values
service.getUser(1).then(user => {
expect(user.getUserId).toBe(1);
expect(user.getUsername).toBe("zorg");
}).catch(error => {
fail();
});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/1");
expect(req.request.method).toBe("GET");
req.flush({
data: [{
userId: 1,
username: "zorg",
email: "blob@planet.us",
password: "Hyttepine",
create_time: 1613552549000,
}]
});
});
it('should reject on invalid user', () => {
// Gets invalid post, should go to catch
service.getUser(2).then(user => {
fail();
}).catch(error => {});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/2");
expect(req.request.method).toBe("GET");
req.flush({
data: [{
userId: 0,
username: "zorg",
email: "blob@planet.us",
password: "Hyttepine",
}]
});
});
it('should reject on http error', () => {
// Gets HTTP error instead of post, should catch
service.getUser(2).then(user => {
fail();
}).catch(error => {});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/2");
expect(req.request.method).toBe("GET");
req.error(new ErrorEvent("400"));
});
});
describe('addUser', () => {
it('should add an user', () => {
const user = new User({
userId: 1,
username: "zorg",
email: "blob@planet.us",
password: "Hyttepine",
create_time: 1613552549000,
});
// Adds user
service.addUser(user)
.then(post => {})
.catch(error => {
fail();
});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/");
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual(user.serialize());
req.flush({
data: [{
status: "success"
}]
});
});
it('should reject on http error', () => {
const user = new User({
userId: 1,
username: "zorg",
email: "blob@planet.us",
password: "Hyttepine",
create_time: 1613552549000,
});
// Adds user, gets HTTP error, should catch
service.addUser(user).then(user => {
fail();
}).catch(error => {});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/");
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual(user.serialize());
req.error(new ErrorEvent("400"));
});
});
});
......@@ -7,10 +7,65 @@ import { User } from '../models/user.model';
})
export class UserService {
userUrl = "api/post/"
userUrl = "api/user/"
constructor(private http: HttpClient) { }
/**
* Adds user to database.
*/
addUser(user: User): Promise<string> {
return new Promise<string>(
(resolve, reject) => {
this.add_user(user).subscribe((data: any) => {
try {
resolve(data.status);
} catch (err: any) {
reject(err);
}
},
(err: any) => {
console.log(err.message);
reject(err);
});
}
);
}
private add_user(user: User) {
return this.http.post(this.userUrl, user.serialize());
}
/**
* Get post from database by id.
*/
getUser(id: number): Promise<User> {
return new Promise<User>(
(resolve, reject) => {
this.get_user(id).subscribe((data: any) => {
try {
const user = new User(data.data[0]);
if (user.getUserId == 0) {
reject("Could not find User with id: " + id);
return;
}
resolve(user);
} catch (err: any) {
reject(err);
}
},
(err: any) => {
console.log(err.message);
reject(err);
});
}
);
}
private get_user(id: number) {
return this.http.get(this.userUrl + id);
}
/**
* Get all users from database.
*/
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment