@mwcp/fetch
TypeScript icon, indicating that this package has built-in type declarations

30.0.1 • Public • Published

midway-component-fetch

HTTP fetch component for midway.js

Version License Conventional Commits

Note

ESM build only, requires @midwayjs >= 3.12 and set "type": "module" in packages.json

Install

npm i @mwcp/fetch

Usage

Update project src/configuration.ts

import * as fetch from '@mwcp/fetch'

@Configuration({
  imports: [
    fetch,
  ],
})
export class ContainerConfiguration implements ILifeCycle {
}

Update project src/config/config.(prod | local | unittest).ts

import { FetchComponentConfig, genRequestHeaders } from 'midway-component-fetch'

export const fetch: FetchComponentConfig = {
  // change to only authorization
  traceLoggingReqHeaders: ['authorization'],
}

Update project base service like src/core/base.service.ts

import { Inject } from '@midwayjs/decorator'
import {
  FetchComponent,
  ResponseData,
  Options as FetchOptions,
} from 'midway-component-fetch'

export class BaseService extends RootClass {
  @Inject() readonly fetch: FetchComponent

  /**
   * 返回类型为 `text` 或者 `html`
   */
  getText<T extends string = string>(
    url: string,
    data?: FetchOptions['data'],
  ): Promise<T> {

    const opts: FetchOptions = {
      ...this.initFetchOptions,
      dataType: 'text',
    }
    if (typeof data !== 'undefined') {
      opts.data = data
    }
    const ret = this.fetch.get<T>(url, opts)
    return ret as Promise<T>
  }

  /**
   * Generate an RxRequestInit variable,
   * @default
   *   - contentType: 'application/json; charset=utf-8'
   *   - dataType: 'json'
   */
  get initFetchOptions(): FetchOptions {
    const args: FetchOptions = {
      url: '',
      method: 'GET',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
    }
    return args
  }
}

Update project service like src/home/home.service.ts

import { Provide } from '@midwayjs/decorator'

import { BaseService } from '~/interface'


@Provide()
export class HomeService extends BaseService {

  /**
   * 获取网关 IP
   */
  async retrieveGatewayIp(): Promise<string> {
    const url = 'https://www.taobao.com/help/getip.php'
    // ipCallback({ip:"222.233.10.1"})
    const text = await this.getText(url)
    let ip = ''
    if (text) {
      const arr = /"([\d.]+)"/ui.exec(text)
      ip = arr && arr.length >= 1 && arr[1] ? arr[1] : ''
    }
    this.logger.info({ ip })
    return ip
  }

}

License

MIT

Package Sidebar

Install

npm i @mwcp/fetch

Weekly Downloads

383

Version

30.0.1

License

MIT

Unpacked Size

64.3 kB

Total Files

61

Last publish

Collaborators

  • waiting