This package has been deprecated

Author message:

The library has been moved to @ngx-resource/core and all Rest renamed to Resource

rest-core
TypeScript icon, indicating that this package has built-in type declarations

0.2.2 • Public • Published

npm version

NPM

rest-core

Rest Core is an evolution of ngx-resource lib which provides freedom for the developers. Each developer can implement his own request handlers. In fact, rest-core is an abstract common library which uses RestHandler to make an requests, so it's even possible to use the lib on node.js server side with typescript. Just need to implement RestHandler for it.

All my examples will be based on angalar 4.4.4+

Known RestHandlers

Creation of rest class

@Injectable()
@RestParams({
  // IRestParams
  pathPrefix: '/auth'
})
export class MyAuthRest extends Rest {
 
  @RestAction({
    // IRestAction
    method: RestRequestMethod.Post
    path'/login'
  })
  login: IRestMethod<{login: string, password: string}, IReturnData>; // will make an post request to /auth/login
 
  @RestAction({
    // IRestAction
    //method: RestRequestMethod.Get is by default
    path: '/logout'
  })
  logout: IRestMethod<void, void>;
  
  constructor(restHandler: RestHandler) {
    super(restHandler);
  }
  
}
 
@Injectable()
@RestParams({
  // IRestParams
  pathPrefix: '/user'
})
export class UserRest extends Rest {
  
  @RestAction({
    path: '/{!id}'
  })
  getUser: IRestMethod<{id: string}, IUser>; // will call /user/id
  
  @RestAction({
    method: RestRequestMethod.Post
  })
  createUser: IRestMethodStrict<IUser, IUserQuery, IUserPathParams, IUser>;
  
  constructor(restHandler: RestHandler) {
    super(restHandler);
  }
  
}
 
// Using created rest
@Injectable
export class MyService {
  
  private user: IUser = null;
 
  constructor(private myRest: MyAuthRest, private userRest: UserRest) {}
  
  doLogin(login: string, password: string): Promise<any> {
    return this.myRest.login({login, password});
  }
  
  doLogout(): Promise<any> {
    return this.myRest.logout();
  }
  
  async loginAndLoadUser(login: string, password: string, userId: string): Promise<any> {
    await this.doLogin(login, password);
    this.user = await this.userRest.getUser({id: userId});
  }
  
}
 

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

IRestParams

Is used by RestParams 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
  • asPromise?: boolean; - if method should return promise or object, which will be fullfilled after receiving response. default true
  • requestBodyType?: RestRequestBodyType; - request body type. default: will be detected automatically. Check for possible body types in the sources of RestRequestBodyType. Type detection algorithm check here.
  • responseBodyType?: RestResponseBodyType; - response body type. default: RestResponseBodyType.JSON Possible body type can be checked here RestResponseBodyType.

IRestAction

Is used by RestAction decorator for methods.

List of params (is all above) plus following:

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

RestGlobalConfig

Mainly used to set defaults

Models

What is that. It's an object which has build in methods to save, update, delete an model. Here is an example of User model.

 
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 GroupRest extends RestCRUD<IGroupQuery, Group, Group> {
  
  constructor(restHandler: RestHandler) {
    super(restHandler);
  }
  
  $resultFactory(data: any, options: IRestActionInner = {}): any {
    return new Group(data);
  }
  
}
 
export class Group extends RestModel {
  
  readonly $rest = GroupRest;
 
  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 UserRest extends RestCRUD<IUserQuery, User, User> {
  
  constructor(restHandler: RestHandler) {
      super(restHandler);
  }
  
  $resultFactory(data: any, options: IRestActionInner = {}): any {
    return new User(data);
  }
  
}
 
export class User extends RestModel implements IUser {
 
  readonly $rest = UserRest;
 
  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(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();
  
}
 

QueryParams Conversion

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

RestGlobalConfig.queryMappingMethod = RestQueryMappingMethod.<CONVERTION_STRATEGY>

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

With <CONVERTION_STRATEGY> being an enumerable within

Plain (default)

No convertion 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

Developing Rest Handler

Use RestHandler abstract class as parent to create your Handler. I think it's clear what should it do by checking sources of the class.

Package Sidebar

Install

npm i rest-core

Weekly Downloads

6

Version

0.2.2

License

MIT

Last publish

Collaborators

  • troyanskiy