Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions apps/web/e2e/tests/platform/rest-posts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,18 +107,11 @@ test.describe('REST posts: list and read', () => {
expect(page2.data.map((p: { id: string }) => p.id)).toEqual([first.id])
expect(page2.meta.pagination.hasMore).toBe(false)

// limit is clamped to at least 1; a non-numeric limit means 20.
const one = await expectJson(
await admin.api.get(`/api/v1/posts?boardId=${board.id}&limit=-5`),
200
)
expect(one.data).toHaveLength(1)
expect(one.meta.pagination.hasMore).toBe(true)
const all = await expectJson(
await admin.api.get(`/api/v1/posts?boardId=${board.id}&limit=abc`),
200
)
expect(all.data).toHaveLength(3)
// A limit below 1 or not a whole number is refused (400), not clamped.
for (const bad of ['-5', '0', 'abc']) {
const res = await admin.api.get(`/api/v1/posts?boardId=${board.id}&limit=${bad}`)
expect(res.status(), `limit=${bad}`).toBe(400)
}
await admin.api.dispose()
}
)
Expand Down
75 changes: 75 additions & 0 deletions apps/web/src/lib/server/domains/api/__tests__/request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest'
import { ValidationError } from '@/lib/shared/errors'
import { generateId } from '@quackback/ids'
import { parseCursor, parseLimit, parseOffset, readJsonBody } from '../request'

const post = (body: BodyInit | null) => new Request('http://t/', { method: 'POST', body })

describe('readJsonBody', () => {
it('parses a JSON body', async () => {
expect(await readJsonBody(post('{"a":1}'))).toEqual({ a: 1 })
})

it('is undefined when there is no body', async () => {
expect(await readJsonBody(post(null))).toBeUndefined()
expect(await readJsonBody(post(' '))).toBeUndefined()
})

it('refuses a body that is not JSON as a ValidationError', async () => {
for (const body of ['{"a":', 'not json', new Uint8Array([0xff, 0xfe, 0x00])]) {
const attempt = readJsonBody(post(body))
await expect(attempt).rejects.toBeInstanceOf(ValidationError)
await expect(attempt).rejects.toThrow('Request body must be valid JSON')
}
})
})

describe('parseLimit', () => {
const url = (query: string) => new URL(`http://t/?${query}`)

it('falls back when absent and caps at the max', () => {
expect(parseLimit(url(''))).toBe(20)
expect(parseLimit(url('limit='))).toBe(20)
expect(parseLimit(url(''), { fallback: 30 })).toBe(30)
expect(parseLimit(url('limit=7'))).toBe(7)
expect(parseLimit(url('limit=500'))).toBe(100)
expect(parseLimit(url('limit=50'), { max: 20 })).toBe(20)
})

it.each(['0', '-1', 'abc', '2.5', '1e2', ' 3'])('refuses limit=%s', (limit) => {
expect(() => parseLimit(url(`limit=${encodeURIComponent(limit)}`))).toThrow(
'limit must be a whole number of 1 or more'
)
})
})

describe('parseOffset', () => {
const url = (query: string) => new URL(`http://t/?${query}`)

it('is 0 when absent and takes any whole number', () => {
expect(parseOffset(url(''))).toBe(0)
expect(parseOffset(url('offset=0'))).toBe(0)
expect(parseOffset(url('offset=40'))).toBe(40)
})

it.each(['-1', 'abc', '1.5'])('refuses offset=%s', (offset) => {
expect(() => parseOffset(url(`offset=${offset}`))).toThrow(ValidationError)
})
})

describe('parseCursor', () => {
const url = (query: string) => new URL(`http://t/?${query}`)

it('is undefined when absent and takes any TypeID', () => {
expect(parseCursor(url(''))).toBeUndefined()
expect(parseCursor(url('cursor='))).toBeUndefined()
const id = generateId('changelog')
expect(parseCursor(url(`cursor=${id}`))).toBe(id)
const other = generateId('post')
expect(parseCursor(url(`cursor=${other}`))).toBe(other)
})

it.each(['garbage', 'not-an-id', 'post_123'])('refuses cursor=%s', (cursor) => {
expect(() => parseCursor(url(`cursor=${cursor}`))).toThrow('Invalid cursor format')
})
})
24 changes: 3 additions & 21 deletions apps/web/src/lib/server/domains/api/__tests__/responses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,27 +425,9 @@ describe('API Responses', () => {
expect(result.limit).toBe(100)
})

it('should use default for limit=0', () => {
// limit=0 is falsy, so it falls through to the default of 20
const url = new URL('https://example.com/api?limit=0')
const result = parsePaginationParams(url)

expect(result.limit).toBe(20)
})

it('should enforce minimum limit of 1', () => {
// Negative numbers are capped to 1 by Math.max
const url = new URL('https://example.com/api?limit=-5')
const result = parsePaginationParams(url)

expect(result.limit).toBe(1)
})

it('should handle invalid limit gracefully', () => {
const url = new URL('https://example.com/api?limit=invalid')
const result = parsePaginationParams(url)

expect(result.limit).toBe(20)
it.each(['0', '-5', 'invalid'])('refuses limit=%s as a ValidationError', (limit) => {
const url = new URL(`https://example.com/api?limit=${limit}`)
expect(() => parsePaginationParams(url)).toThrow('limit must be a whole number of 1 or more')
})
})

Expand Down
55 changes: 55 additions & 0 deletions apps/web/src/lib/server/domains/api/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Reading what a REST caller sent: the JSON body and the paging parameters.
* Input the caller got wrong throws a ValidationError, which every route's
* handleDomainError answers with a 400, never a 500.
*/
import { isValidTypeId } from '@quackback/ids'
import { ValidationError } from '@/lib/shared/errors'

/**
* The request body parsed as JSON, or undefined when there is no body (the
* route's schema then says what was missing).
*/
export async function readJsonBody(request: Request): Promise<unknown> {
const text = await request.text()
if (!text.trim()) return undefined
try {
return JSON.parse(text)
} catch {
throw new ValidationError('VALIDATION_ERROR', 'Request body must be valid JSON')
}
}

/**
* `?cursor=`: the id of the last row on the previous page. Anything that is
* not a TypeID is a 400; a TypeID that names no row pages from the start.
*/
export function parseCursor(url: URL): string | undefined {
const cursor = url.searchParams.get('cursor')
if (!cursor) return undefined
if (!isValidTypeId(cursor)) throw new ValidationError('VALIDATION_ERROR', 'Invalid cursor format')
return cursor
}

/** A query parameter that must be a whole number of at least `min`, or absent. */
function wholeNumberParam(url: URL, name: string, min: number): number | undefined {
const raw = url.searchParams.get(name)
if (raw === null || raw === '') return undefined
if (!/^\d+$/.test(raw) || Number(raw) < min) {
throw new ValidationError(
'VALIDATION_ERROR',
`${name} must be a whole number of ${min} or more`
)
}
return Number(raw)
}

/** `?limit=`: a whole number from 1, `fallback` when absent, capped at `max`. */
export function parseLimit(url: URL, { fallback = 20, max = 100 } = {}): number {
return Math.min(wholeNumberParam(url, 'limit', 1) ?? fallback, max)
}

/** `?offset=`: a whole number from 0, 0 when absent. */
export function parseOffset(url: URL): number {
return wholeNumberParam(url, 'offset', 0) ?? 0
}
7 changes: 2 additions & 5 deletions apps/web/src/lib/server/domains/api/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { TierLimitError } from '@/lib/server/errors/tier-limit-error'
import { logger } from '@/lib/server/logger'
import { getLogContext } from '@/lib/server/log-context'
import { parseLimit } from './request'

const log = logger.child({ component: 'api' })

Expand Down Expand Up @@ -291,11 +292,7 @@ export function parsePaginationParams(url: URL): {
cursor?: string
limit: number
} {
const cursor = url.searchParams.get('cursor') ?? undefined
const limitParam = url.searchParams.get('limit')
const limit = Math.min(Math.max(parseInt(limitParam || '20', 10) || 20, 1), 100)

return { cursor, limit }
return { cursor: url.searchParams.get('cursor') ?? undefined, limit: parseLimit(url) }
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ function compiledWhere(callIndex: number): string {

const mockFeedbackFindFirst = vi.fn()
const mockFeedbackFindMany = vi.fn()
const mockArticleFindFirst = vi.fn()

/** Rows the guarded reason UPDATE reports back; [] models "no row matched". */
let updateReturningRows: unknown[] = []
Expand All @@ -43,7 +44,10 @@ vi.mock('@/lib/server/db', async (importOriginal) => ({
findMany: (...args: unknown[]) => mockFeedbackFindMany(...args),
},
helpCenterCategories: { findFirst: vi.fn() },
helpCenterArticles: { findFirst: vi.fn(), findMany: vi.fn() },
helpCenterArticles: {
findFirst: (...args: unknown[]) => mockArticleFindFirst(...args),
findMany: vi.fn(),
},
principal: { findFirst: vi.fn() },
},
insert: vi.fn(() => {
Expand Down Expand Up @@ -94,6 +98,7 @@ beforeEach(async () => {
updateReturningRows = []
mockFeedbackFindFirst.mockResolvedValue(null)
mockFeedbackFindMany.mockResolvedValue([])
mockArticleFindFirst.mockResolvedValue({ id: 'kb_article_1' })

const mod = await import('../help-center.article-feedback.service')
recordArticleFeedback = mod.recordArticleFeedback
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* An article write that names a category or article that is not there is the
* caller's mistake: a typed error, never the foreign key violation (a 500)
* the insert would hit.
*/
import { afterAll, afterEach, beforeEach, expect, it, vi } from 'vitest'
import {
createId,
type KbArticleId,
type KbCategoryId,
type PrincipalId,
type UserId,
} from '@quackback/ids'
import { createDbTestFixture, testDb } from '@/lib/server/__tests__/db-test-fixture'
import { helpCenterCategories, principal, user } from '@/lib/server/db'
import { NotFoundError, ValidationError } from '@/lib/shared/errors'

vi.mock('@/lib/server/db', async (original) => ({
...(await original<typeof import('@/lib/server/db')>()),
db: (await import('@/lib/server/__tests__/db-test-fixture')).testDb,
}))
vi.mock('../help-center-embedding.service', () => ({
generateArticleEmbedding: async () => undefined,
}))

import { createArticle, updateArticle } from '../help-center.article.service'
import { recordArticleFeedback } from '../help-center.article-feedback.service'

const fixture = await createDbTestFixture({
probe: async (db) => {
await db.select({ id: helpCenterCategories.id }).from(helpCenterCategories).limit(0)
},
})

let author: PrincipalId
beforeEach(async () => {
expect(fixture.available).toBe(true)
await fixture.begin()
const userId = createId('user') as UserId
author = createId('principal') as PrincipalId
await testDb.insert(user).values({ id: userId, name: 'Ada', email: `${userId}@example.com` })
await testDb
.insert(principal)
.values({ id: author, userId, role: 'admin', type: 'user', createdAt: new Date() })
})
afterEach(fixture.rollback)
afterAll(fixture.close)

const category = async (values: { deletedAt?: Date } = {}) => {
const [row] = await testDb
.insert(helpCenterCategories)
.values({ name: 'Docs', slug: `docs-${createId('kb_category')}`, ...values })
.returning()
return row!.id
}

it('refuses to file an article in a category that does not exist or was deleted', async () => {
for (const categoryId of [createId('kb_category'), await category({ deletedAt: new Date() })]) {
const attempt = createArticle({ title: 'Setup', content: 'x', categoryId }, author)
await expect(attempt).rejects.toBeInstanceOf(ValidationError)
await expect(attempt).rejects.toThrow('Category not found')
}
})

it('refuses to move an article to a category that does not exist', async () => {
const article = await createArticle(
{ title: 'Setup', content: 'x', categoryId: await category() },
author
)
const attempt = updateArticle(article.id, { categoryId: createId('kb_category') as KbCategoryId })
await expect(attempt).rejects.toBeInstanceOf(ValidationError)
await expect(attempt).rejects.toThrow('Category not found')
})

it('feedback on an article that does not exist is not found', async () => {
const attempt = recordArticleFeedback(createId('kb_article') as KbArticleId, true, author)
await expect(attempt).rejects.toBeInstanceOf(NotFoundError)
await expect(attempt).rejects.toMatchObject({ code: 'ARTICLE_NOT_FOUND' })
})
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from '@/lib/server/db'
import { createId } from '@quackback/ids'
import type { KbArticleFeedbackId, KbArticleId, PrincipalId } from '@quackback/ids'
import { ValidationError } from '@/lib/shared/errors'
import { NotFoundError, ValidationError } from '@/lib/shared/errors'
import { ARTICLE_FEEDBACK_REASON_MAX_LENGTH } from '@/lib/shared/schemas/help-center'
import { logger } from '@/lib/server/logger'

Expand All @@ -30,6 +30,12 @@ export async function recordArticleFeedback(
principalId?: PrincipalId | null
): Promise<KbArticleFeedbackId> {
return db.transaction(async (tx) => {
const article = await tx.query.helpCenterArticles.findFirst({
where: eq(helpCenterArticles.id, articleId),
columns: { id: true },
})
if (!article) throw new NotFoundError('ARTICLE_NOT_FOUND', `Article ${articleId} not found`)

if (principalId) {
const existing = await tx.query.helpCenterArticleFeedback.findFirst({
where: and(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,15 @@ const findArticleSlugConflict = (slug: string) =>
columns: { id: true },
})

/** An article can only be filed in a category that exists and is not deleted. */
async function assertLiveCategory(categoryId: KbCategoryId): Promise<void> {
const category = await db.query.helpCenterCategories.findFirst({
where: and(eq(helpCenterCategories.id, categoryId), isNull(helpCenterCategories.deletedAt)),
columns: { id: true },
})
if (!category) throw new ValidationError('VALIDATION_ERROR', 'Category not found')
}

export async function createArticle(
input: CreateArticleInput,
principalId: PrincipalId,
Expand Down Expand Up @@ -250,8 +259,9 @@ export async function createArticle(
})
// No category picked (a first article in an empty help center): file it
// under General rather than refusing the save.
const categoryId =
(input.categoryId?.trim() as KbCategoryId) || (await ensureDefaultHelpCategory())
const chosen = input.categoryId?.trim() as KbCategoryId | undefined
if (chosen) await assertLiveCategory(chosen)
const categoryId = chosen || (await ensureDefaultHelpCategory())

const [article] = await db
.insert(helpCenterArticles)
Expand Down Expand Up @@ -295,7 +305,10 @@ export async function updateArticle(
updateData.contentJson = contentJson
updateData.content = projectContentJsonToMarkdown(contentJson, input.content?.trim() ?? '')
}
if (input.categoryId !== undefined) updateData.categoryId = input.categoryId as KbCategoryId
if (input.categoryId !== undefined) {
await assertLiveCategory(input.categoryId as KbCategoryId)
updateData.categoryId = input.categoryId as KbCategoryId
}
if (input.slug !== undefined)
updateData.slug = await uniqueHelpCenterSlug(
input.slug.trim(),
Expand Down
Loading
Loading