Giter VIP home page Giter VIP logo

client-core's Introduction

Client Core

test workflow stale workflow Release Draft workflow

Client Core is a library helping you to create a client RestFul API.

Installation

npm install @coaktion/client-core

Generate docs

npm run generate-docs

Usage

import {
  AxiosClient,
  ClientOptionsAxios,
  converterPathParamsUrl
} from '@coaktion/client-core';
import { AxiosResponse } from 'axios';

class ApiClient extends AxiosClient {
  constructor(clientOptions: ClientOptionsAxios) {
    super(clientOptions);
  }

  async custom(id: string): Promise<AxiosResponse> {
    return this.makeRequest(
      'GET',
      converterPathParamsUrl('/resources/{id}/custom', { id })
    );
  }
}

const apiClient = new ApiClient('https://api.example.com');

apiClient.search({ query: 'test' }).then((response) => {
  console.log(response.data);
});

apiClient.fetch('123').then((response) => {
  console.log(response.data);
});

apiClient.create({ name: 'test' }).then((response) => {
  console.log(response.data);
});

apiClient.update('123', { name: 'test' }).then((response) => {
  console.log(response.data);
});

apiClient.delete('123').then((response) => {
  console.log(response.data);
});

apiClient.custom('123').then((response) => {
  console.log(response.data);
});

License

Client Core is Copyright.

Author

GitHub

client-core's People

Contributors

andaragui avatar dependabot[bot] avatar eduardomeira avatar gabrielh-silvestre avatar inaciogu avatar joaomacedo03 avatar lukasmacedo06 avatar matheusdev20 avatar paulo-tinoco avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

sealabr

client-core's Issues

[Bug]: ZendeskClient does not return API error

Describe the bug

When extending the ZendeskClient, the makeRequest method fails to return the appropriate API call error.

Your minimal, reproducible example

none

Steps to reproduce

  1. Instantiate a client derived from ZendeskClient
  2. Intentionally trigger an error in your API request, such as by passing an incorrect parameter.
  3. Attempt to capture the error message using the catch method

Expected behavior

As a developer, I'd like if the makeRequest method relayed the error that my client's API returned.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS[Ubuntu: 20.04]
  • Typescript[4.9.5]
  • React[18.2.0]

Package version

v1.4.0

Additional context

No response

Testes de erro passariam caso caso a função não jogasse o erro.

Discussed in #82

Originally posted by andaraGui August 2, 2024
Hoje os teses de erro do pacote estão no seguinte modelo:

it('should throw ZendeskRequestError error on fail', async () => {
    mockZendeskClient.request.mockRejectedValueOnce({
      status: 400,
      responseJSON: { message: 'Request failed' }
    });

    const auth = new BearerAuthZendesk({
      zafClient: mockZendeskClient,
      baseUrl: 'http://localhost',
      endpoint: '/auth',
      bearer: {
        headers: {
          Authorization: 'Basic 123'
        }
      }
    });
    try {
      await auth.getToken();
    } catch (error) {
      expect(error.message).toEqual('Request failed');
    }
  });

Como mencionado pelo @gabrielh-silvestre nesse PR, realizar o teste utilizando o bloco try/catch pode ocasionar que o teste de cenário não valide o erro, caso não haja o mesmo.

Utilizando o cenário acima, caso a função auth.getToken() não retorne um erro, o teste irá passar da mesma maneira, sendo que o intuito do mesmo é justamente testar um cenário em que se espera que dê erro.

A sujestão de refatoração segue o seguinte modelo:

it('should throw ZendeskRequestError error on fail', async () => {
    mockZendeskClient.request.mockRejectedValueOnce({
      status: 400,
      responseJSON: { message: 'Request failed' }
    });

    const auth = new BearerAuthZendesk({
      zafClient: mockZendeskClient,
      baseUrl: 'http://localhost',
      endpoint: '/auth',
      bearer: {
        headers: {
          Authorization: 'Basic 123'
        }
      }
    });
  
     await expect(auth.getToken()).rejects.toEqual({
        message: 'Request failed',
        status: 400
     });
  });

[Bug]: Payload Zendesk needs to receive timeout and secure as params

Describe the bug

No método make request do zendesk client, deveria ser possível configurar o secure e o timeout para uma requisição específica.

Your minimal, reproducible example

none

Steps to reproduce

none

Expected behavior

Como desenvolvedora, gostaria de poder passar o timeout e o secure como parâmetro quando estou usando o método make request do zendesk.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • Node version 20.5.1
  • React version 18.2.0
  • Typescript version 4.9.5

Package version

v1.4.0

Additional context

No response

[Bug]: Autenticação inconsistente

Describe the bug

Ao definir uma classe derivada da interface AuthBasic e injetá-la no ClientBasic a autenticação não é realizada corretamente, isso porque o authProvider está sendo passado diretamente na opção de Proxy do Axios, fazendo com que o pacote não execute corretamente qualquer tipo de autenticação (com exceção da Basic Auth sem estar encapsulada por um authProvider).

Your minimal, reproducible example

No response

Steps to reproduce

  1. Importe o ClientBasic.
  2. Crie um client qualquer que necessite qualquer tipo de autenticação e extenda o ClientBasic.
  3. No construtor do novo cliente, na propriedade authProvider injete qualquer tipo de AuthBasic.
  4. Instancie o cliente e execute qualquer método que requeira autenticação.

Expected behavior

Como desenvolvedor esperava poder definir diferentes estratégias para autenticação de acordo com a API que esteja integrando, porém a única estratégia de autenticação disponível é via Basic Auth, utiilizando ainda as opções de Proxy do Axios e não do Provider interno do pacote.

How often does this bug happen?

Every time

Screenshots or Videos

Cliente de Tickets utilizando autenticação base a partir do provedor interno do pacote BasicAuth.

import { BasicAuth, ClientBasic } from '@coaktion/client-core';

export class TicketsClient extends ClientBasic {
  constructor(baseUrl: string) {
    super(baseUrl, {
      appName: 'tickets-client',
      endpoints: {
        search: '/tickets',
      },
      authProvider: new BasicAuth({
        username: '[email protected]',
        password: 'Aktie@2021!'
      })
    });
  }
}

Cliente de Tickets utilizando autenticação base a partir do Proxy do Axios.

import { ClientBasic } from '@coaktion/client-core';

export class TicketsClient extends ClientBasic {
  constructor(baseUrl: string) {
    super(baseUrl, {
      appName: 'tickets-client',
      endpoints: {
        search: '/tickets'
      },
      authProvider: {
        username: '[email protected]',
        password: 'Aktie@2021!'
      }
    });
  }
}

Platform

  • OS: Windows Sub-System for Linux (Ubuntu 20.04)
  • Node: 18.12.0
  • TypeScript: 4.9.4

Package version

v1.1.2

Additional context

Atualmente o ClientBasic injeta diretamente o authProvider na opção de Auth Proxy do Axios, porém tal opção permite apenas a passagem de um objeto JS com duas propriedades { username: string; password: string; }.

// src/base.ts

class ClientBasic implements ClientBasicInterface {
  clientOptions: ClientOptions;
  client: AxiosInstance;
  auth: object;
  constructor(baseUrl: string, clientOptions: ClientOptions) {
    this.clientOptions = clientOptions;
    this.auth = {};

    if (!this.clientOptions.timeout) this.clientOptions.timeout = 5000;
    if (typeof this.clientOptions.retryDelay !== 'number')
      this.clientOptions.retryDelay = 3;
    if (typeof this.clientOptions.tries !== 'number')
      this.clientOptions.tries = 0;

    this.client = axios.create({
      baseURL: baseUrl,
      auth: this.clientOptions.authProvider // <- Injeção do Auth Provider
    });

    axiosRetry(this.client, {
      retries: this.clientOptions.tries,
      retryDelay: this.retryDelay,
      retryCondition: this.retryCondition
    });
  }
  // ...
}

Sendo assim seria necessário outra abordagem para garantir a execução correta dos Provedores de autenticação.
Segue o link da documentação do Axios sobre essa parte de autenticação: https://axios-http.com/docs/req_config

[Bug]: Zendesk Client MakeRequest does not accept custom ContentType and it's not receiving body

Describe the bug

In the makeRequest method, the contentType is hardcoded to 'application/x-www-form-urlencoded'. Additionally, the 'data' parameter isn't being set, even when provided as an argument.

Your minimal, reproducible example

none

Steps to reproduce

  1. Define a class that inherits from ZendeskClient.
  2. Implement a custom method that invokes makeRequest.
  3. Ensure you pass the contentType and data parameters.

Expected behavior

As a developer, I'd like the ability to specify various 'contentTypes' and to utilize HTTP methods beyond just GET when employing the ZAF request client.

How often does this bug happen?

Every time

Screenshots or Videos

Captura de tela de 2023-08-15 11-18-25

Platform

  • OS: Ubuntu 20.04
  • Node: 19.1.0
  • Typescript: 4.9.5
  • React: 18.2.0

Package version

v1.3.2

Additional context

No response

[Bug]: Search All Pages and Update method

Describe the bug

  • The client-core lacked a method to retrieve all data from an API, making it essential to provide this functionality to the library users.
  • Additionally, the endpoint's update method had the PUT method hardcoded, but there was a requirement to also support the PATCH option.

Your minimal, reproducible example

none

Steps to reproduce

  1. Define a class that inherits from ZendeskClient or AxiosClient.
  2. Construct the update endpoint.
  3. Invoke the update method and observe that the PATCH method cannot be called.

Expected behavior

  • As a developer, I wanted the ability to fetch all data from an endpoint.
  • Additionally, I hoped to utilize the PATCH method when using update endpoint.

How often does this bug happen?

Every time

Screenshots or Videos

Captura de tela de 2023-08-18 10-30-04

Platform

  • OS: Ubuntu 20.04
  • Node: 19.1.0
  • Typescript: 4.9.5
  • React: 18.2.0

Package version

v1.3.3

Additional context

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.