Coder Social home page Coder Social logo

npwork / ts-retrofit2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nullcc/ts-retrofit

7.0 3.0 1.0 699 KB

A declarative and axios based retrofit implementation for JavaScript and TypeScript.

License: MIT License

JavaScript 0.61% TypeScript 99.18% Shell 0.21%

ts-retrofit2's Introduction

ts-retrofit 2

Declarative and type-safe HTTP client for Node.js and Web

build status github package npm package npm downloads license

Test coverage

Statements Branches Functions Lines
Statements Branches Functions Lines

Installing

Using npm:

$ npm install ts-retrofit2

Using yarn:

$ yarn add ts-retrofit2

Introduction

Automatically turn your decorated methods into axios HTTP requests.

export class GitHubService extends BaseService {
  @GET("/users/{user}/repos")
  listRepos(@Path("user") user: string): ApiResponse<Repo[]> {}
}

Build a service:

const service = new ServiceBuilder()
  .baseUrl("https://api.github.com/")
  .build(GitHubService);

const repose = await service.listRepos("octocat");

Use decorators to describe the HTTP request.

Inlined response body

If you need only response body you can inline it

export class GitHubService extends BaseService {
  @GET("/users/{user}/repos")
  listReposWithInlinedBody(@Path("user") user: string): ApiResponseBody<Repo[]> {}
}
const service = new ServiceBuilder()
  .baseUrl("https://api.github.com/")
  .inlineResponseBody()
  .build(GitHubService);

const repose = await service.listRepos("octocat");

API Declaration

Decorators on the methods and its parameters indicate how a request will be handled.

REQUEST METHOD

Every method must have an HTTP decorator that provides the request method and relative URL. There are built-in decorators: GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD. The relative URL of the resource is specified in the decorator param.

@GET("users/list")

You can also specify query parameters in the URL.

@GET("users/list?sort=desc")

URL MANIPULATION

A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }. A corresponding parameter must be decorated with @Path using the same string.

@GET("group/{id}/users")
groupList(@Path("id") groupId: string): ApiResponse<User[]> {}

Query parameters can also be added using @Query.

@GET("group/{id}/users")
groupList(@Path("id") groupId: string, @Query("sort") sort: string): ApiResponse<User[]> {}

For complex query parameter can be added using @QueryMap. It should be object with primitive properties.

@GET("group/{id}/users")
groupList(@Path("id") groupId: string, @QueryMap query: SearchQuery): ApiResponse<User[]> {}

REQUEST BODY

@POST("users/new")
groupList(@Body user: User): ApiResponse<User> {}

FORM ENCODED AND MULTIPART

@POST("/user/edit")
@FormUrlEncoded
formUrlEncoded(
  @Field("first_name") first: string,
  @Field("last_name") last: string,
): ApiResponse<User> {}

Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part decorator.

@PUT("user/photo")
@Multipart
updateUser(
  @Part("description") description: PartDescriptor<string>,
  @Part("photo") file: PartDescriptor<Buffer>,
): ApiResponse<User> {}

HEADER MANIPULATION

You can set static headers for a method using the @Headers decorator.

@GET("widget/list")
@Headers({
  "Cache-Control": "max-age=640000",
})
widgetList(): ApiResponse<Widget> {}
@GET("users/{username}")
@Headers({
  "Accept": "application/vnd.github.v3.full+json",
  "User-Agent": "Retrofit-Sample-App"
})
getUser(@Path("username") username: string): ApiResponse<Widget> {}

A request Header can be updated dynamically using the @Header decorator. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.

@GET("user")
getUser(@Header("Authorization") authorization: string): ApiResponse<User> {}

Similar to query parameters, for complex header combinations, a @HeaderMap can be used.

@GET("user")
getUser(@HeaderMap headers: MyHeaders): ApiResponse<User> {}

Headers that need to be added to every request can be specified using an interceptor.

ts-retrofit2's People

Contributors

dependabot[bot] avatar mend-bolt-for-github[bot] avatar npwork avatar nullcc avatar pboymt avatar renovate-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

vijaemanlapaz

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.