Skip to content

Instantly share code, notes, and snippets.

@misha130
Last active December 16, 2016 15:17
Show Gist options
  • Save misha130/ed6ce658f94fe0ad8e9e53f244e38364 to your computer and use it in GitHub Desktop.
Save misha130/ed6ce658f94fe0ad8e9e53f244e38364 to your computer and use it in GitHub Desktop.
@Injectable()
export class QueryBuilder<T> {
private queryString: string;
private postObject: Object;
private method: string;
private controller: string;
constructor(public http: HttpHandler) {
}
public Query(controller: string): this {
this.controller = controller;
this.method = 'GET';
return this;
}
public Include(inc: string | Object): this {
if (typeof inc === 'string') {
this.queryString += 'id=' + inc + '&';
this.method = 'GET';
}
else if (typeof inc === 'object') {
this.method = 'POST';
this.postObject === inc;
}
return this;
}
public Add(obj: T): this {
this.postObject = obj;
this.method = 'POST';
return this;
}
public Remove(id: string): this {
this.queryString += 'id=' + id + '&';
this.method = 'DELETE';
return this;
}
public async Execute(): Promise<T | Array<T>> {
let res: Response;
switch (this.method) {
case 'GET':
res = await this.http.Get(this.controller + '?' + this.queryString);
break;
case 'POST':
res = await this.http.Post(this.controller, this.postObject);
break;
case 'DELETE':
res = await this.http.Post(this.controller, this.postObject);
break;
}
return res.json();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment