-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathrequest.ts
86 lines (80 loc) · 2.43 KB
/
request.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import axios from 'axios'
import F from './dev/file.js'
import { getLocalCookies, getLocalUserConfig, setJSONString } from './tool.js'
import { config as CONFIG } from '../core/config.js'
import { Log } from './dev/log.js'
const getHost = async () => {
const { host } = await getLocalUserConfig()
return host || CONFIG.host
}
const withBodyParamsRequest = <T>(
url: string,
method: 'post' | 'put',
params: any,
header?: object
): Promise<{ data: T }> => {
return new Promise(async (resolve, reject) => {
// 登录接口统一使用yuque域名
const config = {
url: (/login/.test(url) ? CONFIG.host : await getHost()) + url,
method: method,
data: params,
headers: Object.assign(header || {}, {
'content-type': 'application/json',
'x-requested-with': 'XMLHttpRequest',
cookie: getLocalCookies(),
}),
}
axios(config)
.then((res) => {
if (res.headers['set-cookie']) {
const cookieContent = setJSONString({
expired: Date.now(),
data: res.headers['set-cookie'],
})
F.touch2(CONFIG.cookieFile, cookieContent)
}
resolve(res.data)
})
.catch((error) => {
Log.error(error.code, {
title: `${method.toUpperCase()}请求出错`,
body: `${error},${config.url}`,
})
reject(error.code)
})
})
}
export const get = <T>(url: string): Promise<{ data: T }> => {
const cookie = getLocalCookies()?.data
if (!cookie) {
Log.error('本地cookie加载失败,程序中断')
process.exit(0)
}
return new Promise(async (resolve, reject) => {
// console.log('请求地址', getHost() + url)
const config = {
url: (await getHost()) + url,
method: 'get',
headers: {
'content-type': 'application/json',
'x-requested-with': 'XMLHttpRequest',
cookie: cookie,
},
}
axios(config)
.then((res) => {
resolve(res.data)
})
.catch((error) => {
Log.error(error.code, { title: 'GET请求出错', body: `${error},${config.url}` })
reject(error.code)
})
})
}
export const post = <T>(url: string, params: any, header?: object): Promise<{ data: T }> => {
return withBodyParamsRequest(url, 'post', params, header)
}
export const put = <T>(url: string, params: any, header?: object): Promise<{ data: T }> => {
return withBodyParamsRequest(url, 'put', params, header)
}