42 lines
1.7 KiB
TypeScript
42 lines
1.7 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<void> {
|
||
|
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) => {
|
||
|
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) => {
|
||
|
if (req.session) {
|
||
|
const contentType = (res.getHeaders())['content-type'];
|
||
|
if (!err && res.statusCode === 200 && (contentType && typeof contentType !== 'number' && contentType.indexOf('text/html') >= 0)) {
|
||
|
req.session!.previousUrl = req.originalUrl;
|
||
|
Logger.debug('Prev url set to', req.session!.previousUrl);
|
||
|
req.session!.save((err) => {
|
||
|
if (err) {
|
||
|
Logger.error(err, 'Error while saving session');
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
|
||
|
next();
|
||
|
});
|
||
|
}
|
||
|
}
|