Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable, OnInit } from '@angular/core';
- import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
- import { Observable, of, throwError } from 'rxjs';
- import { User } from '@/data/models/property/user';
- import { UserService } from '@/_services/user.service';
- @Injectable()
- export class FakeBackendInterceptor implements HttpInterceptor, OnInit {
- users: User[];
- constructor(private http: HttpClient, private userService: UserService) { }
- ngOnInit() {
- this.getAll();
- }
- private getAll(): void {
- this.userService.getAll()
- .subscribe(data => this.users = data);
- }
- intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
- // authenticate
- if (request.url.endsWith('/users/authenticate') && request.method === 'POST') {
- // find if any user matches login credentials
- const filteredUsers = this.users.filter(user => {
- if (user.email === request.body.email && user.password === request.body.password) {
- return user;
- }
- });
- if (filteredUsers) {
- // if login details are valid return 200 OK with user details and fake jwt token
- const user = filteredUsers[0];
- const body = {
- id: user.id,
- email: user.email,
- firstName: user.firstName,
- lastName: user.lastName,
- studentNo: user.studentNo,
- isStaff: user.isStaff,
- token: 'fake-jwt-token'
- };
- return of(new HttpResponse({ status: 200, body: body }));
- } else {
- // else return 400 bad request
- return throwError({ error: { message: 'Email or password is incorrect' } });
- }
- }
- return next.handle(request);
- }
- }
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { Observable, of } from 'rxjs';
- import { catchError, map, tap } from 'rxjs/operators';
- import { User } from '../data/models/property/user';
- @Injectable({ providedIn: 'root' })
- export class UserService {
- constructor(private http: HttpClient) { }
- getAll(): Observable<User[]> {
- return this.http.get<User[]>('api/users')
- .pipe(
- catchError(this.handleError('getAll', []))
- );
- }
- getById(id: number) {
- return this.http.get(`/users/${id}`);
- }
- register(user: User) {
- return this.http.post(`/users/register`, user);
- }
- update(user: User) {
- return this.http.put(`/users/${user.id}`, user);
- }
- delete(id: number) {
- return this.http.delete(`/users/${id}`);
- }
- private handleError<T>(operation = 'operation', result ?: T) {
- return (error: any): Observable<T> => {
- // TODO: send the error to remote logging infrastructure
- console.error(error.name); // log to console instead
- // Let the app keep running by returning an empty result.
- return of(result as T);
- };
- }
- }
Add Comment
Please, Sign In to add comment