@waiting/egg-fetch

fetch for egg, midway

Usage no npm install needed!

<script type="module">
  import waitingEggFetch from 'https://cdn.skypack.dev/@waiting/egg-fetch';
</script>

README

egg-fetch

RxxFetch for midway/egg framework.

Version License Conventional Commits

Installation

npm i @waiting/egg-fetch

Configuration

Enable Plugin

Edit ${app_root}/src/config/plugin.ts:

export const fetch = {
  enable: true,
  package: '@waiting/egg-fetch',
}

Add Configurations

/* location: ${app_root}/src/config/config.${env}.ts */

import { FetchConfig } from '@waiting/egg-fetch'

export const fetch: FetchConfig = {
  client: {
    timeout: 60 * 1000, // ms
  },
}

Usage

import { provide, plugin } from 'midway'
import { Fetch, JsonType, RxRequestInit } from '@waiting/egg-fetch'

@provide()
export class UserService {

  constructor(
    @plugin() private readonly fetch: Fetch,
  ) { }

  @get('/test_json')
  async public testJson(ctx: Context) {
    const url = 'https://httpbin.org/get'
    const json = await this.fetch.get<HttpbinGetResponse>(url).toPromise()
    ctx.body = `\nurl: ${json.url}`
  }

  @get('/test_html')
  async public testHtml(ctx: Context) {
    const url = 'https://httpbin.org/get'
    const args: RxRequestInit = {
      dataType: 'text'
    }
    const html = await this.fetch.get<string>(url, args).toPromise()
    ctx.body = `\nhtml: ${html}`
  }

}

/** GET Response Interface of httpbin.org */
export interface HttpbinGetResponse extends JsonType {
  args: any
  headers: {
    Accept: string
    Connection: string
    Host: string
    'User-Agent': string,
  }
  origin: string  // ip
  url: string
}

Documentation

License

MIT

Languages