added fake-backend for login and registration testing

This commit is contained in:
2020-07-21 15:17:51 +02:00
parent d9935d2dd1
commit 1e9b5817ab
2 changed files with 80 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
import { FakeBackend } from './fake-backend';
describe('FakeBackend', () => {
it('should create an instance', () => {
expect(new FakeBackend()).toBeTruthy();
});
});

View File

@@ -0,0 +1,73 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';
let users = JSON.parse(localStorage.getItem('users')) || [];
@Injectable()
export class FakeBackend implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { url, method, headers, body } = request;
return of(null)
.pipe(mergeMap(handleRoute))
.pipe(materialize())
.pipe(delay(500))
.pipe(dematerialize());
function handleRoute() {
switch (true) {
case url.endsWith('fake_login') && method === 'POST':
return authenticate();
case url.endsWith('fake_registration') && method === 'POST':
return register();
default:
return next.handle(request);
}
}
function authenticate() {
const { username, password } = body;
const user = users.find(x => x.username === username.value && x.password === password.value);
if (!user) {
console.log(password);
return error('Username or password is incorrect.');
}
return ok({
id: user.id,
username: user.username,
token: 'fake-jwt-token',
});
}
function register() {
const user = body;
if (users.find(x => x.username === user.username)) {
return error('Username ' + user.username + ' is already taken.');
}
user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1;
users.push(user);
localStorage.setItem('users', JSON.stringify(users));
console.log('Register user: ' + user);
return ok();
}
function ok(body?) {
return of(new HttpResponse({ status: 200, body }));
}
function error(message) {
return throwError({ error: { message } });
}
}
}
export const fakeBackendProvider = {
provide: HTTP_INTERCEPTORS,
useClass: FakeBackend,
multi: true,
}