-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathexpress.ts
40 lines (35 loc) · 1.4 KB
/
express.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import type { Request, Response } from "express";
import { OAuthException } from "../exceptions/oauth.exception.js";
import { OAuthRequest } from "../requests/request.js";
import { OAuthResponse } from "../responses/response.js";
import { isOAuthError } from "../utils/errors.js";
export function responseFromExpress({ status, ...res }: Response): OAuthResponse {
return new OAuthResponse({ status: res.statusCode ?? 200, ...res });
}
export function requestFromExpress(req: Request): OAuthRequest {
return new OAuthRequest(req);
}
export function handleExpressResponse(expressResponse: Response, oauthResponse: OAuthResponse): void {
if (oauthResponse.status === 302) {
if (!oauthResponse.headers.location) throw new Error("missing redirect location");
expressResponse.set(oauthResponse.headers);
expressResponse.redirect(oauthResponse.headers.location);
} else {
expressResponse.set(oauthResponse.headers);
expressResponse.status(oauthResponse.status).send(oauthResponse.body);
}
}
// @todo v4.0 flip these to always be Express as first arg, OAuth as second. Then update Docs
export function handleExpressError(e: unknown | OAuthException, res: Response): void {
if (isOAuthError(e)) {
res.status(e.status);
res.send({
status: e.status,
message: e.message,
error: e.errorType,
error_description: e.errorDescription ?? e.error,
});
return;
}
throw e;
}