refactor: reorganize files in commons package

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2023-05-29 18:37:06 +02:00
parent c9b98f6185
commit 4d9792bcb9
23 changed files with 94 additions and 69 deletions

View file

@ -0,0 +1,35 @@
/*
* SPDX-FileCopyrightText: 2023 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { MissingTrailingSlashError, WrongProtocolError } from './errors.js'
import { Optional } from '@mrdrogdrog/optional'
/**
* Parses the given string as URL
*
* @param {String | undefined} url the raw url
* @return An {@link Optional} that contains the parsed URL or is empty if the raw value isn't a valid URL
* @throws WrongProtocolError if the protocol of the URL isn't either http nor https
* @throws MissingTrailingSlashError if the URL has a path that doesn't end with a trailing slash
*/
export function parseUrl(url: string | undefined): Optional<URL> {
return createOptionalUrl(url)
.guard(
(value) => value.protocol === 'https:' || value.protocol === 'http:',
() => new WrongProtocolError()
)
.guard(
(value) => value.pathname.endsWith('/'),
() => new MissingTrailingSlashError()
)
}
function createOptionalUrl(url: string | undefined): Optional<URL> {
try {
return Optional.ofNullable(url).map((value) => new URL(value))
} catch (error) {
return Optional.empty()
}
}