Skip to content

Commit b869b01

Browse files
committed
feature(serializer) Adding request and refactor
Passport has an undocumented feature, where the request can be passed to the serializeUser/deserializeUser callback as the first argument, and whether it is or not is determined by the arguments in the function (if it accepts 3, the first is the request). This feature is used to get and pass the request to the callback. The done callback is removed in favor of a promise being expected. A rejected promise (or an exception thrown within the handler) will be passed to passport as an error. Also added types for everything as generics, defaulting to the type safe "unknown" instead of "any", allowing extenders to enforce type safety on this lower level, instead of just theirs.
1 parent cc1ae91 commit b869b01

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed
Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,46 @@
1+
import { IncomingMessage } from 'http';
12
import * as passport from 'passport';
23

3-
export abstract class PassportSerializer {
4-
abstract serializeUser(user: any, done: Function);
5-
abstract deserializeUser(payload: any, done: Function);
4+
export abstract class PassportSerializer<
5+
UserType extends unknown = unknown,
6+
PayloadType extends unknown = unknown,
7+
RequestType extends IncomingMessage = IncomingMessage
8+
> {
9+
abstract serializeUser(
10+
user: UserType,
11+
req?: RequestType
12+
): Promise<PayloadType>;
13+
abstract deserializeUser(
14+
payload: PayloadType,
15+
req?: RequestType
16+
): Promise<UserType>;
617

718
constructor() {
8-
passport.serializeUser((user, done) => this.serializeUser(user, done));
9-
passport.deserializeUser((payload, done) =>
10-
this.deserializeUser(payload, done)
19+
passport.serializeUser(
20+
async (
21+
req: RequestType,
22+
user: UserType,
23+
done: (err: unknown, payload?: PayloadType) => unknown
24+
) => {
25+
try {
26+
done(null, await this.serializeUser(user, req));
27+
} catch (err) {
28+
done(err);
29+
}
30+
}
31+
);
32+
passport.deserializeUser(
33+
async (
34+
req: RequestType,
35+
payload: PayloadType,
36+
done: (err: unknown, user?: UserType) => unknown
37+
) => {
38+
try {
39+
done(null, await this.deserializeUser(payload, req));
40+
} catch (err) {
41+
done(err);
42+
}
43+
}
1144
);
1245
}
1346
}

0 commit comments

Comments
 (0)