├── .editorconfig ├── .gitignore ├── .prettierrc.json ├── CONTRIBUTING.md ├── README.md ├── angular.json ├── package-lock.json ├── package.json ├── projects └── ngx-rest-service │ ├── README.md │ ├── karma.conf.js │ ├── ng-package.json │ ├── package.json │ ├── src │ ├── lib │ │ ├── ngx-rest.config.ts │ │ ├── ngx-rest.module.ts │ │ └── rest-decorators │ │ │ ├── index.ts │ │ │ ├── rest.decorators.ts │ │ │ ├── rest.helpers.ts │ │ │ ├── rest.service.spec.ts │ │ │ ├── rest.service.ts │ │ │ └── rest.symbols.ts │ ├── public-api.ts │ └── test.ts │ ├── tsconfig.lib.json │ ├── tsconfig.lib.prod.json │ ├── tsconfig.spec.json │ └── tslint.json ├── tsconfig.json ├── tslint.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "all", 3 | "tabWidth": 2, 4 | "printWidth": 120, 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing to ngx-rest-service 2 | 🎉 Thanks for your interest in contributing! 🎉 3 | 4 | ## How can I help? 5 | Please check the [issues](https://github.com/ozergul/ngx-rest-service/issues) and support help wanted developers. 6 | 7 | ## Developing 8 | 9 | Start by installing all dependencies 10 | 11 | ```bash 12 | yarn 13 | ``` 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Install 2 | 3 | npm install ngx-rest-service 4 | 5 | or 6 | 7 | yarn add ngx-rest-service 8 | 9 | ### Usage 10 | Add to imports: 11 | ```typescript 12 | @NgModule({ 13 | imports: [ 14 | NgxRestModule.forRoot({ 15 | apiBaseUrl: 'http://localhost:3001', // <---- base url, you can get from environment. 16 | }), 17 | ], 18 | }) 19 | ``` 20 | 21 | Extend RestService in your service: 22 | ```typescript 23 | import { Injectable } from '@angular/core'; 24 | import { Observable } from 'rxjs'; 25 | import { Auth, User } from '../../models'; 26 | import { Body, Get, Post, RestService } from 'ngx-rest-service'; 27 | 28 | @Injectable({ 29 | providedIn: 'root', 30 | }) 31 | export class AuthService extends RestService { 32 | @Post('/auth/login') 33 | login(@Body userLoginRequest: Auth.UserLoginRequest): Observable { 34 | return null; 35 | } 36 | 37 | @Post('/auth/register') 38 | register(@Body userRegisterRequest: Auth.UserRegisterRequest): Observable { 39 | return null; 40 | } 41 | 42 | @Get('/auth/me') 43 | inquireMe(): Observable { 44 | return null; 45 | } 46 | } 47 | ``` 48 | #### @Get() 49 | You can use @Get() decorator to make GET request: 50 | ```typescript 51 | @Get('/projects') 52 | getProjects(): Observable { 53 | return null; 54 | } 55 | ``` 56 | Equals: 57 | 58 | /projects 59 | 60 | --- 61 | ```typescript 62 | @Get('/projects/{code}') 63 | getProjectByCode(@Path('code') code: string): Observable { 64 | return null; 65 | } 66 | ``` 67 | Equals: 68 | 69 | /projects/{code} 70 | --- 71 | 72 | ```typescript 73 | @Get('/projects') 74 | getProjects(@Query('page') page?: number, @Query('limit') limit?: number): Observable> { 75 | return null; 76 | } 77 | ``` 78 | Equals: 79 | 80 | /projects?page={page}&limit={limit} 81 | --- 82 | ```typescript 83 | @Get('/projects/{id}') 84 | getProjectsById( 85 | @Path('id') id: number, 86 | @Params('personCount') personCount: number, 87 | ): Observable { 88 | return null; 89 | } 90 | ``` 91 | Equals: 92 | 93 | //projects/{id} 94 | 95 | Query String Parameters 96 | 97 | personCount: ${personCount} 98 | 99 | #### @Post() 100 | ```typescript 101 | @Post('/projects/create') 102 | createProject(@Body project: Project): Observable { 103 | return null; 104 | } 105 | ``` 106 | 107 | #### @Put() 108 | ```typescript 109 | @Put('/projects/update') 110 | updateProject(@Body project: Project): Observable { 111 | return null; 112 | } 113 | ``` 114 | ### @Delete() 115 | ```typescript 116 | @Delete('/projects/{id}') 117 | deleteProject(@Path('id') id: number): Observable { 118 | return null; 119 | } 120 | ``` 121 | ### Download blob example 122 | ```typescript 123 | @Get('/downloadExcel') 124 | @Headers({ 125 | Accept: 'application/octet-stream,application/json', 126 | }) 127 | @ResponseType(eHTTP.ResponseType.Blob) 128 | inquireExcel( 129 | @Body body: DownloadProjectsExcelRequest, 130 | ): Observable { 131 | return null; 132 | } 133 | ``` 134 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "ngx-rest-service": { 7 | "projectType": "library", 8 | "root": "projects/ngx-rest-service", 9 | "sourceRoot": "projects/ngx-rest-service/src", 10 | "prefix": "lib", 11 | "architect": { 12 | "build": { 13 | "builder": "@angular-devkit/build-angular:ng-packagr", 14 | "options": { 15 | "tsConfig": "projects/ngx-rest-service/tsconfig.lib.json", 16 | "project": "projects/ngx-rest-service/ng-package.json" 17 | }, 18 | "configurations": { 19 | "production": { 20 | "tsConfig": "projects/ngx-rest-service/tsconfig.lib.prod.json" 21 | } 22 | } 23 | }, 24 | "test": { 25 | "builder": "@angular-devkit/build-angular:karma", 26 | "options": { 27 | "main": "projects/ngx-rest-service/src/test.ts", 28 | "tsConfig": "projects/ngx-rest-service/tsconfig.spec.json", 29 | "karmaConfig": "projects/ngx-rest-service/karma.conf.js" 30 | } 31 | }, 32 | "lint": { 33 | "builder": "@angular-devkit/build-angular:tslint", 34 | "options": { 35 | "tsConfig": [ 36 | "projects/ngx-rest-service/tsconfig.lib.json", 37 | "projects/ngx-rest-service/tsconfig.spec.json" 38 | ], 39 | "exclude": [ 40 | "**/node_modules/**" 41 | ] 42 | } 43 | } 44 | } 45 | }}, 46 | "defaultProject": "ngx-rest-service" 47 | } 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngx-rest-service", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint" 10 | }, 11 | "dependencies": { 12 | "@angular/animations": "~10.1.0", 13 | "@angular/common": "~10.1.0", 14 | "@angular/compiler": "~10.1.0", 15 | "@angular/core": "~10.1.0", 16 | "@angular/forms": "~10.1.0", 17 | "@angular/platform-browser": "~10.1.0", 18 | "@angular/platform-browser-dynamic": "~10.1.0", 19 | "@angular/router": "~10.1.0", 20 | "rxjs": "~6.6.0", 21 | "tslib": "^2.0.0", 22 | "zone.js": "~0.10.2" 23 | }, 24 | "devDependencies": { 25 | "@angular-devkit/build-angular": "~0.1001.0", 26 | "@angular/cli": "~10.1.0", 27 | "@angular/compiler-cli": "~10.1.0", 28 | "@types/jasmine": "~3.5.0", 29 | "@types/jasminewd2": "~2.0.3", 30 | "@types/node": "^12.11.1", 31 | "codelyzer": "^6.0.0", 32 | "jasmine-core": "~3.6.0", 33 | "jasmine-spec-reporter": "~5.0.0", 34 | "karma": "~5.0.0", 35 | "karma-chrome-launcher": "~3.1.0", 36 | "karma-coverage-istanbul-reporter": "~3.0.2", 37 | "karma-jasmine": "~4.0.0", 38 | "karma-jasmine-html-reporter": "^1.5.0", 39 | "ng-packagr": "^10.1.0", 40 | "prettier": "2.1.1", 41 | "protractor": "~7.0.0", 42 | "ts-node": "~8.3.0", 43 | "tslint": "~6.1.0", 44 | "typescript": "~4.0.2" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/README.md: -------------------------------------------------------------------------------- 1 | ## Install 2 | 3 | npm install ngx-rest-servic 4 | 5 | or 6 | 7 | yarn add ngx-rest-service 8 | 9 | ### Usage 10 | Add to imports: 11 | ```typescript 12 | @NgModule({ 13 | imports: [ 14 | NgxRestModule.forRoot({ 15 | apiBaseUrl: 'http://localhost:3001', // <---- base url, you can get from environment. 16 | }), 17 | ], 18 | }) 19 | ``` 20 | 21 | Extend RestService in your service: 22 | ```typescript 23 | import { Injectable } from '@angular/core'; 24 | import { Observable } from 'rxjs'; 25 | import { Auth, User } from '../../models'; 26 | import { Body, Get, Post, RestService } from 'ngx-rest-service'; 27 | 28 | @Injectable({ 29 | providedIn: 'root', 30 | }) 31 | export class AuthService extends RestService { 32 | @Post('/auth/login') 33 | login(@Body userLoginRequest: Auth.UserLoginRequest): Observable { 34 | return null; 35 | } 36 | 37 | @Post('/auth/register') 38 | register(@Body userRegisterRequest: Auth.UserRegisterRequest): Observable { 39 | return null; 40 | } 41 | 42 | @Get('/auth/me') 43 | inquireMe(): Observable { 44 | return null; 45 | } 46 | } 47 | ``` 48 | #### @Get() 49 | You can use @Get() decorator to make GET request: 50 | ```typescript 51 | @Get('/projects') 52 | getProjects(): Observable { 53 | return null; 54 | } 55 | ``` 56 | Equals: 57 | 58 | /projects 59 | 60 | --- 61 | ```typescript 62 | @Get('/projects/{code}') 63 | getProjectByCode(@Path('code') code: string): Observable { 64 | return null; 65 | } 66 | ``` 67 | Equals: 68 | 69 | /projects/{code} 70 | --- 71 | 72 | ```typescript 73 | @Get('/projects') 74 | getProjects(@Query('page') page?: number, @Query('limit') limit?: number): Observable> { 75 | return null; 76 | } 77 | ``` 78 | Equals: 79 | 80 | /projects?page={page}&limit={limit} 81 | --- 82 | ```typescript 83 | @Get('/projects/{id}') 84 | inquireAcquisitionCredit( 85 | @Path('id') id: number, 86 | @Params('personCount') personCount: number, 87 | ): Observable { 88 | return null; 89 | } 90 | ``` 91 | Equals: 92 | 93 | //projects/{id} 94 | 95 | Query String Parameters 96 | 97 | personCount: ${personCount} 98 | 99 | #### @Post() 100 | ```typescript 101 | @Post('/projects/create') 102 | createProject(@Body project: Project): Observable { 103 | return null; 104 | } 105 | ``` 106 | 107 | #### @Put() 108 | ```typescript 109 | @Put('/projects/update') 110 | updateProject(@Body project: Project): Observable { 111 | return null; 112 | } 113 | ``` 114 | ### @Delete() 115 | ```typescript 116 | @Delete('/projects/{id}') 117 | deleteProject(@Path('id') id: number): Observable { 118 | return null; 119 | } 120 | ``` 121 | ### Download blob example 122 | ```typescript 123 | @Get('/downloadExcel') 124 | @Headers({ 125 | Accept: 'application/octet-stream,application/json', 126 | }) 127 | @ResponseType(eHTTP.ResponseType.Blob) 128 | inquireBillingAccountChargesSummaryExcel( 129 | @Body body: DownloadProjectsExcelRequest, 130 | ): Observable { 131 | return null; 132 | } 133 | ``` 134 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../../coverage/ngx-rest-service'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/ng-package.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", 3 | "dest": "../../dist/ngx-rest-service", 4 | "lib": { 5 | "entryFile": "src/public-api.ts" 6 | } 7 | } -------------------------------------------------------------------------------- /projects/ngx-rest-service/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngx-rest-service", 3 | "version": "0.0.7", 4 | "peerDependencies": { 5 | "@angular/common": "^10.1.0", 6 | "@angular/core": "^10.1.0" 7 | }, 8 | "dependencies": { 9 | "tslib": "^2.0.0" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/ngx-rest.config.ts: -------------------------------------------------------------------------------- 1 | import { InjectionToken } from '@angular/core'; 2 | 3 | export interface GlobalConfig { 4 | apiBaseUrl: string; 5 | } 6 | 7 | export const REST_CONFIG = new InjectionToken('RestConfig'); 8 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/ngx-rest.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { GlobalConfig, REST_CONFIG } from './ngx-rest.config'; 3 | 4 | @NgModule() 5 | export class NgxRestModule { 6 | static forRoot(config: Partial = {}): ModuleWithProviders { 7 | return { 8 | ngModule: NgxRestModule, 9 | providers: [ 10 | { 11 | provide: REST_CONFIG, 12 | useValue: config, 13 | }, 14 | ], 15 | }; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/rest-decorators/index.ts: -------------------------------------------------------------------------------- 1 | export * from './rest.service'; 2 | export * from './rest.helpers'; 3 | export * from './rest.service'; 4 | export * from './rest.symbols'; 5 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/rest-decorators/rest.decorators.ts: -------------------------------------------------------------------------------- 1 | import { restClientParameterBuilder } from './rest.helpers'; 2 | import { RestService } from './rest.service'; 3 | import { eHTTP } from './rest.symbols'; 4 | 5 | export const Body = restClientParameterBuilder('Body')('Body'); 6 | export const Desc = restClientParameterBuilder('Desc')('Desc'); 7 | export const Query = restClientParameterBuilder('Query'); 8 | export const QueryMap = restClientParameterBuilder('QueryMap')('QueryMap'); 9 | export const Path = restClientParameterBuilder('Path'); 10 | export const Params = restClientParameterBuilder('Params'); 11 | export const ParamsMap = restClientParameterBuilder('ParamsMap')('ParamsMap'); 12 | 13 | export const Header = restClientParameterBuilder('Header'); 14 | 15 | export function WithCredentials() { 16 | return function (target: RestService, propertyKey: string, descriptor: any) { 17 | descriptor.withCredentials = true; 18 | return descriptor; 19 | }; 20 | } 21 | 22 | export function Headers(headers: { [name: string]: string | string[] }) { 23 | return function (target: RestService, propertyKey: string, descriptor: any) { 24 | descriptor.headers = headers; 25 | return descriptor; 26 | }; 27 | } 28 | 29 | export function ResponseType(responseType: eHTTP.ResponseType) { 30 | return function (target: RestService, propertyKey: string, descriptor: any) { 31 | descriptor.responseType = responseType; 32 | return descriptor; 33 | }; 34 | } 35 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/rest-decorators/rest.helpers.ts: -------------------------------------------------------------------------------- 1 | import { HttpHeaders, HttpParams, HttpRequest } from '@angular/common/http'; 2 | import { RestService } from './rest.service'; 3 | import { DecoratorValue, eHTTP, Rest } from './rest.symbols'; 4 | 5 | export function restClientParameterBuilder(paramName: string) { 6 | return function (key: string) { 7 | return function (target: RestService, propertyKey: string | symbol, parameterIndex: number) { 8 | const metadataKey = `${String(propertyKey)}_${paramName}_parameters`; 9 | const value: DecoratorValue = { 10 | key, 11 | parameterIndex, 12 | }; 13 | if (Array.isArray(target[metadataKey])) { 14 | target[metadataKey].push(value); 15 | } else { 16 | target[metadataKey] = [value]; 17 | } 18 | }; 19 | }; 20 | } 21 | 22 | export const Req = (urlPath: string, method: Rest.Method, restConfig?: Partial) => ( 23 | target: RestService, 24 | propertyKey: string, 25 | descriptor: any, 26 | ) => { 27 | const pBody: DecoratorValue[] = target[`${propertyKey}_Body_parameters`]; 28 | const pDesc: DecoratorValue[] = target[`${propertyKey}_Desc_parameters`]; 29 | const pQuery: DecoratorValue[] = target[`${propertyKey}_Query_parameters`]; 30 | const pQueryMap: DecoratorValue[] = target[`${propertyKey}_QueryMap_parameters`]; 31 | const pHeader: DecoratorValue[] = target[`${propertyKey}_Header_parameters`]; 32 | const pPath: DecoratorValue[] = target[`${propertyKey}_Path_parameters`]; 33 | const pParams: DecoratorValue[] = target[`${propertyKey}_Params_parameters`]; 34 | const pParamsMap: DecoratorValue[] = target[`${propertyKey}_ParamsMap_parameters`]; 35 | 36 | descriptor.value = function (this: RestService, ...args: any[]) { 37 | const body = extractMethodParameterValue(args, pBody); 38 | const params = extractParams(pParams, pParamsMap, args); 39 | const headers = extractHeaders(descriptor, pHeader, args); 40 | const responseType = extractResponseType(descriptor); 41 | const url: string = extractUrl(urlPath, pPath, pQuery, pQueryMap, args); 42 | 43 | const config = { 44 | endpoint: 'api', 45 | observe: eHTTP.Observe.Body, 46 | skipError: false, 47 | ...restConfig, 48 | } as Rest.Config; 49 | const request: HttpRequest | Rest.Request = { 50 | ...(body && { body }), 51 | ...(responseType && { responseType }), 52 | method, 53 | url, 54 | headers, 55 | params, 56 | withCredentials: descriptor.withCredentials, 57 | }; 58 | 59 | return this.request(request, config); 60 | }; 61 | 62 | return descriptor; 63 | }; 64 | 65 | export const Get = (urlPath: string, restConfig?: Partial) => 66 | Req.call(this, urlPath, Rest.Method.GET, restConfig); 67 | 68 | export const Post = (urlPath: string, restConfig?: Partial) => 69 | Req.call(this, urlPath, Rest.Method.POST, restConfig); 70 | 71 | export const Head = (urlPath: string, restConfig?: Partial) => 72 | Req.call(this, urlPath, Rest.Method.HEAD, restConfig); 73 | 74 | export const Put = (urlPath: string, restConfig?: Partial) => 75 | Req.call(this, urlPath, Rest.Method.PUT, restConfig); 76 | 77 | export const Patch = (urlPath: string, restConfig?: Partial) => 78 | Req.call(this, urlPath, Rest.Method.PATCH, restConfig); 79 | 80 | export const Delete = (urlPath: string, restConfig?: Partial) => 81 | Req.call(this, urlPath, Rest.Method.DELETE, restConfig); 82 | 83 | export const Connect = (urlPath: string, restConfig?: Partial) => 84 | Req.call(this, urlPath, Rest.Method.CONNECT, restConfig); 85 | 86 | export const Trace = (urlPath: string, restConfig?: Partial) => 87 | Req.call(this, urlPath, Rest.Method.TRACE, restConfig); 88 | 89 | export const Options = (urlPath: string, restConfig?: Partial) => 90 | Req.call(this, urlPath, Rest.Method.OPTIONS, restConfig); 91 | 92 | function extractUrl( 93 | url: string, 94 | pPath: DecoratorValue[], 95 | pQuery: DecoratorValue[], 96 | pQueryMap: DecoratorValue[], 97 | args: any[], 98 | ) { 99 | let resUrl = url; 100 | if (pPath) { 101 | resUrl = extractPath(resUrl, pPath, args); 102 | } 103 | 104 | if (pQuery) { 105 | resUrl = extractQuery(resUrl, pQuery, args); 106 | } 107 | 108 | if (pQueryMap) { 109 | resUrl = extractQueryMap(resUrl, args, pQueryMap); 110 | } 111 | return resUrl.charAt(resUrl.length - 1) === '/' ? resUrl.substring(0, resUrl.length - 1) : resUrl; 112 | } 113 | 114 | function extractQueryMap(resUrl: string, args: any[], pQueryMap: DecoratorValue[]) { 115 | resUrl = resUrl.includes('?') ? resUrl : `${resUrl}?`; 116 | const value = extractMethodParameterValue(args, pQueryMap) as Object; 117 | resUrl = Object.keys(value).reduce((acc, key) => acc + `${key}=${value[key]}&`, resUrl); 118 | resUrl = resUrl.substring(0, resUrl.length - 1); 119 | return resUrl; 120 | } 121 | 122 | function extractQuery(resUrl: string, pQuery: DecoratorValue[], args: any[]) { 123 | resUrl = resUrl.includes('?') ? resUrl : `${resUrl}?`; 124 | pQuery 125 | .filter((p) => args[p.parameterIndex] !== null && args[p.parameterIndex] !== undefined) // filter out optional parameters 126 | .forEach(({ key, parameterIndex }) => { 127 | let value = args[parameterIndex]; 128 | // if the value is a instance of Object, we stringify it 129 | if (value instanceof Object) { 130 | value = JSON.stringify(value); 131 | } 132 | resUrl += `${key}=${value}&`; 133 | }); 134 | resUrl = resUrl.substring(0, resUrl.length - 1); 135 | return resUrl; 136 | } 137 | 138 | function extractParams(pParams: DecoratorValue[], pParamsMap: DecoratorValue[], args: any[]) { 139 | let params = new HttpParams(); 140 | if (pParams) { 141 | pParams 142 | .filter((p) => args[p.parameterIndex]) // filter out optional parameters 143 | .forEach(({ key, parameterIndex }) => { 144 | let value = args[parameterIndex]; 145 | // if the value is a instance of Object, we stringify it 146 | if (value instanceof Object) { 147 | value = JSON.stringify(value); 148 | } 149 | if (value) { 150 | params = params.set(key, value); 151 | } 152 | }); 153 | } 154 | if (pParamsMap) { 155 | const value = extractMethodParameterValue(args, pParamsMap) as Object; 156 | Object.keys(value) 157 | .filter((key) => value[key]) 158 | .forEach((key) => (params = params.set(key, value[key]))); 159 | } 160 | return params; 161 | } 162 | 163 | function extractHeaders(descriptor: any, pHeader: DecoratorValue[], args: any[]) { 164 | let headers = new HttpHeaders(); 165 | // set method specific headers 166 | if (descriptor.headers) { 167 | Object.keys(descriptor.headers).forEach((key) => (headers = headers.set(key, descriptor.headers[key]))); 168 | } 169 | 170 | // set parameter specific headers 171 | if (pHeader) { 172 | pHeader.forEach(({ key, parameterIndex }) => (headers = headers.set(key, args[parameterIndex]))); 173 | } 174 | return headers; 175 | } 176 | 177 | function extractResponseType(descriptor: any) { 178 | if (descriptor.responseType) { 179 | return descriptor.responseType; 180 | } 181 | return null; 182 | } 183 | 184 | function extractPath(resUrl: string, pPath: DecoratorValue[], args: any[]) { 185 | return pPath.reduce((acc, { key, parameterIndex }) => urlBuilder(acc, { [key]: args[parameterIndex] }), resUrl); 186 | } 187 | 188 | function extractMethodParameterValue( 189 | args: any[], 190 | decorator: { key: string; parameterIndex: number }[], 191 | index: number = 0, 192 | ) { 193 | return decorator && args[decorator[index].parameterIndex]; 194 | } 195 | 196 | function urlBuilder(url = '', options = {}) { 197 | return Object.keys(options).reduce( 198 | (acc, key) => (acc = acc.replace(new RegExp(`{\\s*${key}\\s*}`, 'g'), options[key])), 199 | url, 200 | ); 201 | } 202 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/rest-decorators/rest.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { RestService } from './rest.service'; 4 | import { HttpClientModule } from '@angular/common/http'; 5 | import { REST_CONFIG } from '../ngx-rest.config'; 6 | 7 | describe('RestService', () => { 8 | let service: RestService; 9 | 10 | beforeEach(() => { 11 | TestBed.configureTestingModule({ 12 | providers: [HttpClientModule, { 13 | provide: REST_CONFIG, useValue: {} 14 | }], 15 | imports: [HttpClientModule], 16 | }); 17 | service = TestBed.inject(RestService); 18 | }); 19 | 20 | it('should be created', () => { 21 | expect(service).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/rest-decorators/rest.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, HttpRequest } from '@angular/common/http'; 2 | import { Inject, Injectable } from '@angular/core'; 3 | import { eHTTP, Rest } from './rest.symbols'; 4 | import { GlobalConfig, REST_CONFIG } from '../ngx-rest.config'; 5 | 6 | @Injectable({ 7 | providedIn: 'root', 8 | }) 9 | export class RestService { 10 | constructor( 11 | @Inject(REST_CONFIG) public restConfig: GlobalConfig, 12 | protected http: HttpClient) {} 13 | 14 | request(request: HttpRequest | Rest.Request, config: Rest.Config) { 15 | const { method, url, ...options } = request; 16 | const { observe = eHTTP.Observe.Body } = config; 17 | const apiBaseUrl = this.restConfig.apiBaseUrl; 18 | return this.http.request(method, apiBaseUrl + url, { ...options, observe } as any); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/lib/rest-decorators/rest.symbols.ts: -------------------------------------------------------------------------------- 1 | import { HttpHeaders, HttpParams } from '@angular/common/http'; 2 | 3 | export interface DecoratorValue { 4 | key: string; 5 | parameterIndex: number; 6 | } 7 | 8 | export namespace Rest { 9 | export enum Method { 10 | GET = 'GET', 11 | HEAD = 'HEAD', 12 | POST = 'POST', 13 | PUT = 'PUT', 14 | PATCH = 'PATCH', 15 | DELETE = 'DELETE', 16 | CONNECT = 'CONNECT', 17 | TRACE = 'TRACE', 18 | OPTIONS = 'OPTIONS', 19 | } 20 | 21 | export interface Config { 22 | endpoint?: string; 23 | observe?: eHTTP.Observe; 24 | skipError?: boolean; 25 | } 26 | 27 | export interface Request { 28 | body?: T; 29 | headers?: 30 | | HttpHeaders 31 | | { 32 | [header: string]: string | string[]; 33 | }; 34 | method: Method; 35 | params?: 36 | | HttpParams 37 | | { 38 | [param: string]: string | number | boolean | any[]; 39 | }; 40 | reportProgress?: boolean; 41 | responseType?: eHTTP.ResponseType; 42 | url: string; 43 | withCredentials?: boolean; 44 | } 45 | 46 | export interface Error { 47 | body: any; 48 | status: number; 49 | skipError?: boolean; 50 | } 51 | 52 | export type State = { 53 | errors: Error[]; 54 | }; 55 | } 56 | 57 | export namespace eHTTP { 58 | export enum Observe { 59 | Body = 'body', 60 | Events = 'events', 61 | Response = 'response', 62 | } 63 | 64 | export enum ResponseType { 65 | ArrayBuffer = 'arraybuffer', 66 | Blob = 'blob', 67 | JSON = 'json', 68 | Text = 'text', 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/public-api.ts: -------------------------------------------------------------------------------- 1 | export * from './lib/ngx-rest.module'; 2 | export * from './lib/rest-decorators/rest.decorators' 3 | export * from './lib/rest-decorators/rest.service' 4 | export * from './lib/rest-decorators/rest.helpers' 5 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone'; 4 | import 'zone.js/dist/zone-testing'; 5 | import { getTestBed } from '@angular/core/testing'; 6 | import { 7 | BrowserDynamicTestingModule, 8 | platformBrowserDynamicTesting 9 | } from '@angular/platform-browser-dynamic/testing'; 10 | 11 | declare const require: { 12 | context(path: string, deep?: boolean, filter?: RegExp): { 13 | keys(): string[]; 14 | (id: string): T; 15 | }; 16 | }; 17 | 18 | // First, initialize the Angular testing environment. 19 | getTestBed().initTestEnvironment( 20 | BrowserDynamicTestingModule, 21 | platformBrowserDynamicTesting() 22 | ); 23 | // Then we find all the tests. 24 | const context = require.context('./', true, /\.spec\.ts$/); 25 | // And load the modules. 26 | context.keys().map(context); 27 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/tsconfig.lib.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "../../tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "../../out-tsc/lib", 6 | "target": "es2015", 7 | "declaration": true, 8 | "declarationMap": true, 9 | "inlineSources": true, 10 | "types": [], 11 | "lib": [ 12 | "dom", 13 | "es2018" 14 | ] 15 | }, 16 | "angularCompilerOptions": { 17 | "skipTemplateCodegen": true, 18 | "strictMetadataEmit": true, 19 | "enableResourceInlining": true 20 | }, 21 | "exclude": [ 22 | "src/test.ts", 23 | "**/*.spec.ts" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/tsconfig.lib.prod.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.lib.json", 4 | "compilerOptions": { 5 | "declarationMap": false 6 | }, 7 | "angularCompilerOptions": { 8 | "enableIvy": false 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "../../tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "../../out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts" 12 | ], 13 | "include": [ 14 | "**/*.spec.ts", 15 | "**/*.d.ts" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /projects/ngx-rest-service/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "lib", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "lib", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "moduleResolution": "node", 11 | "importHelpers": true, 12 | "target": "es2015", 13 | "module": "es2020", 14 | "lib": [ 15 | "es2018", 16 | "dom" 17 | ], 18 | "paths": { 19 | "ngx-rest-service": [ 20 | "dist/ngx-rest-service/ngx-rest-service", 21 | "dist/ngx-rest-service" 22 | ] 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rulesDirectory": [ 4 | "codelyzer" 5 | ], 6 | "rules": { 7 | "align": { 8 | "options": [ 9 | "parameters", 10 | "statements" 11 | ] 12 | }, 13 | "array-type": false, 14 | "arrow-return-shorthand": true, 15 | "curly": true, 16 | "deprecation": { 17 | "severity": "warning" 18 | }, 19 | "eofline": true, 20 | "import-blacklist": [ 21 | true, 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": { 26 | "options": [ 27 | "spaces" 28 | ] 29 | }, 30 | "max-classes-per-file": false, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-console": [ 47 | true, 48 | "debug", 49 | "info", 50 | "time", 51 | "timeEnd", 52 | "trace" 53 | ], 54 | "no-empty": false, 55 | "no-inferrable-types": [ 56 | true, 57 | "ignore-params" 58 | ], 59 | "no-non-null-assertion": true, 60 | "no-redundant-jsdoc": true, 61 | "no-switch-case-fall-through": true, 62 | "no-var-requires": false, 63 | "object-literal-key-quotes": [ 64 | true, 65 | "as-needed" 66 | ], 67 | "quotemark": [ 68 | true, 69 | "single" 70 | ], 71 | "semicolon": { 72 | "options": [ 73 | "always" 74 | ] 75 | }, 76 | "space-before-function-paren": { 77 | "options": { 78 | "anonymous": "never", 79 | "asyncArrow": "always", 80 | "constructor": "never", 81 | "method": "never", 82 | "named": "never" 83 | } 84 | }, 85 | "typedef": [ 86 | true, 87 | "call-signature" 88 | ], 89 | "typedef-whitespace": { 90 | "options": [ 91 | { 92 | "call-signature": "nospace", 93 | "index-signature": "nospace", 94 | "parameter": "nospace", 95 | "property-declaration": "nospace", 96 | "variable-declaration": "nospace" 97 | }, 98 | { 99 | "call-signature": "onespace", 100 | "index-signature": "onespace", 101 | "parameter": "onespace", 102 | "property-declaration": "onespace", 103 | "variable-declaration": "onespace" 104 | } 105 | ] 106 | }, 107 | "variable-name": { 108 | "options": [ 109 | "ban-keywords", 110 | "check-format", 111 | "allow-pascal-case" 112 | ] 113 | }, 114 | "whitespace": { 115 | "options": [ 116 | "check-branch", 117 | "check-decl", 118 | "check-operator", 119 | "check-separator", 120 | "check-type", 121 | "check-typecast" 122 | ] 123 | }, 124 | "component-class-suffix": true, 125 | "contextual-lifecycle": true, 126 | "directive-class-suffix": true, 127 | "no-conflicting-lifecycle": true, 128 | "no-host-metadata-property": true, 129 | "no-input-rename": true, 130 | "no-inputs-metadata-property": true, 131 | "no-output-native": true, 132 | "no-output-on-prefix": true, 133 | "no-output-rename": true, 134 | "no-outputs-metadata-property": true, 135 | "template-banana-in-box": true, 136 | "template-no-negated-async": true, 137 | "use-lifecycle-interface": true, 138 | "use-pipe-transform-interface": true 139 | } 140 | } 141 | --------------------------------------------------------------------------------