{"id":13406845,"url":"https://github.com/troyanskiy/ngx-resource","last_synced_at":"2025-04-04T12:08:28.732Z","repository":{"id":6193961,"uuid":"54953903","full_name":"troyanskiy/ngx-resource","owner":"troyanskiy","description":"Resource (REST) Client for Angular 2","archived":false,"fork":false,"pushed_at":"2023-02-21T08:36:46.000Z","size":5855,"stargazers_count":200,"open_issues_count":38,"forks_count":46,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-28T11:07:03.169Z","etag":null,"topics":["angular-2","network","requests","rest","rest-api"],"latest_commit_sha":null,"homepage":"http://troyanskiy.github.io/ngx-resource/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/troyanskiy.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2016-03-29T07:09:09.000Z","updated_at":"2024-02-03T16:19:19.000Z","dependencies_parsed_at":"2024-01-14T09:00:27.128Z","dependency_job_id":null,"html_url":"https://github.com/troyanskiy/ngx-resource","commit_stats":{"total_commits":279,"total_committers":19,"mean_commits":14.68421052631579,"dds":0.5340501792114696,"last_synced_commit":"6b62040e0a34674d5f4537fea6fd029baad06dbb"},"previous_names":["troyanskiy/ng2-resource-rest"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/troyanskiy%2Fngx-resource","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/troyanskiy%2Fngx-resource/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/troyanskiy%2Fngx-resource/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/troyanskiy%2Fngx-resource/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/troyanskiy","download_url":"https://codeload.github.com/troyanskiy/ngx-resource/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246970318,"owners_count":20862509,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular-2","network","requests","rest","rest-api"],"created_at":"2024-07-30T19:02:40.858Z","updated_at":"2025-04-04T12:08:28.700Z","avatar_url":"https://github.com/troyanskiy.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"## Unfortunately I don't have time to maintain the library. So PRs are more than welcome. \n\u003cbr\u003e\u003cbr\u003e\n\n| @ngx-resource/core | @ngx-resource/handler-ngx-http | @ngx-resource/handler-cordova-advanced-http | @ngx-resource/handler-ngx-http-legacy |\n| --- | --- | --- | --- |\n| [![npm version](https://img.shields.io/npm/v/%40ngx-resource%2Fcore.svg)](https://www.npmjs.com/package/@ngx-resource/core) | [![npm version](https://img.shields.io/npm/v/%40ngx-resource%2Fhandler-ngx-http.svg)](https://www.npmjs.com/package/@ngx-resource/handler-ngx-http) | [![npm version](https://img.shields.io/npm/v/%40ngx-resource%2Fhandler-cordova-advanced-http.svg)](https://www.npmjs.com/package/@ngx-resource/handler-cordova-advanced-http) | [![npm version](https://img.shields.io/npm/v/%40ngx-resource%2Fhandler-ngx-http-legacy.svg)](https://www.npmjs.com/package/@ngx-resource/handler-ngx-http-legacy) | \n\n# @ngx-resource/core\nResource 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.\nIn 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.\n\nAll my examples will be based on angular 4.4.4+\n\n### Known ResourceHandlers\n* `@ngx-resource/handler-ngx-http`. Based on `HttpClient` from `@angular/common/http`. Includes `ResourceModule.forRoot`.\n* `@ngx-resource/handler-ngx-http-legacy`. Based on `Http` from `@angular/http`. Includes `ResourceModule.forRoot`.\n* `@ngx-resource/handler-cordova-advanced-http`. Based on [Cordova Plugin Advanced HTTP](`https://github.com/silkimen/cordova-plugin-advanced-http`).\n* `@ngx-resource/handler-fetch`. Besed on [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). Not yet created.\n\n\n## Creation of Resource class\n\n```typescript\n@Injectable()\n@ResourceParams({\n  // IResourceParams\n  pathPrefix: '/auth'\n})\nexport class MyAuthResource extends Resource {\n\n  @ResourceAction({\n    // IResourceAction\n    method: ResourceRequestMethod.Post,\n    path: '/login'\n  })\n  login: IResourceMethod\u003c{login: string, password: string}, IReturnData\u003e; // will make an post request to /auth/login\n\n  @ResourceAction({\n    // IResourceAction\n    //method: ResourceRequestMethod.Get is by default\n    path: '/logout'\n  })\n  logout: IResourceMethod\u003cvoid, void\u003e;\n  \n  constructor(handler: ResourceHandler) {\n    super(handler);\n  }\n  \n}\n\n@Injectable()\n@ResourceParams({\n  // IResourceParams\n  pathPrefix: '/user'\n})\nexport class UserResource extends Resource {\n  \n  @ResourceAction({\n    path: '/{!id}'\n  })\n  getUser: IResourceMethodPromise\u003c{id: string}, IUser\u003e; // will call /user/id\n  \n  @ResourceAction({\n    method: ResourceRequestMethod.Post\n  })\n  createUser: IResourceMethodPromiseStrict\u003cIUser, IUserQuery, IUserPathParams, IUser\u003e;\n  \n  @ResoucreAction({\n    path: '/test/data',\n    asResourceResponse: true\n  })\n  testUserRequest: IResourceMethodPromiseFull\u003c{id: string}, IUser\u003e; // will call /test/data and receive repsponse object with headers, status and body\n  \n  constructor(restHandler: ResourceHandler) {\n    super(restHandler);\n  }\n  \n}\n\n// Using created Resource\n@Injectable\nexport class MyService {\n  \n  private user: IUser = null;\n\n  constructor(private myResource: MyAuthResource, private userResource: UserResource) {}\n  \n  doLogin(login: string, password: string): Promise\u003cany\u003e {\n    return this.myResource.login({login, password});\n  }\n  \n  doLogout(): Promise\u003cany\u003e {\n    return this.myResource.logout();\n  }\n  \n  async loginAndLoadUser(login: string, password: string, userId: string): Promise\u003cany\u003e {\n    await this.doLogin(login, password);\n    this.user = await this.userResource.getUser({id: userId});\n  }\n  \n}\n\n```\n\nFinal url is generated by concatination of `$getUrl`, `$getPathPrefix` and `$getPath` methods of `Resource` base class.\n\n### [IResourceParams](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/Declarations.ts#L2-L23) \n\nIs used by `ResourceParams` decorator for class decoration\n\nList of params:\n* `url?: string;` - url of the api server; *default `''`*\n* `pathPrefix?: string;` - path prefix of the api; *default `''`*\n* `path?: string;` - path of the api; *default `''`*\n* `headers?: any;` - headers; *default `{}`*\n* `body?: any;` - default body; *default `null`*\n* `params?: any;` - default url params; *default `null`*\n* `query?: any;` - defualt query params; *default `null`*\n* `rootNode?: string;` - key to assign all body; *default `null`*\n* `removeTrailingSlash?: boolean;` - *default `true`*\n* `addTimestamp?: boolean | string;` - *default `false`*\n* `withCredentials?: boolean;` - *default `false`*\n* `lean?: boolean;` - do no add `$` properties on result. Used only with `toPromise: false` *default `false`*\n* `mutateBody?: boolean;` - if need to mutate provided body with response body. *default `false`*\n* `returnAs?: ResourceActionReturnType;` - what type response should be returned by action/method . *default `ResourceActionReturnType.Observable`*\n* `keepEmptyBody?: boolean;` - if need to keep empty body object `{}`\n* `requestBodyType?: ResourceRequestBodyType;` - request body type. *default: will be detected automatically*.\nCheck for possible body types in the sources of [ResourceRequestBodyType](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/Declarations.ts#L114-L122). Type detection algorithm [check here](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/ResourceHelper.ts#L12-L34).\n* `responseBodyType?: ResourceResponseBodyType;` - response body type. *default: `ResourceResponseBodyType.JSON`* Possible body type can be checked here [ResourceResponseBodyType](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/Declarations.ts#L124-L129).\n\n### [IResourceAction](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/Declarations.ts#L2-L31) \n\nIs used by `ResourceAction` decorator for methods.\n\nList of params (is all of the above) plus the following:\n* `method?: ResourceRequestMethod;` - method of request. *Default `ResourceRequestMethod.Get`*. All possible methods listed in [ResourceRequestMethod](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/Declarations.ts#L131-L139)\n* `expectJsonArray?: boolean;` - if expected to receive an array. The field is used only with `toPromise: false`. *Default `false`*.\n* `resultFactory?: IResourceResultFactory;` - custom method to create result object. *Default: `returns {}`*\n* `map?: IResourceResponseMap;` - custom data mapping method. *Default: `returns without any changes`*\n* `filter?: IResourceResponseFilter;` - custom data filtering method. *Default: `returns true`*\n\n### [ResourceGlobalConfig](https://github.com/troyanskiy/ngx-resource-core/blob/master/src/ResourceGlobalConfig.ts)\nMainly used to set defaults.\n\n\n## Models\nAn object with built-in in methods to save, update, and delete a model.\nHere is an example of a `User` model.\n\nNote: UserResource should be injected at the beginning in order to use static\nmodel method like `User.get(\u003cid\u003e)`, `User.query()`, `User.remove(\u003cid\u003e)`\n\n```typescript\n\nexport interface IPaginationQuery {\n  page?: number;\n  perPage?: number;\n}\n\nexport interface IGroupQuery extends IPaginationQuery {\n  title?: string;\n}\n\nexport interface IUserQuery extends IPaginationQuery {\n  firstName?: string;\n  lastName?: string;\n  groupId?: number;\n}\n\nexport interface IUser {\n  id: number;\n  userName: string;\n  firstName: string;\n  lastName: string;\n  groupId: string;\n}\n\nexport class GroupResource extends ResourceCRUDPromise\u003cIGroupQuery, Group, Group\u003e {\n  \n  constructor(restHandler: ResourceHandler) {\n    super(restHandler);\n  }\n  \n  $resultFactory(data: any, options: IResourceActionInner = {}): any {\n    return new Group(data);\n  }\n  \n}\n\nexport class Group extends ResourceModel {\n  \n  readonly $resource = GroupResource;\n\n  id: number;\n  title: string;\n  \n  constructor(data?: IGroup) {\n    super();\n    if (data) {\n      this.$setData(data);\n    }\n  }\n  \n  $setData(data: IGroup) {\n    this.id = data.id;\n    this.title = data.title;\n  }\n  \n}\n\nexport class UserResource extends ResourceCRUDPromise\u003cIUserQuery, User, User\u003e {\n  \n  constructor(restHandler: ResourceHandler) {\n      super(restHandler);\n  }\n  \n  $resultFactory(data: any, options: IResourceActionInner = {}): any {\n    return new User(data);\n  }\n  \n}\n\nexport class User extends ResourceModel implements IUser {\n\n  readonly $resource = UserResource;\n\n  id: number;\n  userName: string;\n  firstName: string;\n  lastName: string;\n  groupId: string;\n  \n  fullName: string; // generated from first name and last name\n  \n  constructor(data?: IUser) {\n    super();\n    if (data) {\n      this.$setData(data);\n    }\n  }\n  \n  $setData(data: IUser): this {\n    Object.assign(this, data);\n    this.fullName = `${this.firstName} ${this.lastName}`;\n    return this;\n  }\n  \n  toJSON() {\n    // here i'm using lodash lib pick method.\n    return _.pick(this, ['id', 'firstName', 'lastName', 'groupId']);\n  }\n\n}\n\n\n// example of using the staff\nasync someMethodToCreateGroupAndUser() {\n\n  // Creation a group\n  const group = new Group();\n  group.title = 'My group';\n  \n  // Saving the group\n  await group.$save();\n  \n  // Creating an user\n  const user = new User({\n    userName: 'troyanskiy',\n    firstName: 'firstName',\n    lastName: 'lastName',\n    groupId: group.id\n  });\n  \n  // Saving the user\n  await user.$save();\n  \n  \n  // Query data from server\n  \n  const user1 = await this.userResource.get('1');\n  \n  // or\n  \n  const user2: User = await User.get('id');\n  \n}\n\n```\n\n\n## QueryParams Conversion\n\nYou can define the way query params are converted.\nSet the global config at the root of your app.\n\n`ResourceGlobalConfig.queryMappingMethod = ResourceQueryMappingMethod.\u003cCONVERSION_STRATEGY\u003e`\n\n```\n{\n  a: [{ b:1, c: [2, 3] }]\n}\n```\n\nWith `\u003cCONVERSION_STRATEGY\u003e` being one of the following:\n\n#### Plain (default)\nNo conversion at all\n\nOutput: `?a=[Object object]`\n\n#### Bracket\nAll array elements will be indexed\n\nOutput: `?a[0][b]=10383\u0026a[0][c][0]=2\u0026a[0][c][1]=3`\n\n#### JQueryParamsBracket \nImplements the standard $.params way of converting\n\nOutput: `?a[0][b]=10383\u0026a[0][c][]=2\u0026a[0][c][]=3`\n\n\n\n# @ngx-resource/handler-ngx-http\n\nIt's implementation of `ResourceHandler` which uses Angular `HttpClient`\n\n# If you are using Angular 5, please use @ngx-resource/handler-ngx-http 5.x\n\n## How to install and setup it\n```bash\n\u0026 npm i --save @ngx-resource/core @ngx-resource/handler-ngx-http\n```\n\nIn you app module\n```typescript\n\n// AoT requires an exported function for factories\nexport function myHandlerFactory(http: HttpClient) {\n    return new MyResourceHandler(http);\n}\n\n@NgModule({\n  imports: [\n    BrowserModule,\n    BrowserAnimationsModule,\n    HttpClientModule,\n\n    // Default ResourceHandler uses class `ResourceHandlerHttpClient`\n    ResourceModule.forRoot()\n    \n    // Or set you own handler\n    //ResourceModule.forRoot({\n    //  handler: { provide: ResourceHandler, useFactory: (myHandlerFactory), deps: [HttpClient] }\n    //})\n  ],\n  declarations: [...],\n  bootstrap: [...],\n  entryComponents: [...],\n  providers: [...]\n})\nexport class AppModule {\n}\n```\n\n## [Docs about @ngx-resource/core](https://github.com/troyanskiy/ngx-resource-core/blob/master/README.md)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftroyanskiy%2Fngx-resource","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftroyanskiy%2Fngx-resource","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftroyanskiy%2Fngx-resource/lists"}