config: refactor schemas into a separate file

This commit is contained in:
Alex Gleason 2025-02-15 16:37:33 -06:00
parent 1636601bfe
commit 5f6cdaf7d5
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
3 changed files with 29 additions and 11 deletions

View file

@ -1,11 +1,11 @@
import os from 'node:os';
import ISO6391, { type LanguageCode } from 'iso-639-1';
import { getPublicKey, nip19 } from 'nostr-tools';
import { z } from 'zod';
import { decodeBase64 } from '@std/encoding/base64';
import { encodeBase64Url } from '@std/encoding/base64url';
import { getEcdsaPublicKey } from './utils/crypto.ts';
import { optionalBooleanSchema, optionalNumberSchema } from './utils/schema.ts';
/** Ditto application-wide configuration. */
export class DittoConfig {
@ -462,16 +462,6 @@ export class DittoConfig {
}
}
const optionalBooleanSchema = z
.enum(['true', 'false'])
.optional()
.transform((value) => value !== undefined ? value === 'true' : undefined);
const optionalNumberSchema = z
.string()
.optional()
.transform((value) => value !== undefined ? Number(value) : undefined);
function mergePaths(base: string, path: string) {
const url = new URL(
path.startsWith('/') ? path : new URL(path).pathname,

View file

@ -0,0 +1,17 @@
import { assertEquals, assertThrows } from '@std/assert';
import { optionalBooleanSchema, optionalNumberSchema } from './schema.ts';
Deno.test('optionalBooleanSchema', () => {
assertEquals(optionalBooleanSchema.parse('true'), true);
assertEquals(optionalBooleanSchema.parse('false'), false);
assertEquals(optionalBooleanSchema.parse(undefined), undefined);
assertThrows(() => optionalBooleanSchema.parse('invalid'));
});
Deno.test('optionalNumberSchema', () => {
assertEquals(optionalNumberSchema.parse('123'), 123);
assertEquals(optionalNumberSchema.parse('invalid'), NaN); // maybe this should throw?
assertEquals(optionalNumberSchema.parse(undefined), undefined);
});

View file

@ -0,0 +1,11 @@
import { z } from 'zod';
export const optionalBooleanSchema = z
.enum(['true', 'false'])
.optional()
.transform((value) => value !== undefined ? value === 'true' : undefined);
export const optionalNumberSchema = z
.string()
.optional()
.transform((value) => value !== undefined ? Number(value) : undefined);