koajs / koa

Expressive middleware for node.js using ES2017 async functions
https://koajs.com
MIT License
35.11k stars 3.22k forks source link

[fix] Has callback() changed return type? Now error from eslint #1755

Closed crystalfp closed 1 week ago

crystalfp commented 1 year ago

Describe the bug

The following ts code has always worked:

import http2 from "node:http2";
import fs from "node:fs";

import Koa from "koa";

const options = {
    key:  fs.readFileSync("./cert/localhost-privkey.pem"),
    cert: fs.readFileSync("./cert/localhost-cert.pem")
};
const port = 3322;

const runApp = () => {
    console.log("Running")
}
const handleServerErrors = (error) => {
    console.log("Error", error)
}

const app = new Koa();
const server = http2
            .createSecureServer(options, app.callback()) // <-- Here
            .listen(port, () => runApp())
            .once("error", handleServerErrors);

Node.js version: 19.8.1

OS version: Windows 11 64 bits

Koa version: 2.14.1

@types/koa version: 2.13.6

Description: Wrong type for the app.callback() function.

Actual behavior

eslint complains: Promise returned in function argument where a void return was expected (@typescript-eslint/no-misused-promises) at the marked line. Is it my fault (but always compiled clearly) or the typing is wrong? That is, has the function changed and I should change the code or is it an error in @types/koa?

Expected behavior

No complains from eslint.

Code to reproduce

See above

Checklist

crystalfp commented 1 year ago

In the meantime added issue to DefinitelyTyped @types/koa module https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/64923

zacanger commented 1 year ago

This change (the one referenced in your issue on the @types repo) was incorrect. Returning a function that returns a promise isn't the same as returning a Promise. It looks like the original change mentions that issue, but the current version of the types on npm is still incorrect.

younes-io commented 1 year ago

@crystalfp did you try something like this

import http2 from "node:http2";
import fs from "node:fs";

import Koa from "koa";

const options = {
  key: fs.readFileSync("./cert/localhost-privkey.pem"),
  cert: fs.readFileSync("./cert/localhost-cert.pem"),
};
const port = 3322;

const runApp = () => {
  console.log("Running");
};
const handleServerErrors = (error) => {
  console.log("Error", error);
};

const app = new Koa();
const startServer = async () => {
  const server = http2.createSecureServer(options, app.callback());
  server.listen(port, () => runApp()).once("error", handleServerErrors);
};

startServer();
crystalfp commented 1 year ago

This is exactly my code (also in my first question BTW). The problem is the typing of app.callback() not the code.

3imed-jaberi commented 1 year ago

@crystalfp This should be fixed on the @types/koa side.

I am not sure but maybe wrapping the callback method on another anonymous function like () => { app.callback() } be work.