Проблемы с набором контроллеров в приложении node / express - PullRequest
0 голосов
/ 02 августа 2020

Я кодирую свой первый API Node / Express и решаю использовать Typescript (я уже немного использую TS в проекте React в своей работе).

У меня есть следующий контроллер:

import { Request, Response } from "express";

const syncWallet = async (req: Request, res: Response) => {
  // awaits everywhere
  res.status(204)
};

Для контроллеров / маршрутов я создал следующие интерфейсы в /src/index.d.ts:


interface Controller {
  (
    req: Express.Request,
    res: Express.Response,
    next?: Express.NextFunction
  ): Promise<void> | void;
}

interface Route{
  path: string;
  method: string;
  controller: Controller;
}

Итак, в routes.ts файле я экспортирую массив типа Array<Route>, потому что im используя эту функцию

import { Router } from "express";

export const applyRoutes = (routes: Array<Route>, router: Router) => {
  for (const route of routes) {
    const { method, path, controller } = route;
    (router as any)[method](path, controller);
  }
};

С помощью этого типа Route я могу организовать свой проект аналогично Django (url + views).

Итак, в моем main.ts файл имеет:

import http from "http";
import express from "express";
import errorHandlers from "./middlewares/errorHandler";
import routes from "./routes";
import {applyRoutes} from "./routes/handlers"
import * as bodyParser from 'body-parser'


const router = express();
router.use(bodyParser.json())
applyRoutes(routes, router);

const { PORT = 3000 } = process.env;
const server = http.createServer(router);

server.listen(PORT, () =>
  console.log(`Server is running http://localhost:${PORT}...`)
);

Но я получаю следующую ошибку:

src/main.ts(22,13): error TS2345: Argument of type '{ path: string; method: string; controller: (req: Request<ParamsDictionary, any, any, ParsedQs>, res: Response<any>) => Promise<void>; }[]' is not assignable to parameter of type 'Route[]'.
  Type '{ path: string; method: string; controller: (req: Request, res: Response) => Promise<void>; }' is not assignable to type 'Route'.
    Types of property 'controller' are incompatible.
      Type '(req: Request, res: Response) => Promise<void>' is not assignable to type 'Controller'.
        Types of parameters 'req' and 'req' are incompatible.
          Type 'Request' is missing the following properties from type 'Request<ParamsDictionary, any, any, ParsedQs>': get, header, accepts, acceptsCharsets, and 77 more.

Есть намек на то, что мне не хватает?

1 Ответ

0 голосов
/ 12 августа 2020

Проблема заключалась в неправильном использовании async / await и путанице с типом http.Request и типом Express.Request.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...