从 didReceiveResponse 回调返回 null 是不是有效?

Posted

技术标签:

【中文标题】从 didReceiveResponse 回调返回 null 是不是有效?【英文标题】:Is it valid to return null from a didReceiveResponse callback?从 didReceiveResponse 回调返回 null 是否有效? 【发布时间】:2020-04-25 03:16:54 【问题描述】:

我在扩展 RESTDataSource 的类上有一个 didReceiveResponse 回调,如果响应状态为 404,我将在其中返回 null。由于输入了 RESTDataSource.didReceiveResponse,这似乎是无效的。

  async didReceiveResponse<T>(res: Response, req: Request): Promise<T | null> 
      if (res.status === 404) 
        return null;
      

      return super.didReceiveResponse(res, req);
  

这是我在使用 --strict-null-checks 时遇到的 Typescript 错误

TS2416: Property 'didReceiveResponse' in type 'APIDataSource' is not assignable to the same property in base type 'RESTDataSource<ResolverContext>'.
  Type '<T>(res: Response, req: Request) => Promise<T | null>' is not assignable to type '<TResult = any>(response: Response, _request: Request) => Promise<TResult>'.
    Type 'Promise<TResult | null>' is not assignable to type 'Promise<TResult>'.
      Type 'TResult | null' is not assignable to type 'TResult'.
        Type 'null' is not assignable to type 'TResult'.

有没有办法在不禁用编译器或严格的空检查的情况下在返回 null 的同时解决这种输入问题?

【问题讨论】:

【参考方案1】:

看看RESTDataSource.ts#L100这个apollo-datasource-rest包的源代码。

didReceiveResponse方法的源码为:

protected async didReceiveResponse<TResult = any>(
    response: Response,
    _request: Request,
): Promise<TResult> 
    if (response.ok) 
      return (this.parseBody(response) as any) as Promise<TResult>;
     else 
      throw await this.errorFromResponse(response);
    

他们使用这样的类型断言:

return (this.parseBody(response) as any) as Promise<TResult>;

所以,如果您确定 null 值正是您想要的,您也可以这样做

例如

SomeDataSource.ts:

import  RESTDataSource  from 'apollo-datasource-rest';
import  Response, Request  from 'apollo-server-env';

class SomeDataSource extends RESTDataSource 
  protected async didReceiveResponse<TResult>(res: Response, req: Request): Promise<TResult> 
    if (res.status === 404) 
      return (null as any) as Promise<TResult>;
    

    return super.didReceiveResponse<TResult>(res, req);
  

tsconfig.json:

"strictNullChecks": true /* Enable strict null checks. */,

【讨论】:

以上是关于从 didReceiveResponse 回调返回 null 是不是有效?的主要内容,如果未能解决你的问题,请参考以下文章

在应用程序购买 didReceiveResponse 不显示我的产品

FBRequestDelegate didReceiveResponse 如何找出这个响应是啥请求

如何从回调中返回值?

从回调返回值或在 node.js 中的特定回调之外访问它?

从回调中返回字符串 - Java

Node.js:如何从回调中正确返回对象?