Skip to content

Commit

Permalink
chore: clean up old code (#4645)
Browse files Browse the repository at this point in the history
* clean up duplicated methods

* format

* Update initializeServer.ts
  • Loading branch information
juanpicado committed May 13, 2024
1 parent 7b14147 commit 6edd6d2
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 80 deletions.
15 changes: 7 additions & 8 deletions src/api/endpoint/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import express from 'express';

import { Auth } from '@verdaccio/auth';
import {
antiLoop,
encodeScopePackage,
match,
validateName,
validatePackage,
} from '@verdaccio/middleware';
import { Config } from '@verdaccio/types';

import Storage from '../../lib/storage';
Expand All @@ -16,14 +23,6 @@ import v1Search from './api/v1/search';
import token from './api/v1/token';
import whoami from './api/whoami';

const {
match,
validateName,
validatePackage,
encodeScopePackage,
antiLoop,
} = require('@verdaccio/middleware');

export default function (config: Config, auth: Auth, storage: Storage) {
/* eslint new-cap:off */
const app = express.Router();
Expand Down
8 changes: 4 additions & 4 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { Auth } from '@verdaccio/auth';
import { getUserAgent } from '@verdaccio/config';
import { pluginUtils } from '@verdaccio/core';
import { asyncLoadPlugin } from '@verdaccio/loaders';
import { final } from '@verdaccio/middleware';
import { log } from '@verdaccio/middleware';
import { errorReportingMiddleware, final, handleError } from '@verdaccio/middleware';
import { Config as IConfig } from '@verdaccio/types';

import AppConfig from '../lib/config';
Expand All @@ -19,7 +19,7 @@ import { ErrorCode } from '../lib/utils';
import { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types';
import hookDebug from './debug';
import apiEndpoint from './endpoint';
import { errorReportingMiddleware, handleError, serveFavicon } from './middleware';
import { serveFavicon } from './middleware';
import webMiddleware from './web';

const { version } = require('../../package.json');
Expand All @@ -43,7 +43,7 @@ const defineAPI = async function (config: IConfig, storage: Storage): Promise<ex

// // Router setup
app.use(log(logger));
app.use(errorReportingMiddleware);
app.use(errorReportingMiddleware(logger));
if (config.user_agent) {
app.use(function (_req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer): void {
res.setHeader('X-Powered-By', getUserAgent(config.user_agent));
Expand Down Expand Up @@ -103,7 +103,7 @@ const defineAPI = async function (config: IConfig, storage: Storage): Promise<ex
app.get('/*', function (_, __, next: $NextFunctionVer) {
next(ErrorCode.getNotFound(API_ERROR.FILE_NOT_FOUND));
});
app.use(handleError);
app.use(handleError(logger));
app.use(final);

return app;
Expand Down
68 changes: 4 additions & 64 deletions src/api/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import buildDebug from 'debug';
import fs from 'fs';
import { HttpError } from 'http-errors';
import _ from 'lodash';
import path from 'path';
import validator from 'validator';

import { Config, Package } from '@verdaccio/types';
import { Config, Manifest } from '@verdaccio/types';

import { API_ERROR, HTTP_STATUS } from '../lib/constants';
import { logger } from '../lib/logger';
import { HTTP_STATUS } from '../lib/constants';
import { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types';

const debug = buildDebug('verdaccio');
const debug = buildDebug('verdaccio:middleware:favicon');

export function serveFavicon(config: Config) {
return function (req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer) {
Expand Down Expand Up @@ -58,66 +56,8 @@ export function serveFavicon(config: Config) {
};
}

export function handleError(
err: HttpError,
req: $RequestExtend,
res: $ResponseExtend,
next: $NextFunctionVer
) {
debug('error handler init');
if (_.isError(err)) {
debug('is native error', err);
if (err.code === 'ECONNABORT' && res.statusCode === HTTP_STATUS.NOT_MODIFIED) {
return next();
}
if (_.isFunction(res.locals.report_error) === false) {
debug('is locals error report ref');
// in case of very early error this middleware may not be loaded before error is generated
// fixing that
errorReportingMiddleware(req, res, _.noop);
}
debug('set locals error report ref');
res.locals.report_error(err);
} else {
// Fall to Middleware.final
debug('no error to report, jump next layer');
return next(err);
}
}

export interface MiddlewareError {
error: string;
}

export type FinalBody = Package | MiddlewareError | string;

// Middleware
export function errorReportingMiddleware(
req: $RequestExtend,
res: $ResponseExtend,
next: $NextFunctionVer
): void {
res.locals.report_error =
res.locals.report_error ||
function (err: any): void {
if (err.status && err.status >= HTTP_STATUS.BAD_REQUEST && err.status < 600) {
if (!res.headersSent) {
res.status(err.status);
next({ error: err.message || API_ERROR.UNKNOWN_ERROR });
}
} else {
logger.error({ err: err }, 'unexpected error: @{!err.message}\n@{err.stack}');
if (!res.status || !res.send) {
logger.error('this is an error in express.js, please report this');
res.destroy();
} else if (!res.headersSent) {
res.status(HTTP_STATUS.INTERNAL_ERROR);
next({ error: API_ERROR.INTERNAL_SERVER_ERROR });
} else {
// socket should be already closed
}
}
};

next();
}
export type FinalBody = Manifest | MiddlewareError | string;
8 changes: 4 additions & 4 deletions test/helpers/initializeServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import path from 'path';

import { Auth } from '@verdaccio/auth';
import { errorUtils } from '@verdaccio/core';
import { final } from '@verdaccio/middleware';
import { errorReportingMiddleware, final, handleError } from '@verdaccio/middleware';
import { ConfigYaml } from '@verdaccio/types';
import { generateRandomHexString } from '@verdaccio/utils';

import { errorReportingMiddleware, handleError } from '../../src/api/middleware';
import Config from '../../src/lib/config';
import { logger } from '../../src/lib/logger';

const debug = buildDebug('verdaccio:tools:helpers:server');

Expand All @@ -35,7 +35,7 @@ export async function initializeServer(
// TODO: this might not be need it, used in apiEndpoints
app.use(express.json({ strict: false, limit: '10mb' }));
// @ts-ignore
app.use(errorReportingMiddleware);
app.use(errorReportingMiddleware(logger));
for (let route of routesMiddleware) {
if (route.async) {
const middleware = await route.routes(config, auth, storage);
Expand All @@ -51,7 +51,7 @@ export async function initializeServer(
});

// @ts-ignore
app.use(handleError);
app.use(handleError(logger));
// @ts-ignore
app.use(final);

Expand Down

0 comments on commit 6edd6d2

Please sign in to comment.