0
Fork 0
mirror of https://github.com/verdaccio/verdaccio.git synced 2025-01-06 22:40:26 -05:00
verdaccio/packages/api/src/package.ts

100 lines
2.9 KiB
TypeScript
Raw Normal View History

import buildDebug from 'debug';
import { Router } from 'express';
2020-03-03 17:59:19 -05:00
import { Auth } from '@verdaccio/auth';
import { HEADERS, HEADER_TYPE, stringUtils } from '@verdaccio/core';
import { logger } from '@verdaccio/logger';
import { allow } from '@verdaccio/middleware';
import { Storage } from '@verdaccio/store';
import { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types/custom';
2020-03-03 17:59:19 -05:00
const debug = buildDebug('verdaccio:api:package');
export default function (route: Router, auth: Auth, storage: Storage): void {
const can = allow(auth, {
beforeAll: (a, b) => logger.trace(a, b),
afterAll: (a, b) => logger.trace(a, b),
});
route.get(
'/:package/:version?',
can('access'),
async function (
req: $RequestExtend,
_res: $ResponseExtend,
next: $NextFunctionVer
): Promise<void> {
debug('init package by version');
const name = req.params.package;
let version = req.params.version;
const write = req.query.write === 'true';
const abbreviated =
stringUtils.getByQualityPriorityValue(req.get('Accept')) === Storage.ABBREVIATED_HEADER;
const requestOptions = {
protocol: req.protocol,
headers: req.headers as any,
// FIXME: if we migrate to req.hostname, the port is not longer included.
host: req.host,
remoteAddress: req.socket.remoteAddress,
byPassCache: write,
};
2020-03-03 17:59:19 -05:00
try {
const manifest = await storage.getPackageByOptions({
name,
uplinksLook: true,
abbreviated,
version,
requestOptions,
});
if (abbreviated) {
_res.setHeader(HEADER_TYPE.CONTENT_TYPE, HEADERS.JSON_INSTALL_CHARSET);
} else {
_res.setHeader(HEADER_TYPE.CONTENT_TYPE, HEADERS.JSON);
}
next(manifest);
} catch (err) {
next(err);
}
}
);
2020-03-03 17:59:19 -05:00
route.get(
2023-01-31 11:09:38 -05:00
'/:package/-/:filename',
can('access'),
async function (req: $RequestExtend, res: $ResponseExtend, next): Promise<void> {
2023-01-31 11:09:38 -05:00
const { package: pkgName, filename } = req.params;
const abort = new AbortController();
try {
2023-01-31 11:09:38 -05:00
const stream = (await storage.getTarballNext(pkgName, filename, {
signal: abort.signal,
// TODO: review why this param
// enableRemote: true,
})) as any;
stream.on('content-length', (size) => {
res.header(HEADER_TYPE.CONTENT_LENGTH, size);
});
stream.once('error', (err) => {
res.locals.report_error(err);
next(err);
});
req.on('abort', () => {
debug('request aborted for %o', req.url);
abort.abort();
});
res.header(HEADERS.CONTENT_TYPE, HEADERS.OCTET_STREAM);
stream.pipe(res);
} catch (err: any) {
// console.log('catch API error request', err);
res.locals.report_error(err);
next(err);
}
}
);
2020-03-03 17:59:19 -05:00
}