@beechcms/api 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,59 +1,59 @@
1
- import type { Context } from 'hono'
2
- import { cleanStr } from '../shared/query-utils'
3
- import { checkPublicOperation } from './access-policy'
4
- import { publicProblem, internalErrorDetail } from './problem-details'
5
- import { resolveEdgeCache, withCachedResponse } from './cache-utils'
6
- import { readSingleEntry } from './read-single'
7
- import { readListEntries } from './read-list'
8
- import { AppEnv } from '../types'
9
-
10
- export async function publicReadHandler(context: Context<AppEnv>) {
11
- const seedSlug = context.req.param('seed') ?? ''
12
- const seed = context.get('getSeed')(seedSlug)
13
- if (!seed) {
14
- const available = context.get('seedRegistry').all().map(s => s.slug).join(', ')
15
- return publicProblem(context, {
16
- type: 'seed-not-found',
17
- title: 'Seed Not Found',
18
- status: 404,
19
- detail: `The content type '${seedSlug}' does not exist. Available types: ${available}.`,
20
- })
21
- }
22
-
23
- const access = checkPublicOperation(seed, 'read')
24
- if (!access.ok) {
25
- return publicProblem(context, { type: 'operation-not-allowed', title: access.error.error, status: 403, detail: access.error.message })
26
- }
27
-
28
- const edgeCache = resolveEdgeCache(context)
29
- const cacheKey = context.req.raw
30
- if (edgeCache) {
31
- const hit = await edgeCache.cache.match(cacheKey)
32
- if (hit) return hit
33
- }
34
-
35
- const query = context.req.query()
36
- const id = cleanStr(query.id)
37
- const slug = cleanStr(query.slug)
38
- const publishedOnly = context.env.PUBLIC_PUBLISHED_ONLY !== 'false'
39
- const repository = context.get('repository')
40
-
41
- try {
42
- if (id || slug) {
43
- const result = await readSingleEntry({ seed, seedSlug, repository, id, slug, publishedOnly, fieldsParam: query.fields })
44
- if (!result.ok) {
45
- return publicProblem(context, { type: 'entry-not-found', title: 'Not Found', status: 404, detail: result.detail })
46
- }
47
- return withCachedResponse(edgeCache, cacheKey, context.json({ data: result.data, meta: result.meta }, 200))
48
- }
49
-
50
- const result = await readListEntries({ seed, seedSlug, repository, query, publishedOnly })
51
- return withCachedResponse(edgeCache, cacheKey, context.json(result, 200))
52
- } catch (error) {
53
- if (error instanceof Error && error.message.startsWith('Invalid filter:')) {
54
- return publicProblem(context, { type: 'invalid-filter', title: 'Bad Request', status: 400, detail: error.message })
55
- }
56
- console.error('Public read error:', error)
57
- return publicProblem(context, { type: 'internal-server-error', title: 'Internal Server Error', status: 500, detail: internalErrorDetail(context.env, error) })
58
- }
59
- }
1
+ import type { Context } from 'hono'
2
+ import { cleanStr } from '../shared/query-utils'
3
+ import { checkPublicOperation } from './access-policy'
4
+ import { publicProblem, internalErrorDetail } from './problem-details'
5
+ import { resolveEdgeCache, withCachedResponse } from './cache-utils'
6
+ import { readSingleEntry } from './read-single'
7
+ import { readListEntries } from './read-list'
8
+ import { AppEnv } from '../types'
9
+
10
+ export async function publicReadHandler(context: Context<AppEnv>) {
11
+ const seedSlug = context.req.param('seed') ?? ''
12
+ const seed = context.get('getSeed')(seedSlug)
13
+ if (!seed) {
14
+ const available = context.get('seedRegistry').all().map(s => s.slug).join(', ')
15
+ return publicProblem(context, {
16
+ type: 'seed-not-found',
17
+ title: 'Seed Not Found',
18
+ status: 404,
19
+ detail: `The content type '${seedSlug}' does not exist. Available types: ${available}.`,
20
+ })
21
+ }
22
+
23
+ const access = checkPublicOperation(seed, 'read')
24
+ if (!access.ok) {
25
+ return publicProblem(context, { type: 'operation-not-allowed', title: access.error.error, status: 403, detail: access.error.message })
26
+ }
27
+
28
+ const edgeCache = resolveEdgeCache(context)
29
+ const cacheKey = context.req.raw
30
+ if (edgeCache) {
31
+ const hit = await edgeCache.cache.match(cacheKey)
32
+ if (hit) return hit
33
+ }
34
+
35
+ const query = context.req.query()
36
+ const id = cleanStr(query.id)
37
+ const slug = cleanStr(query.slug)
38
+ const publishedOnly = context.env.PUBLIC_PUBLISHED_ONLY !== 'false'
39
+ const repository = context.get('repository')
40
+
41
+ try {
42
+ if (id || slug) {
43
+ const result = await readSingleEntry({ seed, seedSlug, repository, id, slug, publishedOnly, fieldsParam: query.fields })
44
+ if (!result.ok) {
45
+ return publicProblem(context, { type: 'entry-not-found', title: 'Not Found', status: 404, detail: result.detail })
46
+ }
47
+ return withCachedResponse(edgeCache, cacheKey, context.json({ data: result.data, meta: result.meta }, 200))
48
+ }
49
+
50
+ const result = await readListEntries({ seed, seedSlug, repository, query, publishedOnly })
51
+ return withCachedResponse(edgeCache, cacheKey, context.json(result, 200))
52
+ } catch (error) {
53
+ if (error instanceof Error && error.message.startsWith('Invalid filter:')) {
54
+ return publicProblem(context, { type: 'invalid-filter', title: 'Bad Request', status: 400, detail: error.message })
55
+ }
56
+ console.error('Public read error:', error)
57
+ return publicProblem(context, { type: 'internal-server-error', title: 'Internal Server Error', status: 500, detail: internalErrorDetail(context.env, error) })
58
+ }
59
+ }
@@ -1,50 +1,50 @@
1
- import type { Seed, ContentRepository } from '@beechcms/core'
2
- import { cleanStr } from '../shared/query-utils'
3
- import { toFlatPublicEntry } from './entry-projection'
4
- import { buildPublicListMeta } from './response-builder'
5
- import { parsePublicFilter, parsePublicPagination, parseLatestCount, toEngineFilters } from './query-builder'
6
-
7
- type ReadListInput = {
8
- seed: Seed
9
- seedSlug: string
10
- repository: ContentRepository
11
- query: Record<string, string | undefined>
12
- publishedOnly: boolean
13
- }
14
-
15
- export async function readListEntries(input: ReadListInput) {
16
- const { seed, seedSlug, repository, query, publishedOnly } = input
17
-
18
- const parsedFilter = parsePublicFilter(query.filter)
19
- const allMode = cleanStr(query.all)?.toLowerCase() === 'true'
20
- const latestMode = cleanStr(query.latest) !== null
21
- const latestCount = latestMode ? parseLatestCount(query.latest ?? '') : null
22
- const pagination = allMode ? { page: 1, limit: 100 } : parsePublicPagination(query)
23
- const offset = (pagination.page - 1) * pagination.limit
24
- const search = cleanStr(query.search) ?? ''
25
- const engineFilters = toEngineFilters(seed, parsedFilter)
26
- const sortBy = cleanStr(query.orderBy) ?? 'created_at'
27
- const sortDir = (cleanStr(query.orderDir) ?? 'desc').toLowerCase() === 'asc' ? 'ASC' : 'DESC'
28
-
29
- const { items, total } = await repository.findMany(seed, {
30
- filters: engineFilters,
31
- search: search || undefined,
32
- status: publishedOnly ? 'published' : null,
33
- pagination: {
34
- limit: latestMode ? (latestCount ?? 10) : pagination.limit,
35
- offset: latestMode ? 0 : offset,
36
- },
37
- orderBy: latestMode ? { column: 'created_at', dir: 'DESC' } : { column: sortBy, dir: sortDir },
38
- })
39
-
40
- const data = items.map(item => toFlatPublicEntry(item, seed, query.fields))
41
-
42
- if (latestMode) {
43
- return { data, meta: { total, returned: data.length, seed: seedSlug } }
44
- }
45
-
46
- return {
47
- data,
48
- meta: buildPublicListMeta({ total, page: pagination.page, limit: pagination.limit, returned: data.length, seed: seedSlug }),
49
- }
50
- }
1
+ import type { Seed, ContentRepository } from '@beechcms/core'
2
+ import { cleanStr } from '../shared/query-utils'
3
+ import { toFlatPublicEntry } from './entry-projection'
4
+ import { buildPublicListMeta } from './response-builder'
5
+ import { parsePublicFilter, parsePublicPagination, parseLatestCount, toEngineFilters } from './query-builder'
6
+
7
+ type ReadListInput = {
8
+ seed: Seed
9
+ seedSlug: string
10
+ repository: ContentRepository
11
+ query: Record<string, string | undefined>
12
+ publishedOnly: boolean
13
+ }
14
+
15
+ export async function readListEntries(input: ReadListInput) {
16
+ const { seed, seedSlug, repository, query, publishedOnly } = input
17
+
18
+ const parsedFilter = parsePublicFilter(query.filter)
19
+ const allMode = cleanStr(query.all)?.toLowerCase() === 'true'
20
+ const latestMode = cleanStr(query.latest) !== null
21
+ const latestCount = latestMode ? parseLatestCount(query.latest ?? '') : null
22
+ const pagination = allMode ? { page: 1, limit: 100 } : parsePublicPagination(query)
23
+ const offset = (pagination.page - 1) * pagination.limit
24
+ const search = cleanStr(query.search) ?? ''
25
+ const engineFilters = toEngineFilters(seed, parsedFilter)
26
+ const sortBy = cleanStr(query.orderBy) ?? 'created_at'
27
+ const sortDir = (cleanStr(query.orderDir) ?? 'desc').toLowerCase() === 'asc' ? 'ASC' : 'DESC'
28
+
29
+ const { items, total } = await repository.findMany(seed, {
30
+ filters: engineFilters,
31
+ search: search || undefined,
32
+ status: publishedOnly ? 'published' : null,
33
+ pagination: {
34
+ limit: latestMode ? (latestCount ?? 10) : pagination.limit,
35
+ offset: latestMode ? 0 : offset,
36
+ },
37
+ orderBy: latestMode ? { column: 'created_at', dir: 'DESC' } : { column: sortBy, dir: sortDir },
38
+ })
39
+
40
+ const data = items.map(item => toFlatPublicEntry(item, seed, query.fields))
41
+
42
+ if (latestMode) {
43
+ return { data, meta: { total, returned: data.length, seed: seedSlug } }
44
+ }
45
+
46
+ return {
47
+ data,
48
+ meta: buildPublicListMeta({ total, page: pagination.page, limit: pagination.limit, returned: data.length, seed: seedSlug }),
49
+ }
50
+ }
@@ -1,44 +1,44 @@
1
- import { EntryNotFoundError } from '@beechcms/core'
2
- import type { Seed, ContentRepository } from '@beechcms/core'
3
- import { toFlatPublicEntry } from './entry-projection'
4
- import { buildPublicSingleMeta } from './response-builder'
5
-
6
- type ReadSingleInput = {
7
- seed: Seed
8
- seedSlug: string
9
- repository: ContentRepository
10
- id: string | null
11
- slug: string | null
12
- publishedOnly: boolean
13
- fieldsParam?: string
14
- }
15
-
16
- export type ReadSingleResult =
17
- | { ok: true; data: Record<string, unknown>; meta: { seed: string } }
18
- | { ok: false; detail: string }
19
-
20
- export async function readSingleEntry(input: ReadSingleInput): Promise<ReadSingleResult> {
21
- const { seed, seedSlug, repository, id, slug, publishedOnly, fieldsParam } = input
22
- const label = id ?? slug!
23
-
24
- try {
25
- const entry = id
26
- ? await repository.findById(seed, id)
27
- : await repository.findBySlug(seed, slug!)
28
-
29
- if (publishedOnly && entry.status !== 'published') {
30
- return { ok: false, detail: `Entry '${label}' not found or not published.` }
31
- }
32
-
33
- return {
34
- ok: true,
35
- data: toFlatPublicEntry(entry, seed, fieldsParam),
36
- meta: buildPublicSingleMeta(seedSlug),
37
- }
38
- } catch (error) {
39
- if (error instanceof EntryNotFoundError) {
40
- return { ok: false, detail: `Entry '${label}' not found for content type '${seedSlug}'.` }
41
- }
42
- throw error
43
- }
44
- }
1
+ import { EntryNotFoundError } from '@beechcms/core'
2
+ import type { Seed, ContentRepository } from '@beechcms/core'
3
+ import { toFlatPublicEntry } from './entry-projection'
4
+ import { buildPublicSingleMeta } from './response-builder'
5
+
6
+ type ReadSingleInput = {
7
+ seed: Seed
8
+ seedSlug: string
9
+ repository: ContentRepository
10
+ id: string | null
11
+ slug: string | null
12
+ publishedOnly: boolean
13
+ fieldsParam?: string
14
+ }
15
+
16
+ export type ReadSingleResult =
17
+ | { ok: true; data: Record<string, unknown>; meta: { seed: string } }
18
+ | { ok: false; detail: string }
19
+
20
+ export async function readSingleEntry(input: ReadSingleInput): Promise<ReadSingleResult> {
21
+ const { seed, seedSlug, repository, id, slug, publishedOnly, fieldsParam } = input
22
+ const label = id ?? slug!
23
+
24
+ try {
25
+ const entry = id
26
+ ? await repository.findById(seed, id)
27
+ : await repository.findBySlug(seed, slug!)
28
+
29
+ if (publishedOnly && entry.status !== 'published') {
30
+ return { ok: false, detail: `Entry '${label}' not found or not published.` }
31
+ }
32
+
33
+ return {
34
+ ok: true,
35
+ data: toFlatPublicEntry(entry, seed, fieldsParam),
36
+ meta: buildPublicSingleMeta(seedSlug),
37
+ }
38
+ } catch (error) {
39
+ if (error instanceof EntryNotFoundError) {
40
+ return { ok: false, detail: `Entry '${label}' not found for content type '${seedSlug}'.` }
41
+ }
42
+ throw error
43
+ }
44
+ }
@@ -53,7 +53,7 @@ export function decodeCursor(cursor: string): { rank: number; entryId: string }
53
53
  const sep = decoded.lastIndexOf(":")
54
54
  if (sep === -1) return null
55
55
  return {
56
- rank: parseFloat(decoded.slice(0, sep)),
56
+ rank: Number.parseFloat(decoded.slice(0, sep)),
57
57
  entryId: decoded.slice(sep + 1),
58
58
  }
59
59
  } catch {
package/src/search.ts CHANGED
@@ -18,7 +18,7 @@ searchRouter.get("/", async (c) => {
18
18
  const queryText = c.req.query("q")?.trim() ?? ""
19
19
  const schemaSlug = c.req.query("schema_slug") ?? null
20
20
  const status = c.req.query("status") ?? null
21
- const rawLimit = parseInt(c.req.query("limit") ?? "20", 10)
21
+ const rawLimit = Number.parseInt(c.req.query("limit") ?? "20", 10)
22
22
  const limit = Math.min(Math.max(rawLimit, 1), 50)
23
23
  const cursor = c.req.query("cursor") ?? null
24
24