Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | 3x 83x 22x 9x 13x 111x 3x 36x 36x 1x 35x 45x 3x 25x 7x 3x 4x 4x 3x 27x 3x 14x 14x 11x | import { createError } from "h3";
import type { EntryQuery, Query } from "#core/domain/content";
import {
DEFAULT_PER_PAGE,
isTermResource,
MAX_PAGE,
MAX_PER_PAGE,
MAX_SEARCH_LENGTH,
TERM_RESOURCES,
} from "#core/domain/content";
import { MalformedQueryError, UndefinedResourceError } from "#core/domain/errors";
const toBoundedInteger = (
value: number | undefined,
param: string,
max: number,
): number | undefined => {
if (value === undefined) return undefined;
if (!Number.isInteger(value) || value < 1 || value > max) {
throw createError(new MalformedQueryError(param, `an integer between 1 and ${max}`));
}
return value;
};
const toText = (value: string | undefined): string | undefined => value?.trim() || undefined;
// `search` is the one query axis whose key space is not small — bounding its length is not the same
// as bounding it, so a public deployment wants a rate limit at the edge as well.
const toSearch = (value: string | undefined): string | undefined => {
const search = toText(value);
if (search !== undefined && search.length > MAX_SEARCH_LENGTH) {
throw createError(
new MalformedQueryError("search", `at most ${MAX_SEARCH_LENGTH} characters`),
);
}
return search;
};
// Defaults are resolved rather than left undefined, so `{}` and `{ page: 1 }` key one cache entry
export const toQuery = (query: Query = {}): Query => ({
page: toBoundedInteger(query.page, "page", MAX_PAGE) ?? 1,
perPage: toBoundedInteger(query.perPage, "perPage", MAX_PER_PAGE) ?? DEFAULT_PER_PAGE,
slug: toText(query.slug),
search: toSearch(query.search),
});
const toTerm = (term: EntryQuery["term"]): EntryQuery["term"] => {
if (!term) return undefined;
if (!isTermResource(term.resource)) {
throw createError(new UndefinedResourceError(term.resource, [...TERM_RESOURCES]));
}
const id = toText(term.id);
if (!id) throw createError(new MalformedQueryError("term", "a taxonomy and a non-empty id"));
return { resource: term.resource, id };
};
export const toEntryQuery = (query: EntryQuery = {}): EntryQuery => ({
...toQuery(query),
term: toTerm(query.term),
author: toText(query.author),
});
export const toSlug = (slug: string): string => {
const text = toText(slug);
if (!text) throw createError(new MalformedQueryError("slug", "a non-empty string"));
return text;
};
|