Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-retrofit

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-retrofit

A axios based retrofit implementation for TypeScript.

  • 1.2.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
71
decreased by-84.43%
Maintainers
1
Weekly downloads
 
Created
Source

ts-retrofit

build status

A axios based retrofit implementation for TypeScript.

Installing

$ npm i ts-retrofit

Quick Overview

import {
  GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, BasePath, Header, Query,
  Headers, Path, QueryMap, Body, FormUrlEncoded, Field, FieldMap,
  BaseService, ServiceBuilder, Response
} from "ts-retrofit";
export const TEST_SERVER_HOST = "http://localhost";
export const TEST_SERVER_PORT = 12345;
export const TEST_SERVER_ENDPOINT = `${TEST_SERVER_HOST}:${TEST_SERVER_PORT}`;
export const API_PREFIX = "/api/v1";
export const TOKEN = "abcdef123456";

export interface IUser {
  id?: number;
  name: string;
  age: number;
  [x: string]: any;
}

export interface ISearchQuery {
  title?: string;
  author?: string;
  category?: string;
}

export interface IAuth {
  username: string;
  password: string;
}

export interface IPost {
  title: string;
  content: string;
}

@BasePath(API_PREFIX)
export class UserService extends BaseService {
  @GET("/users")
  async getUsers(@Header("X-Token") token: string): Promise<Response> { return <Response> {} };

  @GET("/users/{userId}")
  async getUser(@Header("X-Token") token: string, @Path("userId") userId: number): Promise<Response> { return <Response> {} };

  @POST("/users")
  async createUser(@Header("X-Token") token: string, @Body user: IUser): Promise<Response> { return <Response> {} };

  @PUT("/users/{userId}")
  async replaceUser(@Header("X-Token") token: string, @Path("userId") userId: number, @Body user: IUser): Promise<Response> { return <Response> {} };

  @PATCH("/users/{userId}")
  async updateUser(@Header("X-Token") token: string, @Path("userId") userId: number, @Body user: Partial<IUser>): Promise<Response> { return <Response> {} };

  @DELETE("/users/{userId}")
  async deleteUser(@Header("X-Token") token: string, @Path("userId") userId: number): Promise<Response> { return <Response> {} };

  @HEAD("/users/{userId}")
  async headUser(@Header("X-Token") token: string, @Path("userId") userId: number): Promise<Response> { return <Response> {} };

  @OPTIONS("/users/{userId}")
  async optionsUser(@Header("X-Token") token: string, @Path("userId") userId: number): Promise<Response> { return <Response> {} };
}

@BasePath(API_PREFIX)
export class SearchService extends BaseService {
  @GET("/search")
  async search(@Header("X-Token") token: string, @QueryMap query: ISearchQuery): Promise<Response> { return <Response> {} };
}

@BasePath("")
export class AuthService extends BaseService {
  @POST("/oauth2/authorize")
  @Headers({
    "content-type": "application/x-www-form-urlencoded",
    "Accept": "application/json"
  })
  async auth(@Body body: IAuth): Promise<Response> { return <Response> {} };
}

@BasePath(API_PREFIX)
export class PostService extends BaseService {
  @GET("/posts")
  @Query({
    page: 1,
    size: 20,
    sort: "createdAt:desc",
  })
  async getPosts(): Promise<Response> { return <Response> {} };

  @POST("/posts")
  @FormUrlEncoded
  async createPost(@Field("title") title: string, @Field("content") content: string): Promise<Response> { return <Response> {} };
  
  @POST("/posts")
  @FormUrlEncoded
  async createPost2(@FieldMap post: IPost): Promise<Response> { return <Response> {} };
}

@BasePath(API_PREFIX)
export class FileService extends BaseService {
  @POST("/upload")
  @Multipart
  async upload(@Part("bucket") bucket: PartDescriptor, @Part("file") file: PartDescriptor): Promise<Response> { return <Response> {} };
}

(async () => {
  const userService = new ServiceBuilder()
    .setEndpoint(TEST_SERVER_ENDPOINT)
    .build(UserService);
  const response = await userService.getUsers(TOKEN);
  // use response.data ...
})()

See test to get more examples.

Decorators

CategoryNameDescriptionDecorator PositionExample
HTTP Method@GETGET MethodMethod@GET("/users")
HTTP Method@POSTPOST MethodMethod@POST("/users")
HTTP Method@PUTPUT MethodMethod@PUT("/users/{userId}")
HTTP Method@PATCHPATCH MethodMethod@PATCH("/users/{userId}")
HTTP Method@DELETEDELETE MethodMethod@DELETE("/users/{userId}")
HTTP Method@HEADHEAD MethodMethod@HEAD("/users/{userId}")
HTTP Method@OPTIONSOPTIONS MethodMethod@OPTIONS("/users/{userId}")
Base Path@BasePathSpecifying the base path of a series of API endpointsClass@BasePath("/api/v1")
Static Headers@HeadersSpecifying the static headers of API endpointMethod@Headers({ "content-type": "application/x-www-form-urlencoded", "Accept": "application/json" })
Header Parameter@HeaderParameterized headerMethod Parameter@Header("X-Token")
Header Parameters@HeaderMapParameterized headerMethod Parameter@HeaderMap
Path Parameter@PathSpecifying parameter in path of APIMethod Parameter@PathParam("userId")
Body@BodySpecifying body dataMethod Parameter@Body
Static Query@QuerySpecifying static query dataMethod@Query({ page: 1, size: 20, sort: "createdAt:desc" })
Query Parameters@QueryMapParameterized queryMethod Parameter@QueryMap
Static Headers@FormUrlEncodedSpecifying "content-type" to be "application/x-www-form-urlencoded"Method@FormUrlEncoded
Field Parameter@FieldSpecifying field in method parameter, only effective when method has been decorated by @FormUrlEncodedMethod Parameter@Field("name")
Field Parameters@FieldMapSpecifying field map in method parameter, only effective when method has been decorated by @FormUrlEncodedMethod Parameter@FieldMap
Static Headers@MultipartSpecifying "content-type" to be "multipart/form-data"Method@Multipart
Part Parameters@PartSpecifying field map in method parameter, only effective when method has been decorated by @MultipartMethod Parameter@Part("name")

Test

$ npm test

Keywords

FAQs

Package last updated on 19 Dec 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc