Skip to content

Commit

Permalink
feat(core): support other options for fetch request
Browse files Browse the repository at this point in the history
  • Loading branch information
zoomchan-cxj committed Jun 21, 2022
1 parent a789975 commit 762494a
Show file tree
Hide file tree
Showing 16 changed files with 253 additions and 100 deletions.
37 changes: 19 additions & 18 deletions core/js/global/Network.js
Expand Up @@ -22,7 +22,6 @@ global.Headers = class Headers {
if (typeof name !== 'string' || typeof value !== 'string') {
return;
}

if (this.has(name)) {
const curr = this._headers[name];
curr.push(value);
Expand All @@ -36,23 +35,20 @@ global.Headers = class Headers {
if (typeof name !== 'string' || typeof value !== 'string') {
return;
}

this._headers[name] = [value];
}

getAll() {
if (!this._headers['Content-Type'] && !this._headers['content-type']) {
this._headers['content-type'] = ['text/plain;charset=UTF-8'];
}
const ret = Object.assign({}, this._headers);
return ret;
return Object.assign({}, this._headers);
}

delete(name) {
if (typeof name !== 'string') {
return;
}

if (typeof this._headers[name] !== 'undefined') {
delete this._headers.name;
}
Expand All @@ -62,23 +58,21 @@ global.Headers = class Headers {
if (typeof name !== 'string') {
return undefined;
}

return this._headers[name];
}

has(name) {
if (typeof name !== 'string') {
return false;
}

return (typeof this._headers[name] !== 'undefined');
}
};

global.Response = class Response {
constructor(response) {
const resp = response || {};
this.status = resp.statusCode || 404;
this.status = resp.statusCode === undefined ? 200 : resp.statusCode;
this.statusText = resp.statusLine || 'Not Found';
this.headers = resp.respHeaders || {};
this.body = resp.respBody || '';
Expand All @@ -102,37 +96,44 @@ global.Response = class Response {
}
};

const methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];

function normalizeMethod(method) {
const upCased = method.toUpperCase();
return methods.indexOf(upCased) > -1 ? upCased : method;
}

global.fetch = (url, options) => {
if (typeof url !== 'string') {
return Promise.reject(new Error('only String url supported'));
}

const opts = options || {};

const { method, headers, body, ...otherOptions } = options || {};
let reqHeads = {};
if (opts.headers) {
if (opts.headers instanceof Headers) {
reqHeads = opts.headers.getAll();
} else if (opts.headers.constructor === Object) {
const headers = new Headers(opts.headers);
if (headers) {
if (headers instanceof global.Headers) {
reqHeads = headers.getAll();
} else if (headers.constructor === Object) {
const headersInstance = new global.Headers(headers);
reqHeads = headersInstance.getAll();
} else {
return Promise.reject(new Error('Only Headers instance or a pure object is acceptable for headers option'));
}
}

const reqOptions = {
method: opts.method || 'GET',
url,
method: normalizeMethod(method || 'GET'),
headers: reqHeads || {},
body: opts.body || '',
body: body || '',
...otherOptions,
};

return new Promise((resolve, reject) => {
const result = Hippy.bridge.callNativeWithPromise('network', 'fetch', reqOptions);
result.then((resp) => {
if (typeof resp === 'object') {
const responseData = new Response(resp);
const responseData = new global.Response(resp);
resolve(responseData);
} else {
reject(resp);
Expand Down
4 changes: 2 additions & 2 deletions core/src/napi/jsc/native_source_code_ios.cc

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions core/src/napi/v8/native_source_code_android.cc

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions docs/en-us/guide/network-request.md
Expand Up @@ -20,6 +20,8 @@ fetch('//mywebsite.com/mydata.json');

The `fetch` function also supports the configuration of HTTP requests.

> only support `method | headers | body` parameters at lower version, version `2.14.0` or above support any customized parameters, e.g. `redirect: 'follow'`
```javascript
fetch('//mywebsite.com/endpoint/', {
method: 'POST',
Expand All @@ -31,6 +33,7 @@ fetch('//mywebsite.com/endpoint/', {
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
redirect: 'follow', // version `2.14.0` or above
});
```

Expand Down
9 changes: 5 additions & 4 deletions docs/en-us/hippy-react/modules.md
Expand Up @@ -336,7 +336,7 @@ Asynchronously determines whether the device is connected to the Internet and wh
### NetInfo.fetch

`() => Promise<NetInfo>` Used to obtain the current network status.
`() => Promise<string>` Used to obtain the current network status.

### NetInfo.removeEventListener

Expand All @@ -360,14 +360,15 @@ For common network requests,, please refer to: [Getting Started - Network Reques
`(url: string) => Promise<string>` Get all cookies for the specified url

>- url: string - The target url that needs to get the cookie.
>- return value: `Promise<string>`, return string like `name=hippy;network=mobile`.
### NetworkModule.setCookie

`(url: string, keyValue: string, expires?: String) => <void> Set cookie
`(url: string, keyValue: string, expires?: Date) => <void> Set cookie

>- url: string - The target url that needs to set the cookie.
>- keyValue: string - Key-value pair to set.
>- expires?: string - Set the timeout for cookies.
>- keyValue: string - Key-value pair to set, e.g. `name=hippy;network=mobile`.
>- expires?: Date - Set the timeout for cookies.
---

Expand Down
6 changes: 3 additions & 3 deletions docs/en-us/hippy-vue/vue-native.md
Expand Up @@ -257,7 +257,7 @@ The `set-cookie` Header returned by the fetch service in Hippy will automaticall

Return Value:

* `Prmoise<string>`, like `name=someone;Gender=female` string, need to manually parse.
* `Prmoise<string>` like `name=hippy;network=mobile` string.

### set(url, keyValue, expireDate)

Expand All @@ -266,7 +266,7 @@ Attributes:
| Props | Type | Require | Description |
| -------- | -------- | -------- | -------- |
| url | string | yes | Gets the cookie set under the specified URL |
| keyValue | string | yes | The full string that needs to be set to the Cookie, for example`name=someone;gender=female` |
| keyValue | string | yes | The full string that needs to be set to the Cookie, for example`name=hippy;network=mobile` |
| expireDate | Date | no | Date type of expiration time, it will not expired if not fill in. |

---
Expand Down Expand Up @@ -354,7 +354,7 @@ Determine whether the device is connected to the Internet and used a mobile data
### NetInfo.fetch

`() => Promise<NetInfo>` Used to get the current network status.
`() => Promise<string>` Used to get the current network status.

### NetInfo.removeEventListener

Expand Down
3 changes: 3 additions & 0 deletions docs/guide/network-request.md
Expand Up @@ -20,6 +20,8 @@ fetch('//mywebsite.com/mydata.json');

fetch 函数也支持 HTTP 请求的配置。

> 低版本仅支持 `method | headers | body` 参数设置,`2.14.0` 及以上版本支持所有自定义参数透传,如 `redirect: 'follow'`
```javascript
fetch('//mywebsite.com/endpoint/', {
method: 'POST',
Expand All @@ -31,6 +33,7 @@ fetch('//mywebsite.com/endpoint/', {
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
redirect: 'follow', // `2.14.0` 及以上版本支持
});
```

Expand Down
15 changes: 8 additions & 7 deletions docs/hippy-react/modules.md
Expand Up @@ -306,7 +306,7 @@ AsyncStorage 是一个简单的、异步的、持久化的 Key-Value 存储系

[[NetInfo 范例]](//github.com/Tencent/Hippy/tree/master/examples/hippy-react-demo/src/modules/NetInfo)

通过该接口可以获得当前设备的网络状态也可以注册一个监听器,当系统网络切换的时候,得到一个通知
通过该接口可以获得当前设备的网络状态也可以注册一个监听器,当系统网络切换的时候,得到网络变化通知

安卓的开发者,在请求网络状态之前,你需要在 app 的 `AndroidManifest.xml` 加入以下配置 :

Expand Down Expand Up @@ -336,7 +336,7 @@ AsyncStorage 是一个简单的、异步的、持久化的 Key-Value 存储系
### NetInfo.fetch

`() => Promise<NetInfo>` 用于获取当前的网络状态。
`() => Promise<string>` 用于获取当前的网络状态。

### NetInfo.removeEventListener

Expand All @@ -357,17 +357,18 @@ AsyncStorage 是一个简单的、异步的、持久化的 Key-Value 存储系

### NetworkModule.getCookies

`(url: string) => Promise<string>` 获取指定 url 的所有 cookie
`(url: string) => Promise<string>` 获取指定 url 下的所有 cookies

> - url: string - 需要获取 cookie 的目标 url
> - 返回值:`Prmoise<string>`,获取到诸如 `name=hippy;network=mobile` 的字符串。
### NetworkModule.setCookie

`(url: string, keyValue: string, expires?: string) => Promise<void>` 设置 Cookie
`(url: string, keyValue: string, expires?: Date) => Promise<void>` 设置 Cookie

> - url: string - 需要获取 cookie 的目标 url
> - keyValue: string - 需要设置的键值对
> - expires?: string - 设置 Cookie 的超市时间
> - url: string - 需要设置 cookie 的目标 url
> - keyValue: string - 需要设置的键值对,如 `name=hippy;network=mobile`
> - expires?: Date - 设置 Cookie 的过期时间,默认为空,会通过 `toUTCString` 转成 `String` 传给客户端
---

Expand Down
16 changes: 8 additions & 8 deletions docs/hippy-vue/vue-native.md
Expand Up @@ -245,29 +245,29 @@ Vue.Native.AsyncStorage.getItem('itemKey');

# Cookie

Hippy 中通过 fetch 服务返回的 `set-cookie` Header 会自动将 Cookie 保存起来,下次再发出请求的时候就会带上,然后终端提供了这个界面让 业务可以获取或者修改保存好的 Cookie。
Hippy 中通过 fetch 服务返回的 `set-cookie` Header 会自动将 Cookie 保存起来,下次再发出请求的时候就会带上,业务可以获取或者修改保存好的 Cookie。

## 方法

### getAll(url)

| 参数 | 类型 | 必需 | 参数意义 |
| -------- | -------- | -------- | -------- |
| url | string || 获取指定 URL 下设置的 cookie |
| url | string || 获取指定 url 下的所有 cookies |

返回值:

* `Prmoise<string>`类似 `name=someone;gender=female` 的字符串,需要业务自己手工解析一下
* `Prmoise<string>`获取到诸如 `name=hippy;network=mobile` 的字符串。

### set(url, keyValue, expireDate)

参数:

| 参数 | 类型 | 必需 | 参数意义 |
| -------- | -------- | -------- | -------- |
| url | string | | 设置指定 URL 下设置的 cookie |
| keyValue | string | | 需要设置成 Cookie 的完整字符串,例如`name=someone;gender=female` |
| expireDate | Date || Date 类型的过期时间,不填不过期 |
| url | string || 设置指定 URL 下设置的 cookie |
| keyValue | string || 需要设置成 cookie 的完整字符串,例如 `name=hippy;network=mobile` |
| expireDate | Date || Date 类型的过期时间,不填不过期, 内部会通过 `toUTCString` 转成 `String` 传给客户端 |

---

Expand Down Expand Up @@ -324,9 +324,9 @@ console.log(Vue.Native.getElemCss(this.demon1Point)) // => { height: 80, left: 0

# NetInfo

通过该接口可以获得当前设备的网络状态也可以注册一个监听器,当系统网络切换的时候,得到一个通知
通过该接口可以获得当前设备的网络状态也可以注册一个监听器,当系统网络切换的时候,得到网络变化通知

> 最低支持版本 2.7.0
> 最低支持版本 `2.7.0`
安卓的开发者,在请求网络状态之前,你需要在app的 `AndroidManifest.xml` 加入以下配置 :

Expand Down
2 changes: 1 addition & 1 deletion examples/android-demo/res/index.android.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/android-demo/res/vendor.android.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 762494a

Please sign in to comment.