1.0.7 • Published 6 years ago

fetch-rest-api-wrapper v1.0.7

Weekly downloads
1
License
ISC
Repository
github
Last release
6 years ago

FETCH Rest Api Wrapper

Fetch rest api wrapper is a promise based API "abstraction" that allows you to easily interface with your backend services. It is build using the fetch library that is available via the Web Api's that can be found here: https://developer.mozilla.org/en-US/docs/Web/API .

FETCH API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

IE Polyfill: https://github.com/github/fetch

Installation

To install the library you must use the following command npm install fetch-rest-api-wrapper --save

This will now install to your local node_modules folder and in order to require it you must import it like so.

import * as Api from 'fetch-rest-api-wrapper';

If you don't want to have to write Api.GET() you can also destructure the object like so.

import * as Api from 'fetch-rest-api-wrapper';
const {
    HttpService,
    GET,
    POST,
    PUT,
    DELETE,
    Path,
    Body,
    DefaultHeaders,
    Adapter
} = Api;

Example App

<script>
    import * as Api from 'fetch-rest-api-wrapper';
    
    const {
        GET,
        POST,
        PUT,
        DELETE,
        Path,
        Body,
        DefaultHeaders,
        Adapter,
        BaseUrl
    } = Api;
    
    const commentsAdapter = (comments) => {
        console.log(comments);
        return comments.map(i => Object.assign({}, {
            title: i.name,
            email: i.email,
            body: i.body,
            id: i.id
        }));
    };
    
    @DefaultHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    })
    @BaseUrl("https://jsonplaceholder.typicode.com")
    
    export class ApiTester extends HttpService {
        
        @GET('/comments')
        @Adapter(commentsAdapter)
        public getCommentItems() {
            return null;
        }
        
        @GET("/comments/{id}")
        @Adapter(item => item)
        public getCommentItem(@Path("id") id) {}
    
        
        @POST("/posts")
        @Adapter(item => item)
        public createCommentItem(@Body com) {}
        
        
        @PUT("/posts/{id}")
        @Adapter(item => item)
        public updateCommentItem(
            @Body update,
            @Path('id') id
            ) {}
        
        @DELETE("/posts/{id}")
        @Adapter(item => item)
        public deleteComment(@Path("id") id) {}
        
    }
    
    async function init() {
        let apiInterface = new ApiTester();
        let data = await apiInterface.getCommentItems();
        let singleItem = await apiInterface.getCommentItem("1");
        let created = await apiInterface.createCommentItem({
            title: "Testing title one",
            body: " this is a testing post method",
            userId: 1
        });
    
        let updated = await apiInterface.updateCommentItem({title: "Testing this put method out yo!"}, '1');
        
        console.log(data)
        console.log(singleItem)
        console.log(created)
        console.log(updated);
    }
    init();
</script>

API

  • GET - uses a HTTP Get to the Rest Api Services
      @GET('/api/resource/')
      public myMethod () {return null}
  • POST - uses a HTTP Post to the Rest Api Services
      @POST('/api/resource/')
      public myMethod () {return null}
  • PUT - uses a HTTP Put to the Rest Api Services
      @PUT('/api/resource/')
      public myMethod () {return null}
  • DELETE - uses a DELETE Put to the Rest Api Services
      @PUT('/api/resource/')
      public myMethod () {return null}
  • BaseUrl - this allows us to set base url of our code, this way we can simply write
      @BaseUrl("http://server.com/")
      class ApiInterface extends HttpService {
          @GET('api/resource')
          public myMethod () {return null};
      }
  • DefaultHeaders - this allows us to set default headers on our code, this is set as a class decorator
         @DefaultHeaders({
             'Accept': 'application/json',
             'Content-Type': 'application/json'
         })
         class ApiInterface extends HttpService {
             @GET('api/resource')
             public myMethod () {return null};
         }
  • Headers- this allows us to set headers for each request we send to the backend.
        @Headers ({ 
          'X-Some-Common-Header': 'Some value', 
          'X-Some-Other-Common-Header': 'Some other value' 
        })
  • Adapter - this allows us to transform our response from the backend. See examples above
        @GET('https://jsonplaceholder.typicode.com/comments')
        @Adapter(commentsAdapter)
        public getCommentItems() {
            return null;
        }
  • @Path - this allows us to write the following
      @GET('/api/resource/{id}')
      public myMethod (@Path('id') id) {return null}
    This will allow us to pass an id into our function in order to replace the {id} with the value of the id parameter
  • @Body - this allows us to write the following
      @POST('/api/resource')
      public myMethod (@Body payload) {return null}
    This will allow us to pass in an object that will be sent to the backend as the request body.
  • @Query - this allows us to write the following
      @DELETE('/api/resource')
      public myMethod (@Query('filter') filter) {return null}
    This will allow us to set the query parameter of our URL
  • @Header - this allows us to write the following
      @DELETE('/api/resource')
      public myMethod (@Header('x-random-header') header) {return null}
    This will set a custom header on our request

Example

To run the example application follow these steps (github only example is not included within the NPM package)

cd example

npm install

npm start

Coming 2018

  • support for bearer token interception
  • improved response / request interception
  • Option to use observables instead of promises.

Copyright

Copyright 2018 Evan Burbidge

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago