All Projects → troyanskiy → Ngx Resource

troyanskiy / Ngx Resource

Licence: mit
Resource (REST) Client for Angular 2

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Ngx Resource

Ngx Restangular
Restangular for Angular 2 and higher versions
Stars: ✭ 787 (+291.54%)
Mutual labels:  rest-api, rest, angular-2
Restclient
🦄 Simple HTTP and REST client for Unity based on Promises, also supports Callbacks! 🎮
Stars: ✭ 675 (+235.82%)
Mutual labels:  rest-api, rest, requests
Libhv
🔥 比libevent、libuv更易用的国产网络库。A c/c++ network library for developing TCP/UDP/SSL/HTTP/WebSocket client/server.
Stars: ✭ 3,355 (+1569.15%)
Mutual labels:  network, requests
Finale
Create flexible REST endpoints and controllers from Sequelize models in your Express app
Stars: ✭ 167 (-16.92%)
Mutual labels:  rest-api, rest
Jikan Rest
The REST API for Jikan
Stars: ✭ 200 (-0.5%)
Mutual labels:  rest-api, rest
Jda
Java wrapper for the popular chat & VOIP service: Discord https://discord.com
Stars: ✭ 2,598 (+1192.54%)
Mutual labels:  rest-api, rest
Rest Api Slim Php
Example of REST API with Slim PHP Framework.
Stars: ✭ 165 (-17.91%)
Mutual labels:  rest-api, rest
Forrest
A Laravel library for Salesforce
Stars: ✭ 171 (-14.93%)
Mutual labels:  rest-api, rest
Cete
Cete is a distributed key value store server written in Go built on top of BadgerDB.
Stars: ✭ 153 (-23.88%)
Mutual labels:  rest-api, rest
Graphql2rest
GraphQL to REST converter: automatically generate a RESTful API from your existing GraphQL API
Stars: ✭ 181 (-9.95%)
Mutual labels:  rest-api, rest
Storefront Api
Storefront GraphQL API Gateway. Modular architecture. ElasticSearch included. Works great with Magento1, Magento2, Spree, OpenCart, Pimcore and custom backends
Stars: ✭ 180 (-10.45%)
Mutual labels:  rest-api, rest
Lumen Microservice
Lumen on Docker - Skeleton project with Nginx, MySQL & PHP 7 | Aws ECS, Google Kubernates, Azure Container Engine
Stars: ✭ 183 (-8.96%)
Mutual labels:  rest-api, rest
Webtau
Webtau (short for web test automation) is a testing API, command line tool and a framework to write unit, integration and end-to-end tests. Test across REST-API, Graph QL, Browser, Database, CLI and Business Logic with consistent set of matchers and concepts. REPL mode speeds-up tests development. Rich reporting cuts down investigation time.
Stars: ✭ 156 (-22.39%)
Mutual labels:  rest-api, rest
Restcountries
Get information about countries via a RESTful API
Stars: ✭ 2,054 (+921.89%)
Mutual labels:  rest-api, rest
Swagger Js
Javascript library to connect to swagger-enabled APIs via browser or nodejs
Stars: ✭ 2,319 (+1053.73%)
Mutual labels:  rest-api, rest
Hikaku
A library that tests if the implementation of a REST-API meets its specification.
Stars: ✭ 154 (-23.38%)
Mutual labels:  rest-api, rest
Webcc
Lightweight C++ HTTP client and server library based on Asio for embedding purpose.
Stars: ✭ 167 (-16.92%)
Mutual labels:  rest, requests
Swagger Codegen
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
Stars: ✭ 13,859 (+6795.02%)
Mutual labels:  rest-api, rest
Api Guidelines
adidas group API design guidelines
Stars: ✭ 147 (-26.87%)
Mutual labels:  rest-api, rest
Appkernel
API development made easy: a smart Python 3 API framework
Stars: ✭ 152 (-24.38%)
Mutual labels:  rest-api, rest
@ngx-resource/core @ngx-resource/handler-ngx-http @ngx-resource/handler-cordova-advanced-http @ngx-resource/handler-ngx-http-legacy
npm version npm version npm version npm version

@ngx-resource/core

Resource Core is an evolution of ngx-resource lib which provides flexibility for developers. Each developer can implement their own request handlers to easily customize the behavior. In fact, @ngx-resource/core is an abstract common library which uses ResourceHandler to make requests, so it's even possible to use the lib on node.js server side with typescript. You just need to implement a ResourceHandler for it.

All my examples will be based on angular 4.4.4+

Known ResourceHandlers

  • @ngx-resource/handler-ngx-http. Based on HttpClient from @angular/common/http. Includes ResourceModule.forRoot.
  • @ngx-resource/handler-ngx-http-legacy. Based on Http from @angular/http. Includes ResourceModule.forRoot.
  • @ngx-resource/handler-cordova-advanced-http. Based on Cordova Plugin Advanced HTTP.
  • @ngx-resource/handler-fetch. Besed on Fetch API. Not yet created.

Creation of Resource class

@Injectable()
@ResourceParams({
  // IResourceParams
  pathPrefix: '/auth'
})
export class MyAuthResource extends Resource {

  @ResourceAction({
    // IResourceAction
    method: ResourceRequestMethod.Post,
    path: '/login'
  })
  login: IResourceMethod<{login: string, password: string}, IReturnData>; // will make an post request to /auth/login

  @ResourceAction({
    // IResourceAction
    //method: ResourceRequestMethod.Get is by default
    path: '/logout'
  })
  logout: IResourceMethod<void, void>;
  
  constructor(handler: ResourceHandler) {
    super(handler);
  }
  
}

@Injectable()
@ResourceParams({
  // IResourceParams
  pathPrefix: '/user'
})
export class UserResource extends Resource {
  
  @ResourceAction({
    path: '/{!id}'
  })
  getUser: IResourceMethodPromise<{id: string}, IUser>; // will call /user/id
  
  @ResourceAction({
    method: ResourceRequestMethod.Post
  })
  createUser: IResourceMethodPromiseStrict<IUser, IUserQuery, IUserPathParams, IUser>;
  
  @ResoucreAction({
    path: '/test/data',
    asResourceResponse: true
  })
  testUserRequest: IResourceMethodPromiseFull<{id: string}, IUser>; // will call /test/data and receive repsponse object with headers, status and body
  
  constructor(restHandler: ResourceHandler) {
    super(restHandler);
  }
  
}

// Using created Resource
@Injectable
export class MyService {
  
  private user: IUser = null;

  constructor(private myResource: MyAuthResource, private userResource: UserResource) {}
  
  doLogin(login: string, password: string): Promise<any> {
    return this.myResource.login({login, password});
  }
  
  doLogout(): Promise<any> {
    return this.myResource.logout();
  }
  
  async loginAndLoadUser(login: string, password: string, userId: string): Promise<any> {
    await this.doLogin(login, password);
    this.user = await this.userResource.getUser({id: userId});
  }
  
}

Final url is generated by concatination of $getUrl, $getPathPrefix and $getPath methods of Resource base class.

IResourceParams

Is used by ResourceParams decorator for class decoration

List of params:

  • url?: string; - url of the api server; default ''
  • pathPrefix?: string; - path prefix of the api; default ''
  • path?: string; - path of the api; default ''
  • headers?: any; - headers; default {}
  • body?: any; - default body; default null
  • params?: any; - default url params; default null
  • query?: any; - defualt query params; default null
  • rootNode?: string; - key to assign all body; default null
  • removeTrailingSlash?: boolean; - default true
  • addTimestamp?: boolean | string; - default false
  • withCredentials?: boolean; - default false
  • lean?: boolean; - do no add $ properties on result. Used only with toPromise: false default false
  • mutateBody?: boolean; - if need to mutate provided body with response body. default false
  • returnAs?: ResourceActionReturnType; - what type response should be returned by action/method . default ResourceActionReturnType.Observable
  • keepEmptyBody?: boolean; - if need to keep empty body object {}
  • requestBodyType?: ResourceRequestBodyType; - request body type. default: will be detected automatically. Check for possible body types in the sources of ResourceRequestBodyType. Type detection algorithm check here.
  • responseBodyType?: ResourceResponseBodyType; - response body type. default: ResourceResponseBodyType.JSON Possible body type can be checked here ResourceResponseBodyType.

IResourceAction

Is used by ResourceAction decorator for methods.

List of params (is all of the above) plus the following:

  • method?: ResourceRequestMethod; - method of request. Default ResourceRequestMethod.Get. All possible methods listed in ResourceRequestMethod
  • expectJsonArray?: boolean; - if expected to receive an array. The field is used only with toPromise: false. Default false.
  • resultFactory?: IResourceResultFactory; - custom method to create result object. Default: returns {}
  • map?: IResourceResponseMap; - custom data mapping method. Default: returns without any changes
  • filter?: IResourceResponseFilter; - custom data filtering method. Default: returns true

ResourceGlobalConfig

Mainly used to set defaults.

Models

An object with built-in in methods to save, update, and delete a model. Here is an example of a User model.

Note: UserResource should be injected at the beginning in order to use static model method like User.get(<id>), User.query(), User.remove(<id>)

export interface IPaginationQuery {
  page?: number;
  perPage?: number;
}

export interface IGroupQuery extends IPaginationQuery {
  title?: string;
}

export interface IUserQuery extends IPaginationQuery {
  firstName?: string;
  lastName?: string;
  groupId?: number;
}

export interface IUser {
  id: number;
  userName: string;
  firstName: string;
  lastName: string;
  groupId: string;
}

export class GroupResource extends ResourceCRUDPromise<IGroupQuery, Group, Group> {
  
  constructor(restHandler: ResourceHandler) {
    super(restHandler);
  }
  
  $resultFactory(data: any, options: IResourceActionInner = {}): any {
    return new Group(data);
  }
  
}

export class Group extends ResourceModel {
  
  readonly $resource = GroupResource;

  id: number;
  title: string;
  
  constructor(data?: IGroup) {
    super();
    if (data) {
      this.$setData(data);
    }
  }
  
  $setData(data: IGroup) {
    this.id = data.id;
    this.title = data.title;
  }
  
}

export class UserResource extends ResourceCRUDPromise<IUserQuery, User, User> {
  
  constructor(restHandler: ResourceHandler) {
      super(restHandler);
  }
  
  $resultFactory(data: any, options: IResourceActionInner = {}): any {
    return new User(data);
  }
  
}

export class User extends ResourceModel implements IUser {

  readonly $resource = UserResource;

  id: number;
  userName: string;
  firstName: string;
  lastName: string;
  groupId: string;
  
  fullName: string; // generated from first name and last name
  
  constructor(data?: IUser) {
    super();
    if (data) {
      this.$setData(data);
    }
  }
  
  $setData(data: IUser): this {
    Object.assign(this, data);
    this.fullName = `${this.firstName} ${this.lastName}`;
    return this;
  }
  
  toJSON() {
    // here i'm using lodash lib pick method.
    return _.pick(this, ['id', 'firstName', 'lastName', 'groupId']);
  }

}


// example of using the staff
async someMethodToCreateGroupAndUser() {

  // Creation a group
  const group = new Group();
  group.title = 'My group';
  
  // Saving the group
  await group.$save();
  
  // Creating an user
  const user = new User({
    userName: 'troyanskiy',
    firstName: 'firstName',
    lastName: 'lastName',
    groupId: group.id
  });
  
  // Saving the user
  await user.$save();
  
  
  // Query data from server
  
  const user1 = await this.userResource.get('1');
  
  // or
  
  const user2: User = await User.get('id');
  
}

QueryParams Conversion

You can define the way query params are converted. Set the global config at the root of your app.

ResourceGlobalConfig.queryMappingMethod = ResourceQueryMappingMethod.<CONVERSION_STRATEGY>

{
  a: [{ b:1, c: [2, 3] }]
}

With <CONVERSION_STRATEGY> being one of the following:

Plain (default)

No conversion at all

Output: ?a=[Object object]

Bracket

All array elements will be indexed

Output: ?a[0][b]=10383&a[0][c][0]=2&a[0][c][1]=3

JQueryParamsBracket

Implements the standard $.params way of converting

Output: ?a[0][b]=10383&a[0][c][]=2&a[0][c][]=3

@ngx-resource/handler-ngx-http

It's implementation of ResourceHandler which uses Angular HttpClient

If you are using Angular 5, please use @ngx-resource/handler-ngx-http 5.x

How to install and setup it

& npm i --save @ngx-resource/core @ngx-resource/handler-ngx-http

In you app module

// AoT requires an exported function for factories
export function myHandlerFactory(http: HttpClient) {
    return new MyResourceHandler(http);
}

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,

    // Default ResourceHandler uses class `ResourceHandlerHttpClient`
    ResourceModule.forRoot()
    
    // Or set you own handler
    //ResourceModule.forRoot({
    //  handler: { provide: ResourceHandler, useFactory: (myHandlerFactory), deps: [HttpClient] }
    //})
  ],
  declarations: [...],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...]
})
export class AppModule {
}

Docs about @ngx-resource/core

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].