koajs / koa

Expressive middleware for node.js using ES2017 async functions

Home Page:https://koajs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

koa 2.14.7 No generics,I want to be able to add generics

jonlyes opened this issue · comments

In koa 2.14.2, because there are no generics, the Context type needs to be overridden and inherited when using Koa-multer. Hopefully, the koa team will add generics in the next update

Code instance
router:

import Router from "koa-router";
import article from "../../controller/article";
import authMiddleware from "../../middleware/authMiddleware";
import fileMiddleware from "../../middleware/fileMiddleware";

const articleRouter = new Router({
  prefix: "/article",
});

// 添加博客文章
articleRouter.post(
  "/",
  authMiddleware.verifyAuth,
  fileMiddleware.coverHandle,
  article.createArticle
);

export default articleRouter;

filemiddleware

import { Context, Next } from "koa";
import multer from "koa-multer";
import config from "../app/config";

// // 上传文件中间件

class FileMiddleware {
  async coverHandle(ctx:Context) {
    const coverUpload = multer({
      dest: config.COVER_PATH,
    });

    return coverUpload.single("cover");
  }
}

export default new FileMiddleware()

controller

import { Context } from "koa";
import { ArticleList, ArticleId, Article } from "../types/article";
import articleService from "../service/articleService";

import { IncomingMessage } from 'http'

interface ContextWithFile extends Context {
  req: IncomingMessage & { file?: unknown }
}

class articleController {
  // 添加博客文章
  async createArticle(ctx: ContextWithFile) {
    const { title, content, isShare } = ctx.request.body as Article;

    console.log(ctx.req.file);
  }
}

export default new articleController();

Koa core does not provide typescript support and such this ticket will not be fixed here. Please refer to https://www.npmjs.com/package/@types/koa