simple-node-framework
simple-node-framework copied to clipboard
Database in middleware
I need to access my database in a global middleware.
How can I do it?
I try this way:
server.ts
class Server extends Restify {
constructor() {
super();
}
public configure(): ServerRestify {
this.server = this.restify.createServer({
log: Log
});
this.applyMiddlewares();
return this.server;
}
public applyMiddlewares(): void {
MIDDLEWAREHELPER.init(this.server);
}
}
const localServer = new Server();
const restify = localServer.restify;
const server = localServer.configure();
export {
restify,
server
};
MIDDLEWAREHELPER.ts
class MiddlewareHelperClasse extends Base {
constructor() {
super('MiddlewareHelper');
}
public init(server: ServerRestify) {
server.use(this.applyMiddleware(
VERSION.checkVersion
));
}
public applyMiddleware(middleware: any) {
return (req: CustomRequest, res: Response, next: Next) => req.itsNotToIgnore ? middleware(req, res, next) : next();
}
}
export const MIDDLEWAREHELPER = new MiddlewareHelperClasse();
version.ts
class Version {
public versionService: VersionService;
constructor() {
this.versionService = new VersionService();
this.checkVersion = this.checkVersion.bind(this);
}
// Validação permissão
public async checkVersion(
req: CustomRequest,
// eslint-disable-next-line @typescript-eslint/tslint/config
_res: Response,
next: Next
): Promise<void> {
try {
const appVersion = req.header('User-Agent-App-Version', '');
const activeAppVersion = await this.versionService.getMostRecentActiveVersion();
if (activeAppVersion && appVersion === activeAppVersion.version) {
return next();
}
throw CustomError.UPGRADE_REQUIRED();
} catch (err) {
next(applicationError.throw(err));
}
}
}
export const VERSION = new Version();
But I got this error:::
MongooseError: Operation `versions.findOne()` buffering timed out after 10000ms
If I remove that middleware everything works.