Skip to content

Small fixes and make it work with webpack #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 132 additions & 130 deletions app/_helpers/fake-backend.ts
Original file line number Diff line number Diff line change
@@ -1,154 +1,156 @@
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod, XHRBackend, RequestOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions, realBackend: XHRBackend) => {
// array in local storage for registered users
let users: any[] = JSON.parse(localStorage.getItem('users')) || [];

// configure fake backend
backend.connections.subscribe((connection: MockConnection) => {
// wrap in timeout to simulate server api call
setTimeout(() => {

// authenticate
if (connection.request.url.endsWith('/api/authenticate') && connection.request.method === RequestMethod.Post) {
// get parameters from post request
let params = JSON.parse(connection.request.getBody());

// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});

if (filteredUsers.length) {
// if login details are valid return 200 OK with user details and fake jwt token
let user = filteredUsers[0];
connection.mockRespond(new Response(new ResponseOptions({
status: 200,
body: {
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
}
})));
} else {
// else return 400 bad request
connection.mockError(new Error('Username or password is incorrect'));
}
function fakeBackendFactory(backend: MockBackend, options: BaseRequestOptions, realBackend: XHRBackend) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still I can see the error

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested it in Plunker, there was no error. What error do you get?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ERROR in Error encountered resolving symbol values statically. Reference to a non-exported function (position 4:10 in the original .ts file), resolving symbol fakeBackendProvider in ...

Copy link
Author

@yktoo yktoo Feb 12, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, perhaps this function needs to be exported too (works for me with webpack as it is). Anyway, the first commit is safe to merge, the second one may be a bit controversial.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simply it should be export function fakeBackendFactory()

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Shall I add commit this one?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested the change and it seems good.

// array in local storage for registered users
let users: any[] = JSON.parse(localStorage.getItem('users')) || [];

// configure fake backend
backend.connections.subscribe((connection: MockConnection) => {
// wrap in timeout to simulate server api call
setTimeout(() => {

// authenticate
if (connection.request.url.endsWith('/api/authenticate') && connection.request.method === RequestMethod.Post) {
// get parameters from post request
let params = JSON.parse(connection.request.getBody());

// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});

return;
if (filteredUsers.length) {
// if login details are valid return 200 OK with user details and fake jwt token
let user = filteredUsers[0];
connection.mockRespond(new Response(new ResponseOptions({
status: 200,
body: {
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
}
})));
} else {
// else return 400 bad request
connection.mockError(new Error('Username or password is incorrect'));
}

// get users
if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Get) {
// check for fake auth token in header and return users if valid, this security is implemented server side in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: users })));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(new ResponseOptions({ status: 401 })));
}

return;
return;
}

// get users
if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Get) {
// check for fake auth token in header and return users if valid, this security is implemented server side in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: users })));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(new ResponseOptions({ status: 401 })));
}

// get user by id
if (connection.request.url.match(/\/api\/users\/\d+$/) && connection.request.method === RequestMethod.Get) {
// check for fake auth token in header and return user if valid, this security is implemented server side in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
// find user by id in users array
let urlParts = connection.request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
let matchedUsers = users.filter(user => { return user.id === id; });
let user = matchedUsers.length ? matchedUsers[0] : null;

// respond 200 OK with user
connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: user })));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(new ResponseOptions({ status: 401 })));
}

return;
return;
}

// get user by id
if (connection.request.url.match(/\/api\/users\/\d+$/) && connection.request.method === RequestMethod.Get) {
// check for fake auth token in header and return user if valid, this security is implemented server side in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
// find user by id in users array
let urlParts = connection.request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
let matchedUsers = users.filter(user => { return user.id === id; });
let user = matchedUsers.length ? matchedUsers[0] : null;

// respond 200 OK with user
connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: user })));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(new ResponseOptions({ status: 401 })));
}

// create user
if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Post) {
// get new user object from post body
let newUser = JSON.parse(connection.request.getBody());

// validation
let duplicateUser = users.filter(user => { return user.username === newUser.username; }).length;
if (duplicateUser) {
return connection.mockError(new Error('Username "' + newUser.username + '" is already taken'));
}

// save new user
newUser.id = users.length + 1;
users.push(newUser);
localStorage.setItem('users', JSON.stringify(users));
return;
}

// respond 200 OK
connection.mockRespond(new Response(new ResponseOptions({ status: 200 })));
// create user
if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Post) {
// get new user object from post body
let newUser = JSON.parse(connection.request.getBody());

return;
// validation
let duplicateUser = users.filter(user => { return user.username === newUser.username; }).length;
if (duplicateUser) {
return connection.mockError(new Error('Username "' + newUser.username + '" is already taken'));
}

// delete user
if (connection.request.url.match(/\/api\/users\/\d+$/) && connection.request.method === RequestMethod.Delete) {
// check for fake auth token in header and return user if valid, this security is implemented server side in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
// find user by id in users array
let urlParts = connection.request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
for (let i = 0; i < users.length; i++) {
let user = users[i];
if (user.id === id) {
// delete user
users.splice(i, 1);
localStorage.setItem('users', JSON.stringify(users));
break;
}
// save new user
newUser.id = users.length + 1;
users.push(newUser);
localStorage.setItem('users', JSON.stringify(users));

// respond 200 OK
connection.mockRespond(new Response(new ResponseOptions({ status: 200 })));

return;
}

// delete user
if (connection.request.url.match(/\/api\/users\/\d+$/) && connection.request.method === RequestMethod.Delete) {
// check for fake auth token in header and return user if valid, this security is implemented server side in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
// find user by id in users array
let urlParts = connection.request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
for (let i = 0; i < users.length; i++) {
let user = users[i];
if (user.id === id) {
// delete user
users.splice(i, 1);
localStorage.setItem('users', JSON.stringify(users));
break;
}

// respond 200 OK
connection.mockRespond(new Response(new ResponseOptions({ status: 200 })));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(new ResponseOptions({ status: 401 })));
}

return;
// respond 200 OK
connection.mockRespond(new Response(new ResponseOptions({ status: 200 })));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(new ResponseOptions({ status: 401 })));
}

// pass through any requests not handled above
let realHttp = new Http(realBackend, options);
let requestOptions = new RequestOptions({
method: connection.request.method,
headers: connection.request.headers,
body: connection.request.getBody(),
url: connection.request.url,
withCredentials: connection.request.withCredentials,
responseType: connection.request.responseType
return;
}

// pass through any requests not handled above
let realHttp = new Http(realBackend, options);
let requestOptions = new RequestOptions({
method: connection.request.method,
headers: connection.request.headers,
body: connection.request.getBody(),
url: connection.request.url,
withCredentials: connection.request.withCredentials,
responseType: connection.request.responseType
});
realHttp.request(connection.request.url, requestOptions)
.subscribe((response: Response) => {
connection.mockRespond(response);
},
(error: any) => {
connection.mockError(error);
});
realHttp.request(connection.request.url, requestOptions)
.subscribe((response: Response) => {
connection.mockRespond(response);
},
(error: any) => {
connection.mockError(error);
});

}, 500);
}, 500);

});

});
return new Http(backend, options);
}

return new Http(backend, options);
},
export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: Http,
useFactory: fakeBackendFactory,
deps: [MockBackend, BaseRequestOptions, XHRBackend]
};
};
4 changes: 2 additions & 2 deletions app/login/login.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ <h2>Login</h2>
<form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
<input type="text" class="form-control" id="username" name="username" [(ngModel)]="model.username" #username="ngModel" required />
<div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
<input type="password" class="form-control" id="password" name="password" [(ngModel)]="model.password" #password="ngModel" required />
<div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
</div>
<div class="form-group">
Expand Down
12 changes: 6 additions & 6 deletions app/register/register.component.html
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
<div class="col-md-6 col-md-offset-3">
<h2>Register</h2>
<form name="form" (ngSubmit)="f.form.valid && register()" #f="ngForm" novalidate>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !firstName.valid }">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" [(ngModel)]="model.firstName" #firstName="ngModel" required />
<input type="text" class="form-control" id="firstName" name="firstName" [(ngModel)]="model.firstName" #firstName="ngModel" required />
<div *ngIf="f.submitted && !firstName.valid" class="help-block">First Name is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !lastName.valid }">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" name="lastName" [(ngModel)]="model.lastName" #lastName="ngModel" required />
<input type="text" class="form-control" id="lastName" name="lastName" [(ngModel)]="model.lastName" #lastName="ngModel" required />
<div *ngIf="f.submitted && !lastName.valid" class="help-block">Last Name is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
<input type="text" class="form-control" id="username" name="username" [(ngModel)]="model.username" #username="ngModel" required />
<div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
<input type="password" class="form-control" id="password" name="password" [(ngModel)]="model.password" #password="ngModel" required />
<div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
</div>
<div class="form-group">
Expand Down