46 lines
1.8 KiB
TypeScript
46 lines
1.8 KiB
TypeScript
import ApplicationComponent from "../ApplicationComponent";
|
|
import {Request, Router} from "express";
|
|
import {ServerError} from "../HttpError";
|
|
import onFinished from "on-finished";
|
|
import Logger from "../Logger";
|
|
|
|
export default class RedirectBackComponent extends ApplicationComponent {
|
|
public static getPreviousURL(req: Request, defaultUrl?: string): string | undefined {
|
|
return req.session?.previousUrl || defaultUrl;
|
|
}
|
|
|
|
public async handle(router: Router): Promise<void> {
|
|
router.use((req, res, next) => {
|
|
res.redirectBack = (defaultUrl?: string): void => {
|
|
const previousUrl = RedirectBackComponent.getPreviousURL(req, defaultUrl);
|
|
if (!previousUrl) throw new ServerError(`Couldn't redirect you back.`);
|
|
res.redirect(previousUrl);
|
|
};
|
|
|
|
res.locals.getPreviousURL = (defaultUrl?: string) => {
|
|
return RedirectBackComponent.getPreviousURL(req, defaultUrl);
|
|
};
|
|
|
|
onFinished(res, (err) => {
|
|
const session = req.session;
|
|
if (session) {
|
|
const contentType = res.getHeader('content-type');
|
|
if (!err && res.statusCode === 200 && (
|
|
contentType && typeof contentType !== 'number' && contentType.indexOf('text/html') >= 0
|
|
)) {
|
|
session.previousUrl = req.originalUrl;
|
|
Logger.debug('Prev url set to', session.previousUrl);
|
|
session.save((err) => {
|
|
if (err) {
|
|
Logger.error(err, 'Error while saving session');
|
|
}
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
next();
|
|
});
|
|
}
|
|
}
|