npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-api-service-layer

v1.0.0

Published

Simple way to compose from multiple providers

Downloads

13

Readme

React API Service Layer

Give your application an API service layer! Define Service Classes that utilize the abstract ApiService. The benefit to ApiService is it has abstract api-typical methods so one can use it as a mocking service or as an implementation of your faviorite request library.

Generally you'll want to:

  1. Implement your own ApiService(s)
  2. Create Service Classes that utilize your ApiServices (created in step 1)
  3. Use the provided hooks to create memoizations of those services for your custom-hooks/components

Installation

npm install --save react-api-service-layer

Usage

Implementing ApiService

You'll want to implement your own ApiService classes. Perhaps you'll want to use Axios:

import { ApiService } from 'react-api-service-layer';
import axios from 'axios';

class AxiosApiService extends ApiService {
    baseUrl: string = 'http://my-api.com';

    //  Override the get for this example
    get(resourcePath: string, options?: any): Promise<any> {
        return axios.get(`${this.baseUrl}${resourcePath}`);
    }

    post(resourcePath: string, payload: any, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

    put(resourcePath: string, payload: any, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

    patch(resourcePath: string, payload: any, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

    delete(resourcePath: string, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

}

Or maybe you'll want to create some data mocking service:

import { ApiService } from 'react-api-service-layer';

const mockGets = {
    '/todos': []
}

class MockApiService extends ApiService {

    //  Override the get for this example
    get(resourcePath: string, options?: any): Promise<any> {
        return mockGets[resourcePath];
    }

    post(resourcePath: string, payload: any, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

    put(resourcePath: string, payload: any, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

    patch(resourcePath: string, payload: any, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

    delete(resourcePath: string, options?: any): Promise<any> {
        throw new Error('Method not implemented.');
    }

}

Build Service Classes

Composition Pattern

Personally, I'm a big fan of composition pattern.

import { ApiService } from 'react-api-service-layer';

class TodoService {
    apiService: APIService

    getTodos() {
        return this.apiService.get('path-to-my-service');
    }
}

Inheritance Pattern

Surely you can inherit your api service well enough

class TodoService extends AxiosApiService {
    getTodos() {
        return this.get('/todos')
    }
}

Use Service Classes in React

The hooks provided describe patterns for setting the ApiService in your Service Classes.

useService

useService is generically typed, so you'll need to provide the typing AND the class. Any additional constructor params are optional from there on out.

Constructor pattern
import { useService, ApiService, useConstructableApiService } from 'react-api-service-layer';

class TodoService {
    apiService: APIService

    constructor (apiService: ApiService) {
        this.apiService = apiService;
    }

    getTodos() {
        return this.apiService.get('path-to-my-service');
    }
}

const MyComponent = () => {
    const apiService = useService<AxiosApiService>(AxiosApiService);
    const todoService = useService<TodoService>(TodoService, apiService);

    React.useEffect( async () => {
        const todos = await todoService.getTodos();
        console.log('Todos:', todos);
    }, []);
    
    return (
        <div>
            Hello World
        </div>
    )
}
Setter pattern
import { useService, ApiService, useConstructableApiService } from 'react-api-service-layer';

class TodoService {
    apiService: APIService

    setApiService(apiService: ApiService) {
        this.apiService = apiService;
    }

    getTodos() {
        return this.apiService.get('path-to-my-service');
    }
}

const MyComponent = () => {
    const apiService = useService<AxiosApiService>(AxiosApiService);
    const todoService = useService<TodoService>(TodoService);
    
    React.useEffect( async () => {
        todoService.setApiService(apiService);
        const todos = await todoService.getTodos();
        console.log('Todos:', todos);
    }, []);
    
    return (
        <div>
            Hello World
        </div>
    )
}