我正在尝试在一个使用Angular DI(ngx)的node.js应用程序中注入Superagent。
import * as request from 'superagent';
...
{
provide: request,
useFactory: () =>
request.agent()
.timeout({deadline: 10000, timeout: 60000}),
},
但我得到property
超时does not exist on SuperAgent<SuperAgentRequest>
。我尝试了these docs,但SuperAgent似乎不是正确的类型。 request.agent()
的类型应为request.Request
。
我错过了什么?如何正确提供request.Request
以便我可以全局配置它以使用相同(注入)的实例?
答案 0 :(得分:2)
在Superagent typings中可以看到,request.agent()
返回SuperAgent<SuperAgentRequest>
that doesn't have timeout
method,这就是错误信息所说的。
虽然Request
类型中存在timeout
方法,但它是响应的承诺。这就是抛出此错误的原因。没有请求也没有回应。 Superagent documentation为timeout
提供了一个示例:
request
.get('/big-file?network=slow')
.timeout({
response: 5000, // Wait 5 seconds for the server to start sending,
deadline: 60000, // but allow 1 minute for the file to finish loading.
})
文档说明代理程序实例有methods that set defaults,因此缺少输入。没有deadline
方法,对timeout
没有意义,因为这是截止日期超时。
superagent
类型应该在本地扩充,或者改进并PRed到DefinitelyTyped存储库,或者就地修复:
{
provide: request,
useFactory: () =>
<SuperAgent<SuperAgentRequest>>request.agent()
['timeout'](30)
}
我希望增强的输入类似于(使用正则表达式处理原始Request
接口):
custom.d.ts
import * as request from 'superagent';
type CallbackHandler = (err: any, res: request.Response) => void;
type Serializer = (obj: any) => string;
type BrowserParser = (str: string) => any;
type NodeParser = (res: request.Response, callback: (err: Error | null, body: any) => void) => void;
type Parser = BrowserParser | NodeParser;
declare module "superagent" {
interface ConfigurableSuperAgent<Req extends request.SuperAgentRequest> extends request.SuperAgent<Req> {
accept(type: string): this;
auth(user: string, name: string): this;
buffer(val?: boolean): this;
ca(cert: Buffer): this;
cert(cert: Buffer | string): this;
key(cert: Buffer | string): this;
ok(callback: (res: Response) => boolean): this;
on(name: 'error', handler: (err: any) => void): this;
on(name: 'progress', handler: (event: ProgressEvent) => void): this;
on(name: string, handler: (event: any) => void): this;
parse(parser: Parser): this;
pfx(cert: Buffer | string): this;
query(val: object | string): this;
redirects(n: number): this;
retry(count?: number, callback?: CallbackHandler): this;
serialize(serializer: Serializer): this;
set(field: object): this;
set(field: string, val: string): this;
timeout(ms: number | { deadline?: number, response?: number }): this;
type(val: string): this;
use(fn: Plugin): this;
}
interface SuperAgentStatic extends request.SuperAgent<request.SuperAgentRequest> {
agent(): ConfigurableSuperAgent<request.SuperAgentRequest>;
}
}