Reputation: 1938
I am newb in Typescript and trying to integrate koa-router
and koa-passport
. Installed all @types\
import Koa from "koa";
import Route from "koa-router";
import passport from "koa-passport";
import session from "koa-session";
const app = new Koa();
const router = new Route();
app.keys = [process.env.SECRET_KEY || "secret"];
app.use(session({}, app));
app.use(passport.initialize());
app.use(passport.session());
app.use(router.routes()).use(router.allowedMethods());
And when I try to use passport
methods with router
.
router.post("Logout", "/logout", ctx => {
if (ctx.isAuthenticated()) {
ctx.logout();
}
});
have error on context(ctx) methods
Property 'isAuthenticated' does not exist on type 'ParameterizedContext<any, IRouterParamContext<any, {}>>'.
Property 'logout' does not exist on type 'ParameterizedContext<any, IRouterParamContext<any, {}>>'.
I tried different approaches, but unsuccessful. Appreciate any help.
Upvotes: 4
Views: 1464
Reputation: 1
One way I found was to use
const router = new Route<{}, koa.Context>();
The koa-router types adds the passport methods to koa.Context
in https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa-passport/index.d.ts#L23. The 2nd type parameter for Router
lets us add extra properties to the middleware context. By passing in koa.Context
, we get access to the functions added by koa-router.
Upvotes: 0
Reputation: 1938
I found one way is to define all routes with separate function and type definition of passport as typeof KoaPassport
. And for route as Koa.Middleware
had that issue too
// src/index.ts
import routes from "./routes";
...
routes(router, model, passport);
// src/routes/index.ts
function routes(router: Route, model: Model, passport: typeof KoaPassport) {
router
.post("Login", "/login", (async (ctx, next) => {
await passport.authenticate("local", async (err, user) => {
....
})(ctx, next);
}) as Koa.Middleware)
}
Upvotes: 0