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

tsx-http

v1.0.0

Published

http请求响应方法库,基于axios、fetch等实现,同时暴露ITokenHandler、ILoadingHandler、IResponseHandler接口实现定制化需求

Downloads

1

Readme

tsx-http

http 请求响应方法库,基于 axios、fetch 等实现,同时暴露 IRequestHandler、IResponseHandler、ITokenHandler、ILoadingHandler 接口实现定制化需求。

Installing

Using npm:

$ npm install tsx-http

API

1、相关接口

/**
 * http处理器接口
 */
export interface IHttpHandler {
  invoke<T>(options?: any, type?: HttpTypeEnum): Promise<T>;
  get<T>(url: string, data?: any, type?: HttpTypeEnum): Promise<T>;
  post<T>(url: string, data?: any, type?: HttpTypeEnum): Promise<T>;
  postJson<T>(url: string, data?: any, type?: HttpTypeEnum): Promise<T>;
}

/**
 * 请求处理器接口
 */
export interface IRequestHandler {
  handleRequest(options: any): void;
}

/**
 * 响应处理器接口
 */
export interface IResponseHandler {
  handleResponse(result: any, clearTokenHandler?: any): any;
}

/**
 * 令牌处理器接口
 */
export interface ITokenHandler {
  getToken: (options: any) => void;
  clearToken: () => void;
}

/**
 * 加载处理器接口
 */
export interface ILoadingHandler {
  showLoading: () => void;
  hideLoading: () => void;
}

2、相关枚举

/**
 * 【HTTP】实例类型枚举
 */
export enum HttpInstanceTypeEnum {
  Axios = 0, // 基于axios实现
  Fetch = 1, // 基于fetch实现
  Ajax = 2, // 基于jquery ajax实现
}

/**
 * 【HTTP】类型枚举
 */
export enum HttpTypeEnum {
  Default = 0, // 默认
  Token = 1, // token
  Loading = 2, // 加载
  TokenLoading = 3, // token&&加载
}

/**
 * 【HTTP】请求方法枚举
 */
export enum HttpMethodEnum {
  Get = 'GET',
  Post = 'POST',
  Put = 'PUT',
  Head = 'HEAD',
  Delete = 'DELETE',
  Connect = 'CONNECT',
  Options = 'OPTIONS',
  Trace = 'TRACE',
}

/**
 * 【HTTP】内容类型枚举
 */
export enum HttpContentTypeEnum {
  Form = 'application/x-www-form-urlencoded; charset=UTF-8',
  Json = 'application/json; charset=UTF-8',
  FormData = 'multipart/form-data',
}

/**
 * 【HTTP】响应类型枚举
 */
export enum HttpResponseTypeEnum {
  Xml = 'xml',
  Html = 'html',
  Text = 'text',
  Script = 'script',
  Json = 'json',
  Jsonp = 'jsonp',
}

Example

1、通过工厂创建指定实现类 axios 或者 fetch,并且实现相关定制化接口;

import {
  HttpFactory,
  IHttpHandler,
  ITokenHandler,
  ILoadingHandler,
  IResponseHandler,
  HttpInstanceTypeEnum,
} from 'tsx-http';

export class BaseService {
  protected httpInstance: IHttpHandler;

  constructor() {
    const commonOptions: any = {};
    const requestHandler: IRequestHandler = new RequestHandler();
    const responseHandler: IResponseHandler = new ResponseHandler();
    const tokenHandler: ITokenHandler = new TokenHandler();
    const loadingHandler: ILoadingHandler = new LoadingHandler();
    const httpFactory = new HttpFactory(commonOptions, requestHandler, responseHandler, tokenHandler, loadingHandler);
    this.httpInstance = httpFactory.getHttpInstance(HttpInstanceTypeEnum.Axios);
  }
}

// 定制化需求:request处理器实现类
class RequestHandler implements IRequestHandler {
  public handleRequest(options: any): Promise<any> {
    options['custom-field'] = 'hello world';
  }
}

// 定制化需求:response处理器实现类
class ResponseHandler implements IResponseHandler {
  public handleResponse(result: any, clearTokenHandler?: any): Promise<any> {
    if (!result) return Promise.reject('Exceptional data');

    // result: {status,code,data,msg}
    const code = result.code;
    if (code === '0000' && result.status) {
      // 响应成功
      return Promise.resolve(result);
    } else if (code === '1002') {
      // token失效
      clearTokenHandler && clearTokenHandler();
      return Promise.reject('');
    } else {
      return Promise.reject(result.msg);
    }
  }
}

// 定制化需求:token处理器实现类
class TokenHandler implements ITokenHandler {
  public getToken(options: any) {
    const token = 'de3a63efc';
    options['headers']['Authorization'] = token ? `Bearer ${token}` : '';
  }

  public clearToken() {
    // remove token
  }
}

// 定制化需求:loading处理器实现类
class LoadingHandler implements ILoadingHandler {
  public showLoading() {
    // console.log('ILoadingHandler showLoading');
  }

  public hideLoading() {
    // console.log('ILoadingHandler hideLoading');
  }
}

2、通过实现类 BaseService 处理各个模块的服务请求;

export class TestService extends BaseService {
  async testGet(params: any): Promise<string> {
    return await this.httpInstance.get<string>('url', params, HttpTypeEnum.Token);
  }

  async testPost(params: any): Promise<boolean> {
    return await this.httpInstance.post<boolean>('url', params, HttpTypeEnum.Loading);
  }

  async testPost(params: any): Promise<UserModel> {
    return await this.httpInstance.postJson<UserModel>('url', params, HttpTypeEnum.TokenLoading);
  }
}