Skip to content

Commit adaca80

Browse files
Merge pull request #146 from lygstate/master
The buildUrlParams should filter out routeParams & bodyParams. (NEEDS REFACTOR AND TETING)
2 parents 792bb13 + 5958195 commit adaca80

File tree

4 files changed

+89
-64
lines changed

4 files changed

+89
-64
lines changed

lib/angular2/index.js

Lines changed: 51 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,7 @@ module.exports = function generate(ctx) {
404404
{ module: 'LoopBackAuth', from: './auth.service'},
405405
{ module: 'LoopBackConfig', from: '../../lb.config'},
406406
{ module: 'AccessToken', from: '../../models'},
407+
{ module: 'Observable', from: 'rxjs/Observable' },
407408
{ module: 'ErrorObservable', from: 'rxjs/observable/ErrorObservable' },
408409
{ module: 'rxjs/add/operator/catch' },
409410
{ module: 'rxjs/add/operator/map' },
@@ -498,20 +499,46 @@ module.exports = function generate(ctx) {
498499
}
499500
return output.join(', ');
500501
}
502+
/**
503+
* @method paramIsRoute
504+
* @description
505+
* Testing if the param is route type
506+
*/
507+
function paramIsRoute(param) {
508+
return (param.http && param.http.source === 'path') || (param.arg && param.arg.match(/(id|fk|file|container)/));
509+
}
510+
/**
511+
* @method paramIsFunction
512+
* @description
513+
* Testing if the param is function type
514+
*/
515+
function paramIsFunction(param) {
516+
return typeof param.http === 'function'
517+
}
501518
/**
502519
* @method buildPostBody
503520
* @description
504521
* Define which properties should be passed while posting data (POST, PUT, PATCH)
505522
*/
506523
function buildPostBody(postData) {
507524
let output = [];
508-
if (postData && postData.length > 0) {
509-
output.push('');
510-
let l = postData.length;
511-
postData.forEach((property, i) => {
512-
output.push(` ${property.arg}: ${property.arg}${(i < l - 1) ? ',' : ''}`);
513-
});
514-
output.push(' ');
525+
if (Array.isArray(postData)) {
526+
postData = postData.filter(param => {
527+
// Filter out route params and function params
528+
if (paramIsRoute(param) || paramIsFunction(param)) {
529+
return false
530+
}
531+
// Make sure the param is body
532+
return param.http && param.http.source == 'body'
533+
})
534+
if (postData.length > 0) {
535+
output.push('');
536+
let l = postData.length;
537+
postData.forEach((property, i) => {
538+
output.push(` ${property.arg}: ${property.arg}${(i < l - 1) ? ',' : ''}`);
539+
});
540+
output.push(' ');
541+
}
515542
}
516543
return output.join('\n');
517544
}
@@ -523,7 +550,14 @@ module.exports = function generate(ctx) {
523550
function buildUrlParams(model, methodName, urlParams) {
524551
let output = [''];
525552
// filter params that should not go over url query string
526-
urlParams = urlParams.filter(param => (param.arg && !param.arg.match(/(id|fk|data|options|credentials)/g)));
553+
urlParams = urlParams.filter(param => {
554+
// Filter out route params and function params
555+
if (paramIsRoute(param) || paramIsFunction(param)) {
556+
return false
557+
}
558+
// Filter out body params
559+
return (!param.http || param.http.source != 'body')
560+
});
527561
if (model.isUser && methodName === 'logout')
528562
output.push(` urlParams.access_token = this.auth.getAccessTokenId();`);
529563
if (urlParams && urlParams.length > 0) {
@@ -540,12 +574,15 @@ module.exports = function generate(ctx) {
540574
*/
541575
function buildRouteParams(routeParams) {
542576
let output = [];
543-
if (routeParams && routeParams.length > 0) {
544-
output.push('');
545-
routeParams.forEach((param, i) => {
546-
output.push(` ${param.arg}: ${param.arg}${(i < routeParams.length - 1) ? ',' : ''}`);
547-
});
548-
output.push(' ');
577+
if (routeParams) {
578+
routeParams = routeParams.filter(paramIsRoute)
579+
if (routeParams.length > 0) {
580+
output.push('');
581+
routeParams.forEach((param, i) => {
582+
output.push(` ${param.arg}: ${param.arg}${(i < routeParams.length - 1) ? ',' : ''}`);
583+
});
584+
output.push(' ');
585+
}
549586
}
550587
return output.join('\n');
551588
}

lib/angular2/shared/services/core/base.ejs

Lines changed: 33 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ export abstract class BaseLoopBackApi {
1717
protected path: string;
1818

1919
constructor(
20-
@Inject(Http) protected http: Http,
21-
@Inject(LoopBackAuth) protected auth: LoopBackAuth,
22-
@Inject(JSONSearchParams) protected searchParams: JSONSearchParams,
20+
@Inject(Http) protected http: Http,
21+
@Inject(LoopBackAuth) protected auth: LoopBackAuth,
22+
@Inject(JSONSearchParams) protected searchParams: JSONSearchParams,
2323
@Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler
2424
) {}
2525

@@ -37,11 +37,9 @@ export abstract class BaseLoopBackApi {
3737
url : string,
3838
routeParams : any = {},
3939
urlParams : any = {},
40-
postBody : any = null<% if ( isIo === 'enabled' ){ -%>,
41-
isio : boolean = false<% }
42-
-%>
43-
44-
) {
40+
postBody : any = null,
41+
isio : boolean = false
42+
): Observable<any> {
4543

4644
let headers = new Headers();
4745
headers.append('Content-Type', 'application/json');
@@ -61,8 +59,8 @@ export abstract class BaseLoopBackApi {
6159
routeParams[key] + "$1"
6260
);
6361
}
64-
6562
<% if ( isIo === 'enabled' ){ -%>
63+
6664
if (isio) {
6765
if (requestUrl.match(/fk/)) {
6866
let arr = requestUrl.split('/'); arr.pop();
@@ -76,35 +74,31 @@ export abstract class BaseLoopBackApi {
7674
let socket: any = SocketConnections.getHandler(LoopBackConfig.getPath(), token);
7775
socket.on(event, (res: any) => subject.next(res));
7876
return subject.asObservable();
79-
} else {<% } -%>
80-
// Body fix for built in remote methods using "data", "options" or "credentials
81-
// that are the actual body, Custom remote method properties are different and need
82-
// to be wrapped into a body object
83-
let body: any;
84-
if (
85-
typeof postBody === 'object' &&
86-
(postBody.data || postBody.credentials || postBody.options) &&
87-
Object.keys(postBody).length === 1
88-
) {
89-
body = postBody.data ? postBody.data :
90-
postBody.options ? postBody.options :
91-
postBody.credentials;
92-
} else {
93-
body = postBody;
94-
}
95-
this.searchParams.setJSON(urlParams);
96-
let request: Request = new Request({
97-
headers : headers,
98-
method : method,
99-
url : urlParams.filter ? `${requestUrl}?filter=${ encodeURI(JSON.stringify(urlParams.filter))}`
100-
: requestUrl,
101-
search : !urlParams.filter && Object.keys(urlParams).length > 0
102-
? this.searchParams.getURLSearchParams() : null,
103-
body : body ? JSON.stringify(body) : undefined
104-
});
105-
return this.http.request(request)
106-
.map((res: any) => (res.text() != "" ? res.json() : {}))
107-
.catch(this.errorHandler.handleError);
108-
<% if ( isIo === 'enabled' ){ -%> }<% } -%>
77+
}
78+
<% } -%>
79+
80+
// Body fix for built in remote methods using "data", "options" or "credentials
81+
// that are the actual body, Custom remote method properties are different and need
82+
// to be wrapped into a body object
83+
let body: any;
84+
let postBodyKeys = typeof postBody === 'object' ? Object.keys(postBody) : []
85+
if (postBodyKeys.length === 1) {
86+
body = postBody[postBodyKeys[0]]
87+
} else {
88+
body = postBody;
89+
}
90+
this.searchParams.setJSON(urlParams);
91+
let request: Request = new Request({
92+
headers : headers,
93+
method : method,
94+
url : urlParams.filter ? `${requestUrl}?filter=${ encodeURI(JSON.stringify(urlParams.filter))}`
95+
: requestUrl,
96+
search : !urlParams.filter && Object.keys(urlParams).length > 0
97+
? this.searchParams.getURLSearchParams() : null,
98+
body : body ? JSON.stringify(body) : undefined
99+
});
100+
return this.http.request(request)
101+
.map((res: any) => (res.text() != "" ? res.json() : {}))
102+
.catch(this.errorHandler.handleError);
109103
}
110104
}

lib/angular2/shared/services/core/error.ejs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
import { Injectable } from '@angular/core';
33
import { Response } from '@angular/http';
44
import { Observable } from 'rxjs/Observable';
5+
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
56
import 'rxjs/add/observable/throw';
67
/**
78
* Default error handler
89
*/
910
@Injectable()
1011
export class ErrorHandler {
11-
public handleError(error: Response) {
12+
public handleError(error: Response): ErrorObservable {
1213
return Observable.throw(error.json().error || 'Server error');
1314
}
1415
}

lib/angular2/shared/services/custom/service.ejs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,21 +52,14 @@ export class <%-: modelName %>Api extends BaseLoopBackApi {
5252
}
5353
5454
// SET URL PARAMS
55-
var urlParams = action.accepts.filter(function(param) {
56-
return !(param.arg === "access_token" && methodName === "logout") && !(param.http && param.http.source === 'path');
57-
});
55+
var urlParams = action.accepts;
5856
// SET POST BODY
5957
var postData;
6058
if (httpVerb == 'POST' || httpVerb == 'PUT' || httpVerb == 'PATCH') {
61-
postData = action.accepts.filter(function(param) {
62-
return !(param.http && (param.http.source == 'query' || param.http.source == 'path'))
63-
&& !(param.arg === "access_token" && methodName === "logout");
64-
});
59+
postData = action.accepts;
6560
}
6661
// SET ROUTE PARAMS
67-
var routeParams = action.accepts.filter(function(param) {
68-
return (param.http && param.http.source === 'path') || (param.arg && param.arg.match(/(id|fk|file|container)/));
69-
});
62+
var routeParams = action.accepts
7063
-%>
7164
public <%- normalizeMethodName(methodName) %>(<%- buildMethodParams(model, methodName, action.accepts) %>): Observable<<%- buildObservableType(modelName, methodName) %>> {
7265
let method: string = <%-: httpVerb | q %>;

0 commit comments

Comments
 (0)