Skip to content

Commit db4728f

Browse files
committed
fix: config byte parsing
resolves #42
1 parent e56d700 commit db4728f

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

packages/api/src/config.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { loadConfig } from '@ryanke/venera';
2-
import bytes from 'bytes';
32
import c from 'chalk';
43
import { randomBytes } from 'crypto';
54
import dedent from 'dedent';
@@ -9,14 +8,15 @@ import z, { any, array, boolean, number, record, strictObject, string, union } f
98
import { fromZodError } from 'zod-validation-error';
109
import { expandMime } from './helpers/expand-mime.js';
1110
import { HostService } from './modules/host/host.service.js';
11+
import { parseBytes } from './helpers/parse-bytes.js';
1212

1313
export type MicroHost = ReturnType<typeof enhanceHost>;
1414

1515
const schema = strictObject({
1616
databaseUrl: string().startsWith('postgresql://'),
1717
secret: string().min(6),
1818
inquiries: string().email(),
19-
uploadLimit: string().transform(bytes.parse),
19+
uploadLimit: string().transform(parseBytes),
2020
maxPasteLength: number().default(500000),
2121
allowTypes: z
2222
.union([array(string()), string()])
@@ -25,7 +25,7 @@ const schema = strictObject({
2525
storagePath: string(),
2626
restrictFilesToHost: boolean().default(true),
2727
purge: strictObject({
28-
overLimit: string().transform(bytes.parse),
28+
overLimit: string().transform(parseBytes),
2929
afterTime: string().transform(ms),
3030
}).optional(),
3131
email: strictObject({
@@ -36,7 +36,7 @@ const schema = strictObject({
3636
strictObject({
3737
from: union([array(string()), string()]).transform((value) => new Set(expandMime(value))),
3838
to: string(),
39-
minSize: string().transform(bytes.parse).optional(),
39+
minSize: string().transform(parseBytes).optional(),
4040
}),
4141
).optional(),
4242
hosts: array(
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const UNITS = new Map<string, number>([
2+
['B', 1],
3+
['KB', 1024],
4+
['K', 1024],
5+
['MB', 1024 * 1024],
6+
['M', 1024 * 1024],
7+
['GB', 1024 * 1024 * 1024],
8+
['G', 1024 * 1024 * 1024],
9+
]);
10+
11+
const PATTERN = new RegExp(`(?<value>[0-9]+(?:\\.[0-9]+)?)\\s*(?<unit>${[...UNITS.keys()].join('|')})`, 'i')
12+
13+
export const parseBytes = (input:string) => {
14+
const match = input.match(PATTERN)
15+
if (!match) {
16+
throw new Error('Invalid byte format')
17+
}
18+
19+
const value = +match.groups!.value
20+
const unit = match.groups!.unit.toUpperCase()
21+
const unitMultiplier = UNITS.get(unit)
22+
23+
if (!unitMultiplier) {
24+
throw new Error('Invalid byte format')
25+
}
26+
27+
return value * unitMultiplier
28+
}

0 commit comments

Comments
 (0)