Skip to content

Commit d2409e6

Browse files
committed
Added the method of getting the request result through the callback function
1 parent 1a31ddd commit d2409e6

File tree

3 files changed

+81
-67
lines changed

3 files changed

+81
-67
lines changed

src/index.ts

+54-38
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,13 @@ import {
2121
IFetchFileConfig,
2222
IFetchPollingConfig,
2323
IFetchBaseConifg,
24-
IFetchCommon,
2524
IFileInfo,
2625
IFetchHTML,
2726
IRequestResItem,
2827
IRequestConfig,
29-
IIntervalTime
28+
IIntervalTime,
29+
IFetchCommon,
30+
IFetchCommonArr
3031
} from './types'
3132

3233
export default class XCrawl {
@@ -73,23 +74,24 @@ export default class XCrawl {
7374

7475
private async useBatchRequestByMode(
7576
requestConifg: IRequestConfig | IRequestConfig[],
76-
intervalTime: IIntervalTime | undefined
77+
intervalTime: IIntervalTime | undefined,
78+
callback: (requestResItem: IRequestResItem) => void
7779
) {
7880
const requestConfigQueue = isArray(requestConifg)
7981
? requestConifg
8082
: [requestConifg]
8183

82-
let requestRes: IRequestResItem[] = []
8384
if (this.baseConfig.mode !== 'sync') {
84-
requestRes = await batchRequest(requestConfigQueue, intervalTime)
85+
await batchRequest(requestConfigQueue, intervalTime, callback)
8586
} else {
86-
requestRes = await syncBatchRequest(requestConfigQueue, intervalTime)
87+
await syncBatchRequest(requestConfigQueue, intervalTime, callback)
8788
}
88-
89-
return requestRes
9089
}
9190

92-
async fetchHTML(config: IFetchHTMLConfig): Promise<IFetchHTML> {
91+
async fetchHTML(
92+
config: IFetchHTMLConfig,
93+
callback?: (res: IFetchHTML) => void
94+
): Promise<IFetchHTML> {
9395
const { requestConifg } = this.mergeConfig({
9496
requestConifg: isString(config) ? { url: config } : config
9597
})
@@ -105,44 +107,50 @@ export default class XCrawl {
105107
}
106108
}
107109

110+
if (callback) {
111+
callback(res)
112+
}
113+
108114
return res
109115
}
110116

111-
async fetchData<T = any>(config: IFetchDataConfig): Promise<IFetchCommon<T>> {
117+
async fetchData<T = any>(
118+
config: IFetchDataConfig,
119+
callback?: (res: IFetchCommon<T>) => void
120+
): Promise<IFetchCommonArr<T>> {
112121
const { requestConifg, intervalTime } = this.mergeConfig(config)
113122

114-
const requestRes = await this.useBatchRequestByMode(
115-
requestConifg,
116-
intervalTime
117-
)
118-
119-
const container: IFetchCommon<T> = []
120-
121-
requestRes.forEach((item) => {
122-
const contentType = item.headers['content-type'] ?? ''
123-
const rawData = item.data
123+
const container: IFetchCommonArr<T> = []
124+
function handleResItem(requestResItem: IRequestResItem) {
125+
const contentType = requestResItem.headers['content-type'] ?? ''
126+
const rawData = requestResItem.data
124127

125128
const data = contentType.includes('text')
126129
? rawData.toString()
127130
: JSON.parse(rawData.toString())
128131

129-
container.push({ ...item, data })
130-
})
132+
const itemRes = { ...requestResItem, data }
133+
134+
if (callback) {
135+
callback(itemRes)
136+
}
137+
138+
container.push(itemRes)
139+
}
140+
141+
await this.useBatchRequestByMode(requestConifg, intervalTime, handleResItem)
131142

132143
return container
133144
}
134145

135-
async fetchFile(config: IFetchFileConfig): Promise<IFetchCommon<IFileInfo>> {
146+
async fetchFile(
147+
config: IFetchFileConfig,
148+
callback?: (res: IFetchCommon<IFileInfo>) => void
149+
): Promise<IFetchCommonArr<IFileInfo>> {
136150
const { requestConifg, intervalTime, fileConfig } = this.mergeConfig(config)
137151

138-
const requestRes = await this.useBatchRequestByMode(
139-
requestConifg,
140-
intervalTime
141-
)
142-
143-
const container: IFetchCommon<IFileInfo> = []
144-
145-
requestRes.forEach((requestResItem) => {
152+
const container: IFetchCommonArr<IFileInfo> = []
153+
function handleResItem(requestResItem: IRequestResItem) {
146154
const { id, headers, data } = requestResItem
147155

148156
const mimeType = headers['content-type'] ?? ''
@@ -156,16 +164,24 @@ export default class XCrawl {
156164
try {
157165
fs.writeFileSync(filePath, data)
158166

159-
container.push({
167+
const res = {
160168
...requestResItem,
161169
data: { fileName, mimeType, size: data.length, filePath }
162-
})
170+
}
171+
172+
if (callback) {
173+
callback(res)
174+
}
175+
176+
container.push(res)
163177
} catch (error: any) {
164178
log(logError(`File save error at id ${id}: ${error.message}`))
165179
}
166-
})
180+
}
181+
182+
await this.useBatchRequestByMode(requestConifg, intervalTime, handleResItem)
167183

168-
const saveTotal = requestRes.length
184+
const saveTotal = isArray(requestConifg) ? requestConifg.length : 1
169185
const success = container.length
170186
const error = saveTotal - success
171187
log(
@@ -188,12 +204,12 @@ export default class XCrawl {
188204
const total = year + month + day + hour + minute
189205

190206
let count = 0
191-
function cb() {
207+
function startCallback() {
192208
console.log(logWarn(`Start the ${logWarn.bold(++count)} polling`))
193209
callback(count)
194210
}
195211

196-
cb()
197-
setInterval(cb, total)
212+
startCallback()
213+
setInterval(startCallback, total)
198214
}
199215
}

src/request.ts

+23-27
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,8 @@ async function useSleepByBatch(
163163

164164
export async function batchRequest(
165165
requestConifgs: IRequestConfig[],
166-
intervalTime: IIntervalTime | undefined
166+
intervalTime: IIntervalTime | undefined,
167+
callback: (requestResItem: IRequestResItem) => void
167168
) {
168169
const isHaveIntervalTime = !isUndefined(intervalTime)
169170
const isNumberIntervalTime = isNumber(intervalTime)
@@ -172,9 +173,10 @@ export async function batchRequest(
172173
`Begin execution, mode: async, total: ${logNumber(requestConifgs.length)} `
173174
)
174175

175-
const requestQueue: Promise<IRequestResItem | string>[] = []
176-
177176
let index = 0
177+
let successTotal = 0
178+
let errorTotal = 0
179+
const requestQueue: Promise<undefined | string>[] = []
178180
for (const requestConifg of requestConifgs) {
179181
const id = ++index
180182

@@ -187,12 +189,14 @@ export async function batchRequest(
187189

188190
const requestItem = request(requestConifg)
189191
.catch((error: any) => {
192+
errorTotal++
190193
return `Request ${id} is an error: ${error.message}`
191194
})
192195
.then((requestRes) => {
193196
if (typeof requestRes === 'string') return requestRes
194197

195-
return { id, ...requestRes }
198+
successTotal++
199+
callback({ id, ...requestRes })
196200
})
197201

198202
requestQueue.push(requestItem)
@@ -202,32 +206,20 @@ export async function batchRequest(
202206

203207
const res = await Promise.all(requestQueue)
204208

205-
const success: IRequestResItem[] = []
206-
const error: string[] = []
207-
208-
// 通过类型分类
209-
res.forEach((item) => {
210-
if (typeof item === 'string') {
211-
return error.push(item)
212-
}
213-
214-
success.push(item)
215-
})
216-
217-
error.forEach((message) => log(logError(message)))
209+
// 打印错误消息
210+
res.forEach((item) => (item ? log(logError(item)) : ''))
218211

219212
log(
220213
`requestsTotal: ${logNumber(requestConifgs.length)}, success: ${logSuccess(
221-
success.length
222-
)}, error: ${logError(error.length)}`
214+
successTotal
215+
)}, error: ${logError(errorTotal)}`
223216
)
224-
225-
return success
226217
}
227218

228219
export async function syncBatchRequest(
229220
requestConifgs: IRequestConfig[],
230-
intervalTime: IIntervalTime | undefined
221+
intervalTime: IIntervalTime | undefined,
222+
callback: (requestResItem: IRequestResItem) => void
231223
) {
232224
const isHaveIntervalTime = !isUndefined(intervalTime)
233225
const isNumberIntervalTime = isNumber(intervalTime)
@@ -239,7 +231,6 @@ export async function syncBatchRequest(
239231
let id = 0
240232
let successTotal = 0
241233
let errorTotal = 0
242-
const requestRes: IRequestResItem[] = []
243234
for (const requestConifg of requestConifgs) {
244235
id++
245236

@@ -250,15 +241,22 @@ export async function syncBatchRequest(
250241
id
251242
)
252243

244+
let isRequestSuccess = true
245+
let requestResItem: IRequestResItem | null = null
253246
try {
254-
const requestResItem = await request(requestConifg)
255-
requestRes.push({ id, ...requestResItem })
247+
const requestRes = await request(requestConifg)
248+
requestResItem = { id, ...requestRes }
256249
log(logSuccess(`Request ${logNumber(id)} is an success`))
257250
successTotal++
258251
} catch (error: any) {
252+
isRequestSuccess = false
259253
log(logError(`Request ${id} is an error: ${error.message}`))
260254
errorTotal++
261255
}
256+
257+
if (isRequestSuccess && callback) {
258+
callback(requestResItem as IRequestResItem)
259+
}
262260
}
263261

264262
log(logSuccess('All requests are over!'))
@@ -268,6 +266,4 @@ export async function syncBatchRequest(
268266
successTotal
269267
)}, error: ${logError(errorTotal)}`
270268
)
271-
272-
return requestRes
273269
}

src/types.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,14 @@ export interface IFetchPollingConfig {
8989
m?: number
9090
}
9191

92-
export type IFetchCommon<T> = {
92+
export interface IFetchCommon<T> {
9393
id: number
9494
statusCode: number | undefined
9595
headers: IncomingHttpHeaders
9696
data: T
97-
}[]
97+
}
98+
99+
export type IFetchCommonArr<T> = IFetchCommon<T>[]
98100

99101
export interface IFileInfo {
100102
fileName: string

0 commit comments

Comments
 (0)