1.2.0 • Published 3 months ago

ts-fetcheasy v1.2.0

Weekly downloads
-
License
ISC
Repository
github
Last release
3 months ago

Fetcheasy, declarative typescript API

Decorator based declarative API clients.

Installation

Install NPM package:

npm install ts-fetcheasy --save

Limitation: Min nodejs version is 18.0.0, which have fetch API globally available without polyfill, etc.

Usage

Define API (as class)

import { Get, Json, MediaType, PathParam, Post } from 'fetcheasy';

export class BooksApi {
  @Get({ path: '/books/:id', consumes: MediaType.APPLICATION_JSON })
  async get(@PathParam('id') id: string): Promise<Book> {}

  @Post({ path: '/books', consumes: MediaType.APPLICATION_JSON })
  async add(@Json() jsonData: object): Promise<Book> {}

  @Delete('/books/:id')
  async delete(@PathParam('id') id: string): Promise<Response> {}
}

Get defined API via factory and use

const booksApi = FetcheasyApiFactory.builder()
  .baseUrl('http://host')
  .basicAuthentication('test', 'test')
  .build(BooksApi);

// Add new book
let book = booksApi.add({ name: 'book' });
// Get book by id
book = booksApi.get('1');
// Delete book by id
booksApi.delete('1');

Frameworks integrations

Nestjs (typescript / nodejs)

import {
  FetcheasyApiFactory,
  logRequestInterceptor,
  logResponseInterceptor,
} from 'ts-fetcheasy';

@Module({
  providers: [
    {
      provide: BooksApi,
      useFactory: (configService: ConfigService) => {
        return FetcheasyApiFactory.builder()
          .baseUrl(configService.getOrThrow('BASE_PATH'))
          .basicAuthentication(
            configService.getOrThrow('USER'),
            configService.getOrThrow('PASS'),
          )
          .requestInterceptor(logRequestInterceptor)
          .responseInterceptor(logResponseInterceptor)
          .build(BooksApi);
      },
      inject: [ConfigService],
    },
  ],
  exports: [BooksApi],
})
export class BooksModule {}
1.2.0

3 months ago

1.1.0

4 months ago

1.0.0

6 months ago

0.0.1

6 months ago