midway-component-fetch

HTTP fetch component for midway.js

Usage no npm install needed!

<script type="module">
  import midwayComponentFetch from 'https://cdn.skypack.dev/midway-component-fetch';
</script>

README

midway-component-fetch

HTTP fetch component for midway.js

Version License Conventional Commits

Install

npm i midway-component-fetch

Usage

Update project src/configuration.ts

import * as fetch from 'midway-component-fetch'

@Configuration({
  imports: [
    fetch,
  ],
  importConfigs: [join(__dirname, 'config')],
})
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 = {
  enableTraceLoggingReqBody: true,
  enableTraceLoggingRespData: true,
  enableDefaultCallbacks: true,
  traceLoggingReqHeaders: ['authorization'],
  genRequestHeaders,
}

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

import { Inject } from '@midwayjs/decorator'
import {
  FetchComponent,
  FetchResponse,
  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