在TypeScript的一个接口中返回超级代理承诺响应

时间:2019-01-11 21:57:44

标签: typescript promise es6-promise

我正在使用超级代理发出返回JSON的REST请求。我希望将这些请求封装在一个类中,该类返回带有get或post结果(包括HTTP状态和错误)的接口。因此,与其为解决和拒绝而不使用单独的处理程序。我只希望有一种方法可以通过一个接口返回承诺。

例如,使用https://jsonplaceholder.typicode.com/进行待办事项,我想返回:

  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
 File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/user/Python/KeepSoftPythonAPI/controller/ProjetoController.py", line 93, in add_projeto
return mProjeto.projeto_schema.jsonify(new_projeto)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask_marshmallow/schema.py", line 42, in jsonify
return flask.jsonify(data, *args, **kwargs)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 201, in encode
chunks = list(chunks)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
yield from chunks
  File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 438, in _iterencode
o = _default(o)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
  File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
  TypeError: Object of type Usuario is not JSON serializable

而呼叫者只是这样做:

export interface ITodo {
    userId: number;
    id: number;
    title: string;
    completed: boolean;
    status: number;
    ok: boolean;
    error: string;
}

我有下面的类,它在运行时运行良好,但是无论如何,我的语法都会出现TSLINT错误,特别是res:superagent.Response行:

    const todo: ITodo = await TodoRequest.getTodo(100);
    if (todo.ok) {
        console.log(todo.title);
    } else {
        console.log("Error status " + todo.status + " reason: " + todo.error);
    }

是否有更好的方法对此进行编码?

src/actions/TodoRequest.ts:26:15 - error TS2322: Type 'ITodo | Response' is not assignable to type 'Response'.

1 个答案:

答案 0 :(得分:0)

您可以在函数定义中使用联合和类型保护。它们在这里定义:

https://www.typescriptlang.org/docs/handbook/advanced-types.html

这将在https://www.typescriptlang.org/play/上运行:

interface ITodo {
    Thing: string
}

interface IError {
    Status: number,
    Message: string
}

function getIt(returnTodo: boolean): Promise<ITodo | IError> {
    if (returnTodo) {
        return Promise.resolve({
            Thing: "Hi todo"
        });
    }

    return Promise.resolve({
        Status: 55,
        Message: "You said false..."
    });
}

function isError(res: IError | ITodo): res is IError {
    return (<IError>res).Status !== undefined;
}

getIt(false)
    .then((value) => {
        if (isError(value)) {
            const elem = document.createElement("p");
            elem.innerText = `Error: ${value.Message}`;
            document.body.append(elem);
        }
    });

getIt(true)
    .then((value) => {
        if (isError(value)) {
            // Won't get this...
        } else {
            const elem = document.createElement("p");
            elem.innerText = `TODO: ${value.Thing}`;
            document.body.append(elem);
        }
    });