Skip to content

Commit

Permalink
Merge pull request #146 from lygstate/master
Browse files Browse the repository at this point in the history
The buildUrlParams should filter out routeParams & bodyParams.

(NEEDS REFACTOR AND TETING)
  • Loading branch information
jonathan-casarrubias authored Oct 18, 2016
2 parents 792bb13 + 5958195 commit adaca80
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 64 deletions.
65 changes: 51 additions & 14 deletions lib/angular2/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ module.exports = function generate(ctx) {
{ module: 'LoopBackAuth', from: './auth.service'},
{ module: 'LoopBackConfig', from: '../../lb.config'},
{ module: 'AccessToken', from: '../../models'},
{ module: 'Observable', from: 'rxjs/Observable' },
{ module: 'ErrorObservable', from: 'rxjs/observable/ErrorObservable' },
{ module: 'rxjs/add/operator/catch' },
{ module: 'rxjs/add/operator/map' },
Expand Down Expand Up @@ -498,20 +499,46 @@ module.exports = function generate(ctx) {
}
return output.join(', ');
}
/**
* @method paramIsRoute
* @description
* Testing if the param is route type
*/
function paramIsRoute(param) {
return (param.http && param.http.source === 'path') || (param.arg && param.arg.match(/(id|fk|file|container)/));
}
/**
* @method paramIsFunction
* @description
* Testing if the param is function type
*/
function paramIsFunction(param) {
return typeof param.http === 'function'
}
/**
* @method buildPostBody
* @description
* Define which properties should be passed while posting data (POST, PUT, PATCH)
*/
function buildPostBody(postData) {
let output = [];
if (postData && postData.length > 0) {
output.push('');
let l = postData.length;
postData.forEach((property, i) => {
output.push(` ${property.arg}: ${property.arg}${(i < l - 1) ? ',' : ''}`);
});
output.push(' ');
if (Array.isArray(postData)) {
postData = postData.filter(param => {
// Filter out route params and function params
if (paramIsRoute(param) || paramIsFunction(param)) {
return false
}
// Make sure the param is body
return param.http && param.http.source == 'body'
})
if (postData.length > 0) {
output.push('');
let l = postData.length;
postData.forEach((property, i) => {
output.push(` ${property.arg}: ${property.arg}${(i < l - 1) ? ',' : ''}`);
});
output.push(' ');
}
}
return output.join('\n');
}
Expand All @@ -523,7 +550,14 @@ module.exports = function generate(ctx) {
function buildUrlParams(model, methodName, urlParams) {
let output = [''];
// filter params that should not go over url query string
urlParams = urlParams.filter(param => (param.arg && !param.arg.match(/(id|fk|data|options|credentials)/g)));
urlParams = urlParams.filter(param => {
// Filter out route params and function params
if (paramIsRoute(param) || paramIsFunction(param)) {
return false
}
// Filter out body params
return (!param.http || param.http.source != 'body')
});
if (model.isUser && methodName === 'logout')
output.push(` urlParams.access_token = this.auth.getAccessTokenId();`);
if (urlParams && urlParams.length > 0) {
Expand All @@ -540,12 +574,15 @@ module.exports = function generate(ctx) {
*/
function buildRouteParams(routeParams) {
let output = [];
if (routeParams && routeParams.length > 0) {
output.push('');
routeParams.forEach((param, i) => {
output.push(` ${param.arg}: ${param.arg}${(i < routeParams.length - 1) ? ',' : ''}`);
});
output.push(' ');
if (routeParams) {
routeParams = routeParams.filter(paramIsRoute)
if (routeParams.length > 0) {
output.push('');
routeParams.forEach((param, i) => {
output.push(` ${param.arg}: ${param.arg}${(i < routeParams.length - 1) ? ',' : ''}`);
});
output.push(' ');
}
}
return output.join('\n');
}
Expand Down
72 changes: 33 additions & 39 deletions lib/angular2/shared/services/core/base.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ export abstract class BaseLoopBackApi {
protected path: string;

constructor(
@Inject(Http) protected http: Http,
@Inject(LoopBackAuth) protected auth: LoopBackAuth,
@Inject(JSONSearchParams) protected searchParams: JSONSearchParams,
@Inject(Http) protected http: Http,
@Inject(LoopBackAuth) protected auth: LoopBackAuth,
@Inject(JSONSearchParams) protected searchParams: JSONSearchParams,
@Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler
) {}

Expand All @@ -37,11 +37,9 @@ export abstract class BaseLoopBackApi {
url : string,
routeParams : any = {},
urlParams : any = {},
postBody : any = null<% if ( isIo === 'enabled' ){ -%>,
isio : boolean = false<% }
-%>

) {
postBody : any = null,
isio : boolean = false
): Observable<any> {

let headers = new Headers();
headers.append('Content-Type', 'application/json');
Expand All @@ -61,8 +59,8 @@ export abstract class BaseLoopBackApi {
routeParams[key] + "$1"
);
}

<% if ( isIo === 'enabled' ){ -%>
if (isio) {
if (requestUrl.match(/fk/)) {
let arr = requestUrl.split('/'); arr.pop();
Expand All @@ -76,35 +74,31 @@ export abstract class BaseLoopBackApi {
let socket: any = SocketConnections.getHandler(LoopBackConfig.getPath(), token);
socket.on(event, (res: any) => subject.next(res));
return subject.asObservable();
} else {<% } -%>
// Body fix for built in remote methods using "data", "options" or "credentials
// that are the actual body, Custom remote method properties are different and need
// to be wrapped into a body object
let body: any;
if (
typeof postBody === 'object' &&
(postBody.data || postBody.credentials || postBody.options) &&
Object.keys(postBody).length === 1
) {
body = postBody.data ? postBody.data :
postBody.options ? postBody.options :
postBody.credentials;
} else {
body = postBody;
}
this.searchParams.setJSON(urlParams);
let request: Request = new Request({
headers : headers,
method : method,
url : urlParams.filter ? `${requestUrl}?filter=${ encodeURI(JSON.stringify(urlParams.filter))}`
: requestUrl,
search : !urlParams.filter && Object.keys(urlParams).length > 0
? this.searchParams.getURLSearchParams() : null,
body : body ? JSON.stringify(body) : undefined
});
return this.http.request(request)
.map((res: any) => (res.text() != "" ? res.json() : {}))
.catch(this.errorHandler.handleError);
<% if ( isIo === 'enabled' ){ -%> }<% } -%>
}
<% } -%>

// Body fix for built in remote methods using "data", "options" or "credentials
// that are the actual body, Custom remote method properties are different and need
// to be wrapped into a body object
let body: any;
let postBodyKeys = typeof postBody === 'object' ? Object.keys(postBody) : []
if (postBodyKeys.length === 1) {
body = postBody[postBodyKeys[0]]
} else {
body = postBody;
}
this.searchParams.setJSON(urlParams);
let request: Request = new Request({
headers : headers,
method : method,
url : urlParams.filter ? `${requestUrl}?filter=${ encodeURI(JSON.stringify(urlParams.filter))}`
: requestUrl,
search : !urlParams.filter && Object.keys(urlParams).length > 0
? this.searchParams.getURLSearchParams() : null,
body : body ? JSON.stringify(body) : undefined
});
return this.http.request(request)
.map((res: any) => (res.text() != "" ? res.json() : {}))
.catch(this.errorHandler.handleError);
}
}
3 changes: 2 additions & 1 deletion lib/angular2/shared/services/core/error.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import 'rxjs/add/observable/throw';
/**
* Default error handler
*/
@Injectable()
export class ErrorHandler {
public handleError(error: Response) {
public handleError(error: Response): ErrorObservable {
return Observable.throw(error.json().error || 'Server error');
}
}
13 changes: 3 additions & 10 deletions lib/angular2/shared/services/custom/service.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -52,21 +52,14 @@ export class <%-: modelName %>Api extends BaseLoopBackApi {
}
// SET URL PARAMS
var urlParams = action.accepts.filter(function(param) {
return !(param.arg === "access_token" && methodName === "logout") && !(param.http && param.http.source === 'path');
});
var urlParams = action.accepts;
// SET POST BODY
var postData;
if (httpVerb == 'POST' || httpVerb == 'PUT' || httpVerb == 'PATCH') {
postData = action.accepts.filter(function(param) {
return !(param.http && (param.http.source == 'query' || param.http.source == 'path'))
&& !(param.arg === "access_token" && methodName === "logout");
});
postData = action.accepts;
}
// SET ROUTE PARAMS
var routeParams = action.accepts.filter(function(param) {
return (param.http && param.http.source === 'path') || (param.arg && param.arg.match(/(id|fk|file|container)/));
});
var routeParams = action.accepts
-%>
public <%- normalizeMethodName(methodName) %>(<%- buildMethodParams(model, methodName, action.accepts) %>): Observable<<%- buildObservableType(modelName, methodName) %>> {
let method: string = <%-: httpVerb | q %>;
Expand Down

0 comments on commit adaca80

Please sign in to comment.