troyanskiy / ngx-resource

Resource (REST) Client for Angular 2
http://troyanskiy.github.io/ngx-resource/
200 stars 46 forks source link

Intercept array response in 7.0 #156

Closed adrianmarinica closed 5 years ago

adrianmarinica commented 5 years ago

Hi! I need to intercept responses and map them to a specific format.

If the HTTP response is a simple JSON object, this works fine with both map and resultFactory. If the HTTP response is an array, then both map and resultFactory get the array items one by one. I would like to have a method that receives the entire response and is able to return it in a different format. Is this possible?

Thanks!

troyanskiy commented 5 years ago

hi! Not really possible with the lib. You can do something like that

import { Injectable } from '@angular/core';
import {
  IResourceMethodObservable,
  IResourceMethodPromise,
  Resource,
  ResourceAction,
  ResourceActionReturnType,
  ResourceHandler,
  ResourceParams
} from '@ngx-resource/core';

import { ILanguage } from '@app-declarations';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@ResourceParams({
  pathPrefix: '/api/i18n'
})
@Injectable({
  providedIn: 'root'
})
export class LanguageResource extends Resource {

  @ResourceAction({
    path: '/languages'
  })
  getLanguages: IResourceMethodObservable<void, ILanguage[]>;

  @ResourceAction({
    path: '/languages',
    returnAs: ResourceActionReturnType.Promise
  })
  getLanguagesProm: IResourceMethodPromise<void, ILanguage[]>;

  constructor(resourceHandler: ResourceHandler) {
    super(resourceHandler);
  }

  // As observable
  getLanguagesAsMap(): Observable<{ [code: string]: string }> {
    return this.getLanguages()
      .pipe(
        map(langs => {
          // do you transformation here
          return langs.reduce((acc: any, lang: ILanguage) => {
            acc[lang.code] = lang.title;

            return acc;
          }, {});
        })
      );
  }

  // As promise
  getLanguagesAsMapPromise(): Promise<{ [code: string]: string }> {
    return this.getLanguagesProm()
      .then(langs => {
        // do you transformation here
        return langs.reduce((acc: any, lang: ILanguage) => {
          acc[lang.code] = lang.title;

          return acc;
        }, {});
      });
  }
}
adrianmarinica commented 5 years ago

I understand, thank you for the help. Great job on this library, it's fantastically easy to use once you get the hang of it.