Skip to content

Commit 8bf40e1

Browse files
committed
feat(@produces) short-hand decorator for parsing responses
1 parent a2175c3 commit 8bf40e1

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

angular2-rest.ts

+29-3
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export class RESTClient {
7676
* @param {Response} res - response object
7777
* @returns {Response} res - transformed response object
7878
*/
79-
protected responseInterceptor(res: Response): Response {
79+
protected responseInterceptor(res: Observable<any>): Observable<any> {
8080
return res;
8181
}
8282

@@ -158,6 +158,27 @@ export function Headers(headersDef: any) {
158158
};
159159
}
160160

161+
162+
/**
163+
* Defines the media type(s) that the methods can produce
164+
* @param MediaType producesDef - mediaType to be parsed
165+
*/
166+
export function Produces(producesDef: MediaType) {
167+
return function(target: RESTClient, propertyKey: string, descriptor: any) {
168+
descriptor.isJSON = producesDef === MediaType.JSON;
169+
return descriptor;
170+
};
171+
}
172+
173+
174+
/**
175+
* Supported @Produces media types
176+
*/
177+
export enum MediaType {
178+
JSON
179+
}
180+
181+
161182
function methodBuilder(method: number) {
162183
return function(url: string) {
163184
return function(target: RESTClient, propertyKey: string, descriptor: any) {
@@ -234,8 +255,14 @@ function methodBuilder(method: number) {
234255
this.requestInterceptor(req);
235256
// make the request and store the observable for later transformation
236257
var observable: Observable<Response> = this.http.request(req);
258+
259+
// transform the obserable in accordance to the @Produces decorator
260+
if (descriptor.isJSON) {
261+
observable = observable.map(res => res.json());
262+
}
263+
237264
// intercept the response
238-
observable = observable.map(this.responseInterceptor);
265+
observable = this.responseInterceptor(observable);
239266

240267
return observable;
241268
};
@@ -270,4 +297,3 @@ export var DELETE = methodBuilder(RequestMethods.Delete);
270297
* @param {string} url - resource url of the method
271298
*/
272299
export var HEAD = methodBuilder(RequestMethods.Head);
273-

0 commit comments

Comments
 (0)