application-not-installed.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import type { NextFunction, Request, Response } from 'express';
  2. import createError, { isHttpError } from 'http-errors';
  3. import type Crowi from '../crowi';
  4. /**
  5. * Middleware factory to check if the application is already installed
  6. */
  7. export const generateCheckerMiddleware = (crowi: Crowi) => async(req: Request, res: Response, next: NextFunction): Promise<void> => {
  8. const { appService } = crowi;
  9. const isDBInitialized = await appService.isDBInitialized(true);
  10. if (isDBInitialized) {
  11. return next(createError(409, 'Application is already installed'));
  12. }
  13. return next();
  14. };
  15. /**
  16. * Middleware to return HttpError 409 if the application is already installed
  17. */
  18. export const allreadyInstalledMiddleware = async(req: Request, res: Response, next: NextFunction): Promise<void> => {
  19. return next(createError(409, 'Application is already installed'));
  20. };
  21. /**
  22. * Error handler to handle errors as API errors
  23. */
  24. export const handleAsApiError = (error: Error, req: Request, res: Response, next: NextFunction): void => {
  25. if (error == null) {
  26. return next();
  27. }
  28. if (isHttpError(error)) {
  29. const httpError = error as createError.HttpError;
  30. res.status(httpError.status).json({ message: httpError.message });
  31. return;
  32. }
  33. next();
  34. };
  35. /**
  36. * Error handler to redirect to top page on error
  37. */
  38. export const redirectToTopOnError = (error: Error, req: Request, res: Response, next: NextFunction): void => {
  39. if (error != null) {
  40. return res.redirect('/');
  41. }
  42. return next();
  43. };