icynet-auth-server/src/middleware/flash.middleware.ts

48 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-03-09 18:37:04 +00:00
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { SessionData } from 'express-session';
import { format } from 'util';
@Injectable()
export class FlashMiddleware implements NestMiddleware {
private _flash(
session: SessionData,
type: string,
...msg: any[]
): Record<string, any> {
const msgs = (session.flash = session.flash || {});
if (type && msg?.length) {
let result: string;
if (Array.isArray(msg[0])) {
msg[0].forEach((val) => {
(msgs[type] = msgs[type] || []).push(val);
});
return msgs;
} else {
result = msg.length > 1 ? format(...msg) : msg[0];
}
return (msgs[type] = msgs[type] || []).push(result);
} else if (type) {
const arr = msgs[type];
delete msgs[type];
return arr || [];
} else {
session.flash = {};
return msgs;
}
}
use(req: Request, res: Response, next: NextFunction) {
if (req.flash) {
return next();
}
req.flash = this._flash.bind(this, req.session);
next();
}
}