diff --git a/src/app/utils/fake-backend.spec.ts b/src/app/utils/fake-backend.spec.ts new file mode 100644 index 0000000..ac1e6af --- /dev/null +++ b/src/app/utils/fake-backend.spec.ts @@ -0,0 +1,7 @@ +import { FakeBackend } from './fake-backend'; + +describe('FakeBackend', () => { + it('should create an instance', () => { + expect(new FakeBackend()).toBeTruthy(); + }); +}); diff --git a/src/app/utils/fake-backend.ts b/src/app/utils/fake-backend.ts new file mode 100644 index 0000000..dc0a847 --- /dev/null +++ b/src/app/utils/fake-backend.ts @@ -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, next: HttpHandler): Observable> { + 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, +}