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

@ithinkdt/http

v1.2.2

Published

ithinkdt http库

Downloads

16

Readme

@ithinkdt/http

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

安装

Using npm:

$ npm install @ithinkdt/http

Using yarn:

$ yarn add @ithinkdt/http

API

1、相关接口

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

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

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

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

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'
}

示例

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

import { LocalStorage } from '@ithinkdt/storage';
import {
  HttpFactory,
  IHttpHandler,
  ITokenHandler,
  ILoadingHandler,
  IResponseHandler,
  HttpInstanceTypeEnum,
} from '@packages/http';
import { TOKEN } from '../constants';

export class BaseService {
  protected httpInstance: IHttpHandler;

  constructor() {
    const commonOptions: any = {};
    const tokenHandler: ITokenHandler = new TokenHandler();
    const loadingHandler: ILoadingHandler = new LoadingHandler();
    const responseHandler: IResponseHandler = new ResponseHandler();
    const httpFactory = new HttpFactory(commonOptions, tokenHandler, loadingHandler, responseHandler);
    this.httpInstance = httpFactory.getHttpInstance(HttpInstanceTypeEnum.Axios);// 工厂创建指定实现类axios或者fetch
  }
}

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

  public clearToken() {
    LocalStorage.removeItem(TOKEN);
  }
}

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

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

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

    const code = result.code;
    if (code === '0000' && result.status) {
      return Promise.resolve(result);
    } else if (code === '1002') {
      clearTokenHandler && clearTokenHandler();
      return Promise.reject('');
    } else {
      return Promise.reject(result.messages);
    }
  }
}

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

import { HttpTypeEnum } from '@packages/http';
import { BaseService } from './base.service';

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);
  }
}